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(model-hub): hosted tools v2 B2+C2 - image_generate on the engine's images endpoints, and Vibey's image tool (#2652)

Call White073746d4c81d
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index 309eb56f0..cef57b3cf 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -128,6 +128,7 @@ from core.agent_core.harness.projection import (
from core.agent_core.harness.store import ContextEntry, EntryKind, TranscriptStore
from core.agent_core.messages import (
AssistantMessage,
+ HostedImage,
Message,
Origin,
ToolCallBlock,
@@ -346,6 +347,9 @@ class Agent:
# The run's attempt ledger (C-9): every model attempt, in order.
self._attempts: list[_Attempt] = []
self._refusals = _Refusals()
+ # The images the run's committed tool results generated, which its final delivers: a reply even without text
+ # (``has_reply``). Read from the committed rows, so a result another writer settled counts as it committed.
+ self._generated_images: list[HostedImage] = []
# When each upstream prompt cache was last used in this Agent: the end of its latest model call, by the provider
# and model that served it (``_cache_of``, C-9 section 3).
self._last_model_at: dict[tuple[str, str], float] = {}
@@ -526,14 +530,21 @@ class Agent:
except ProjectionError as error:
raise ProviderProtocolViolation(f"Provider protocol violation: {error}") from error
- async def _response(self, message: AssistantMessage, *, final: bool) -> ContextEntry:
+ async def _response(self, message: AssistantMessage, *, final: bool, replied: Optional[bool] = None) -> ContextEntry:
self._validate_response(message)
await self._save_state()
# The attempt this response answered: the ledger's latest conversation attempt (the C-9 anchor).
attempt = next((item for item in reversed(self._attempts) if item.purpose == "conversation"), None)
facts = {"request": request_facts(attempt.request)} if self.context is not None and attempt else {}
row = await self._scope.call(
- lambda: self.store.append_response(self.session_id, deepcopy(message), final=final, **facts),
+ lambda: self.store.append_response(
+ self.session_id,
+ deepcopy(message),
+ final=final,
+ replied=replied,
+ images=tuple(self._generated_images) if final else (),
+ **facts,
+ ),
interruptible=False,
)
if attempt is not None:
@@ -560,6 +571,7 @@ class Agent:
self._turn_inputs = set()
self._attempts = []
self._refusals = _Refusals()
+ self._generated_images = []
loaded = True
system = self.system
self._run_tools = dict(self._tools)
@@ -931,10 +943,10 @@ class Agent:
await self._audit("attempt", payload)
async def _commit_model_message(
- self, message: AssistantMessage, emit: Callable[..., Awaitable[None]]
+ self, message: AssistantMessage, emit: Callable[..., Awaitable[None]], *, replied: bool
) -> tuple[ContextEntry, bool]:
"""Commit the response: its row, and whether it is final. Finality and queued-input admission share one lock
- with the commit."""
+ with the commit. ``replied`` is the run's decision whether it replies, which the store takes as given."""
pending: list[tuple[AgentInput, bool]] = []
consumed: list[tuple[AgentInput, bool]] = []
failed = message.stop_reason in {"error", "aborted"}
@@ -948,7 +960,7 @@ class Agent:
final = not message.tool_calls and not pending and not failed
if final or failed:
self._open = False
- row = await self._response(message, final=final)
+ row = await self._response(message, final=final, replied=replied)
for item, is_steer in pending:
await self._consume(item)
(self._steers if is_steer else self._follow_ups).popleft()
@@ -1001,8 +1013,10 @@ class Agent:
"local" if aborted else "source",
cause=decided,
)
- response, final = await self._commit_model_message(message, emit)
- empty_reply = final and not has_reply(message)
+ # Decided once: the empty-reply test, the row's type and settlement all take it (``has_reply``).
+ replied = has_reply(message, generated_images=bool(self._generated_images))
+ response, final = await self._commit_model_message(message, emit, replied=replied)
+ empty_reply = final and not replied
truncated_reply = final and message.stop_reason == "length"
if empty_reply or truncated_reply:
decided = self._outcome.primary("error")
@@ -1207,6 +1221,10 @@ class Agent:
interruptible=False,
)
self._rows.append(row)
+ # The committed result, which a settlement race may have taken from another writer, not this execution's.
+ committed = row.message.hosted if isinstance(row.message, ToolResultMessage) else None
+ if committed is not None and committed.record.status == "completed":
+ self._generated_images.extend(committed.record.images or ())
await emit(
ToolFinished,
tool_call_id=call.id,
diff --git a/core/agent_core/harness/store.py b/core/agent_core/harness/store.py
index 0d82a816e..c98455eff 100644
--- a/core/agent_core/harness/store.py
+++ b/core/agent_core/harness/store.py
@@ -13,7 +13,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal, Mapping, Optional, Protocol, Sequence
-from core.agent_core.messages import AssistantMessage, Message, ToolResultMessage, UserMessage
+from core.agent_core.messages import AssistantMessage, HostedImage, Message, ToolResultMessage, UserMessage
EntryKind = Literal["input", "response", "tool_result", "compaction", "context_edit", "agent_state"]
@@ -49,11 +49,21 @@ class TranscriptStore(Protocol):
...
async def append_response(
- self, session_id: str, message: AssistantMessage, *, final: bool, request: Optional[Mapping[str, Any]] = None
+ self,
+ session_id: str,
+ message: AssistantMessage,
+ *,
+ final: bool,
+ request: Optional[Mapping[str, Any]] = None,
+ replied: Optional[bool] = None,
+ images: Sequence[HostedImage] = (),
) -> ContextEntry:
"""Commit a response; ``request`` (C-9 ``ModelResponse.request``) is stored with it and read back in ``payload``.
- The loop passes ``request`` only when context management is on.
+ The loop passes ``request`` only when context management is on. ``replied`` is the loop's decision whether the
+ response replies (``has_reply``), which a final's row type takes as given; without one, the response alone
+ decides. ``images`` are those the run's committed tool results generated, which a final delivers with its
+ reply: its committed display carries them, so the row is a complete result even if delivery never runs.
"""
...
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
index b85ddda3a..a3ec9e813 100644
--- a/core/agent_core/messages.py
+++ b/core/agent_core/messages.py
@@ -37,8 +37,7 @@ HOSTED_STATUSES: tuple[str, ...] = ("completed", "failed", "incomplete", "pendin
HOSTED_ERROR_MAX_CHARS = 400
#: The stable code of each hosted failure Avibe words itself (``HostedRecord.error_code``), by which a display localizes
#: it; a provider's own reason has none. A record loads with any snake_case code, so one a newer build wrote still reads.
-#: ``provider_no_image`` and ``image_not_streamed`` have no producer since native images went (v2); they stay for the
-#: records already written.
+#: ``image_not_streamed`` has no producer since native images went (v2); it stays for the records already written.
HOSTED_ERROR_CODES: tuple[str, ...] = (
"provider_no_reason",
"provider_no_image",
@@ -51,6 +50,18 @@ HOSTED_ERROR_CODES: tuple[str, ...] = (
"gateway_no_result",
"image_param_unsupported",
"image_model_unavailable",
+ "image_argument_invalid",
+ "image_reference_unreadable",
+ # The gateway's search executor and image endpoint (vibey-hosted-tools.md §6, §7.4).
+ "provider_refused",
+ "provider_timed_out",
+ "provider_unreachable",
+ "provider_unreadable",
+ "provider_too_large",
+ "provider_image_unusable",
+ "search_not_run",
+ "search_failed",
+ "response_ended_early",
)
COST_BASES: tuple[str, ...] = ("reported", "list", "included")
SOURCE_BILLINGS: tuple[str, ...] = ("monthly", "metered")
@@ -350,8 +361,11 @@ class HostedImage:
class HostedRecord:
"""Per-call facts. ``images`` is set exactly for ``image_generate`` (possibly empty).
- ``error`` is model-facing English. ``error_code`` names a reason Avibe wrote (``HOSTED_ERROR_CODES``), only beside
- an ``error``.
+ ``error`` carries the reason as text, which the model reads: the provider's own, or one Avibe wrote. Every reason
+ Avibe writes carries an ``error_code`` (``HOSTED_ERROR_CODES``, #2589), only beside an ``error``: the display key,
+ which the Web card and the IM line render as that code's copy in the viewer's language. A reason without one is
+ shown as written: the provider's own, or the one reason whose useful part is that call's own fact (the gateway's
+ "no provider can run this search; add an API key from …"), which Avibe writes in the user's language.
"""
status: HostedStatus
@@ -670,14 +684,18 @@ def text(value: str) -> TextBlock:
return TextBlock(text=value)
-def has_reply(message: AssistantMessage) -> bool:
- """Whether a response says something to the user: non-blank text.
+def has_reply(message: AssistantMessage, *, generated_images: bool = False) -> bool:
+ """Whether a turn's final response gives the user something: non-blank text, or, when it ended normally, the images
+ the turn's calls generated (``generated_images``), which are delivered with it. A refusal, safety or length stop
+ without text stays a failure, whatever the turn generated.
- The one rule for "the model replied", read by the loop's empty-reply test and
- by a final row's outcome. A generated image is an ``image_generate`` tool
- result, delivered with the turn, never part of the response itself.
+ The one rule for "the model replied". The loop decides it once for each response it commits, and the store's row
+ type and live settlement take that decision. A generated image is an ``image_generate`` tool result, never part of
+ the response itself, so only the turn knows of it.
"""
- return any(isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content)
+ if any(isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content):
+ return True
+ return generated_images and message.stop_reason == "stop"
# --- persisted form ---------------------------------------------------------
diff --git a/core/agent_core/tools/hosted.py b/core/agent_core/tools/hosted.py
index 676eedba0..fccdd5df2 100644
--- a/core/agent_core/tools/hosted.py
+++ b/core/agent_core/tools/hosted.py
@@ -9,11 +9,25 @@ other tool; on a hop that runs the tool natively, the adapter sends the provider
from __future__ import annotations
import copy
-from typing import Any
+import re
+from typing import Any, Optional
+from core.agent_core.ai.provider import ImageModels
from core.agent_core.messages import HOSTED_TOOLS
from core.agent_core.tools.base import ToolSpec
+#: The reference images and outputs one ``image_generate`` call takes (§7.2).
+MAX_IMAGES = 4
+#: The forms an ``image_generate`` size takes (``size_forms``), as the image endpoint accepts them.
+SIZE_FORMS = {"pixels": re.compile(r"[1-9][0-9]{1,4}x[1-9][0-9]{1,4}"), "ratio": re.compile(r"[1-9][0-9]?:[1-9][0-9]?")}
+_SIZE_FORMS = {"pixels": "a size such as 1024x1024 or 1536x1024", "ratio": "an aspect ratio such as 16:9"}
+
+
+def size_form(size: Any) -> Optional[str]:
+ """The form of an ``image_generate`` size (``pixels`` or ``ratio``), or None when it is neither."""
+
+ return next((form for form, pattern in SIZE_FORMS.items() if isinstance(size, str) and pattern.fullmatch(size)), None)
+
_SPECS: dict[str, tuple[str, dict[str, Any]]] = {
"web_search": (
"Search the web. Returns numbered results with their titles, links and short excerpts.",
@@ -48,3 +62,33 @@ def hosted_tool_spec(tool: str) -> ToolSpec:
raise ValueError(f"unknown hosted tool: {tool!r}")
description, schema = _SPECS[tool]
return ToolSpec(tool, description, copy.deepcopy(schema))
+
+
+def image_generate_spec(models: ImageModels) -> ToolSpec:
+ """The ``image_generate`` spec of a turn (§7.2): ``model`` lists the turn's image models, the default first and
+ marked, each on one short line; ``size``, ``images`` and ``n`` are offered when one of them takes it."""
+
+ entries = models.models
+ lines = [f"{model.model_id}: {model.description}" + (" (default)" if index == 0 else "") for index, model in enumerate(entries)]
+ properties: dict[str, Any] = {
+ "model": {"type": "string", "enum": [model.model_id for model in entries], "description": " · ".join(lines)},
+ "prompt": {"type": "string", "description": "What to draw, or how to change the reference images."},
+ }
+ forms = [form for form in _SIZE_FORMS if any("size" in model.params and form in model.size_forms for model in entries)]
+ if forms:
+ properties["size"] = {"type": "string", "description": " or ".join(_SIZE_FORMS[form] for form in forms).capitalize() + "."}
+ if any("images" in model.params for model in entries):
+ properties["images"] = {
+ "type": "array",
+ "items": {"type": "string"},
+ "maxItems": MAX_IMAGES,
+ "description": "Paths of reference images to edit.",
+ }
+ if any("n" in model.params for model in entries):
+ properties["n"] = {"type": "integer", "minimum": 1, "maximum": MAX_IMAGES, "description": "How many images."}
+ return ToolSpec(
+ "image_generate",
+ "Generate an image with an image model, or edit reference images. The user sees each image; the result names "
+ "the file it was saved to, which read can open.",
+ {"type": "object", "properties": properties, "required": ["model", "prompt"], "additionalProperties": False},
+ )
diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.py
index bba5c21f7..fce977256 100644
--- a/core/agent_core/tools/read.py
+++ b/core/agent_core/tools/read.py
@@ -158,26 +158,84 @@ def _load(
mime_type = _sniff_image(head)
if mime_type is None:
return _read_text(handle, absolute, path, offset, limit, cancelled)
- if mime_type in IMAGE_MIME_TYPES:
- data = head + handle.read(max(0, MAX_INLINE_IMAGE_BYTES + 1 - len(head)))
- size = max(os.fstat(handle.fileno()).st_size, len(data))
- if size > MAX_INLINE_IMAGE_BYTES:
- # Avibe: no resizing in v1.
- return text_result(
- f"Read image file [{mime_type}]\n[Image omitted: the file is {format_size(size)}, over the "
- f"{format_size(MAX_INLINE_IMAGE_BYTES)} inline image limit. Images are not resized.]",
- details={"path": absolute, "mime_type": mime_type, "bytes": size},
- )
- if mime_type == "image/png" and _png_is_animated(data):
- # acTL may sit past the sniffed prefix, behind large ancillary chunks.
- mime_type = "image/apng"
- else:
- return _Image(mime_type, data, len(data))
- # Pi converts other formats to PNG; without an image library Avibe cannot.
- return text_result(
- f"Read image file [{mime_type}]\n[Image omitted: could not be converted to a supported inline image format.]",
- details={"path": absolute, "mime_type": mime_type},
- )
+ image = _load_image(handle, head, mime_type)
+ if isinstance(image, _Image):
+ return image
+ details = {"path": absolute, "mime_type": image.mime_type}
+ if image.size is not None:
+ details["bytes"] = image.size
+ return text_result(f"Read image file [{image.mime_type}]\n[Image omitted: {image.reason}]", details=details)
+
+
+@dataclass(frozen=True)
+class _Omitted:
+ mime_type: str
+ reason: str
+ size: Optional[int] = None
+
+
+def _load_image(handle: BinaryIO, head: bytes, mime_type: str) -> Union[_Image, _Omitted]:
+ """The image ``handle`` holds, ``head`` already read from it, or why ``read`` cannot attach it."""
+ if mime_type in IMAGE_MIME_TYPES:
+ data = head + handle.read(max(0, MAX_INLINE_IMAGE_BYTES + 1 - len(head)))
+ size = max(os.fstat(handle.fileno()).st_size, len(data))
+ if size > MAX_INLINE_IMAGE_BYTES:
+ # Avibe: no resizing in v1.
+ reason = (
+ f"the file is {format_size(size)}, over the {format_size(MAX_INLINE_IMAGE_BYTES)} inline image limit. "
+ "Images are not resized."
+ )
+ return _Omitted(mime_type, reason, size)
+ if mime_type == "image/png" and _png_is_animated(data):
+ # acTL may sit past the sniffed prefix, behind large ancillary chunks.
+ mime_type = "image/apng"
+ else:
+ return _Image(mime_type, data, len(data))
+ # Pi converts other formats to PNG; without an image library Avibe cannot.
+ return _Omitted(mime_type, "could not be converted to a supported inline image format.")
+
+
+class ImageUnreadable(Exception):
+ """Why ``read_image`` cannot give the image at a path: ``kind`` says which check refused it, so a caller can word
+ it; ``reason`` is the text ``read`` would show, the system's own words for a file it could not open."""
+
+ def __init__(
+ self,
+ reason: str,
+ *,
+ kind: str = "unreadable",
+ mime_type: Optional[str] = None,
+ size: Optional[int] = None,
+ ) -> None:
+ super().__init__(reason)
+ self.reason, self.kind, self.mime_type, self.size = reason, kind, mime_type, size
+
+
+def read_image(path: str, cwd: str) -> tuple[str, bytes]:
+ """The image at ``path`` as ``read`` attaches it, its type and bytes: the path resolved against ``cwd`` and checked
+ as ``read`` does (a regular, readable file; a supported image type within the inline limit). Raises
+ ``ImageUnreadable`` with the reason otherwise. Blocking: call it off the event loop."""
+ try:
+ absolute = resolve_read_path(path, cwd)
+ refusal = _refusal(absolute)
+ if refusal:
+ raise ImageUnreadable(refusal)
+ with os.fdopen(open_regular(absolute), "rb") as handle:
+ head = handle.read(_IMAGE_SNIFF_BYTES)
+ mime_type = _sniff_image(head)
+ image = _load_image(handle, head, mime_type) if mime_type is not None else None
+ except NotRegularFile as exc:
+ raise ImageUnreadable(KIND_REASON[exc.kind]) from None
+ except OSError as exc:
+ raise ImageUnreadable(os_reason(exc)) from None
+ except ToolInputError as exc:
+ raise ImageUnreadable(str(exc)) from None
+ if image is None:
+ raise ImageUnreadable("it is not an image (jpg, png, gif, webp)", kind="not_image")
+ if isinstance(image, _Omitted):
+ kind = "too_large" if image.size is not None else "unsupported"
+ raise ImageUnreadable(image.reason.rstrip("."), kind=kind, mime_type=image.mime_type, size=image.size)
+ return image.mime_type, image.data
def _sniff_image(head: bytes) -> Optional[str]:
diff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.py
index 49f7a08a3..24a927db7 100644
--- a/core/handlers/model_hub/classification.py
+++ b/core/handlers/model_hub/classification.py
@@ -220,14 +220,20 @@ def machine_error_codes(outcome: RawCallOutcome) -> tuple[str, ...]:
def names_model_refusal(outcome: RawCallOutcome) -> bool:
- """Whether the upstream's machine code says it does not serve the requested model."""
+ """Whether the upstream says it does not serve the requested model: a code naming it, or a 404 not_found_error."""
- return bool(_MODEL_SURFACE_PATTERNS.search(_error_text(outcome))) or (
+ return machine_codes_name_model(outcome) or (
outcome.http_status == 404
and any(code in _MODEL_NOT_FOUND_ERROR_CODES for code in machine_error_codes(outcome))
)
+def machine_codes_name_model(outcome: RawCallOutcome) -> bool:
+ """Whether a machine code itself names the model as not served (``model_not_found``, ``unknown_model``)."""
+
+ return bool(_MODEL_SURFACE_PATTERNS.search(_error_text(outcome)))
+
+
def _classify_unstreamed(
outcome: RawCallOutcome,
*,
diff --git a/core/handlers/model_hub/evidence_rules.py b/core/handlers/model_hub/evidence_rules.py
index 54b7d244e..c8502a937 100644
--- a/core/handlers/model_hub/evidence_rules.py
+++ b/core/handlers/model_hub/evidence_rules.py
@@ -14,6 +14,7 @@ from dataclasses import dataclass
from typing import Any, Callable, Mapping, Optional
from config.v2_config import ModelHubSourceConfig
+from vibe.backend_model_catalog import OVERLAY_SEARCH_TOOLS
from .adapter import UpstreamRejection
from .capability_evidence import EvidenceFeature
@@ -81,7 +82,7 @@ def learn(
rejected_type = rejection.unsupported_tool_type
if rejected_type is not None and rejected_type in declared_tool_types(request):
- for tool in ("web_search", "x_search", "image_generation"):
+ for tool in OVERLAY_SEARCH_TOOLS:
spec = spec_for(source.vendor, source.protocol, model_id, tool)
if spec is not None and spec.declaration_type == rejected_type:
return LearnedEvidence(EvidenceFeature.hosted(tool, "call"), _detail(rejection))
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.py
index 0daf598e7..7078f8d8e 100644
--- a/core/handlers/model_hub/hosted_executor.py
+++ b/core/handlers/model_hub/hosted_executor.py
@@ -160,9 +160,52 @@ def executor_request(
# Renders one of this module's failure keys (``modelHub.hostedTools.*``) in the user's language.
Say = Callable[..., str]
+# The stable code of each reason this gateway words (``HOSTED_ERROR_CODES``, #2589): the key the Web card and the IM
+# line show it by, in their reader's language. The record's ``error`` keeps the worded text, details included, for
+# the model. A reason whose useful part is what only this call knows (which providers to add) has no code: it is
+# worded in the user's language and shown as written.
+FAILURE_CODES: Final[Mapping[str, str]] = {
+ "modelHub.hostedTools.providerRefused": "provider_refused",
+ "modelHub.hostedTools.timedOut": "provider_timed_out",
+ "modelHub.hostedTools.unreachable": "provider_unreachable",
+ "modelHub.hostedTools.unreadable": "provider_unreadable",
+ "modelHub.hostedTools.tooLarge": "provider_too_large",
+ "modelHub.hostedTools.didNotRun": "search_not_run",
+ "modelHub.hostedTools.callFailed": "search_failed",
+ "modelHub.hostedTools.responseEnded": "response_ended_early",
+ "modelHub.hostedTools.imageMissing": "provider_no_image",
+ "modelHub.hostedTools.imageUnreadable": "provider_image_unusable",
+}
+
+
+@dataclass(frozen=True)
+class Failure:
+ """A reason this gateway words: its text in the user's language, and its code (None: shown as written)."""
+
+ error: str
+ code: str | None
+
+ def also(self, text: str) -> "Failure":
+ """The same reason, with more said after it."""
-def failed_record(error: str, sources: list[dict[str, Any]] | None = None) -> dict[str, Any]:
- return {"status": "failed", "error": bounded_diagnostic_detail(error) or error[:400], "sources": sources or []}
+ return Failure(f"{self.error} {text}".strip(), self.code)
+
+
+def failure(say: Say, key: str, *, provider_says: str | None = None, **params: str) -> Failure:
+ """The reason ``key`` names, worded by ``say``; what the provider said, verbatim, follows in brackets."""
+
+ text = say(key, **params)
+ return Failure(f"{text} ({provider_says})" if provider_says else text, FAILURE_CODES[key])
+
+
+def failed_record(
+ reason: Failure, sources: list[dict[str, Any]] | None = None, *, status: str = "failed",
+) -> dict[str, Any]:
+ error = bounded_diagnostic_detail(reason.error) or reason.error[:400]
+ record: dict[str, Any] = {"status": status, "error": error, "sources": sources or []}
+ if reason.code is not None:
+ record["error_code"] = reason.code
+ return record
@dataclass
@@ -265,22 +308,24 @@ def _usage_section(response: Any) -> Mapping[str, Any] | None:
return usage if isinstance(usage, Mapping) else None
-def responses_result(tool: str, readout: ResponsesReadout, say: Say, *, failure: str | None = None) -> ExecutorResult:
+def responses_result(
+ tool: str, readout: ResponsesReadout, say: Say, *, failed: Failure | None = None,
+) -> ExecutorResult:
"""The canonical record of one streamed Responses executor call.
- ``failure`` is how the call failed, from its outcome, when it did; it takes
+ ``failed`` is how the call failed, from its outcome, when it did; it takes
precedence over anything the stream emitted, whose sources a failed record
keeps. A call the provider marked failed is failed too.
"""
- return replace(_responses_record(tool, readout, say, failure), usage=_usage_section(readout.response))
+ return replace(_responses_record(tool, readout, say, failed), usage=_usage_section(readout.response))
-def _responses_record(tool: str, readout: ResponsesReadout, say: Say, failure: str | None) -> ExecutorResult:
+def _responses_record(tool: str, readout: ResponsesReadout, say: Say, failed: Failure | None) -> ExecutorResult:
response = readout.response or {}
calls = [item for item in readout.items if _responses_call_tool(item) == tool]
if not calls:
- return ExecutorResult(failed_record(failure or _ended_without(tool, response, say)))
+ return ExecutorResult(failed_record(failed or _ended_without(tool, response, say)))
texts = [
part
for item in readout.items
@@ -290,10 +335,10 @@ def _responses_record(tool: str, readout: ResponsesReadout, say: Say, failure: s
]
cited = _cited_sources(texts, x_posts_only=tool == "x_search")
sources = _merge_sources(cited, [] if tool == "x_search" else _call_sources(calls))
- if failure is not None:
- return ExecutorResult(failed_record(failure, sources))
+ if failed is not None:
+ return ExecutorResult(failed_record(failed, sources))
if any(call.get("status") == "failed" for call in calls):
- return ExecutorResult(failed_record(say("modelHub.hostedTools.callFailed", tool=tool), sources))
+ return ExecutorResult(failed_record(failure(say, "modelHub.hostedTools.callFailed", tool=tool), sources))
return ExecutorResult(_settled(response, sources, say))
@@ -307,12 +352,10 @@ def _settled(response: Mapping[str, Any], sources: list[dict[str, Any]], say: Sa
status = _text_field(response, "status")
if status == "completed":
return {"status": "completed", "sources": sources}
- ended = _ended_without("", response, say) if status in {"failed", "incomplete"} else say(
- "modelHub.hostedTools.responseEnded", status=str(status or "unknown"),
+ ended = _ended_without("", response, say) if status in {"failed", "incomplete"} else failure(
+ say, "modelHub.hostedTools.responseEnded", status=str(status or "unknown"),
)
- if status == "incomplete":
- return {"status": "incomplete", "error": failed_record(ended)["error"], "sources": sources}
- return failed_record(ended, sources)
+ return failed_record(ended, sources, status="incomplete" if status == "incomplete" else "failed")
def _text_field(item: Mapping[str, Any], key: str) -> str | None:
@@ -326,14 +369,16 @@ def _responses_call_tool(item: Mapping[str, Any]) -> str | None:
return responses_item_tool(_text_field(item, "type"), _text_field(item, "name"))
-def _ended_without(tool: str, response: Mapping[str, Any], say: Say) -> str:
+def _ended_without(tool: str, response: Mapping[str, Any], say: Say) -> Failure:
status = _text_field(response, "status")
if status in {"failed", "incomplete"}:
details = response.get("incomplete_details")
reason = details.get("reason") if isinstance(details, dict) else None
- text = say("modelHub.hostedTools.responseEnded", status=status)
- return f"{text} ({reason})" if isinstance(reason, str) and reason else text
- return say("modelHub.hostedTools.didNotRun", tool=tool)
+ return failure(
+ say, "modelHub.hostedTools.responseEnded", status=status,
+ provider_says=reason if isinstance(reason, str) and reason else None,
+ )
+ return failure(say, "modelHub.hostedTools.didNotRun", tool=tool)
def _call_sources(calls: list[Mapping[str, Any]]) -> list[dict[str, Any]]:
@@ -466,7 +511,7 @@ def anthropic_result(body: bytes | bytearray, say: Say) -> ExecutorResult:
try:
message = json.loads(body)
except (ValueError, RecursionError):
- return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable")))
+ return ExecutorResult(failed_record(failure(say, "modelHub.hostedTools.unreadable")))
return replace(_anthropic_record(message, say), usage=_usage_section(message))
@@ -474,7 +519,7 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
content = message.get("content") if isinstance(message, dict) else None
blocks = [block for block in content if isinstance(block, dict)] if isinstance(content, list) else []
if not any(block.get("type") == "server_tool_use" and block.get("name") == "web_search" for block in blocks):
- return ExecutorResult(failed_record(say("modelHub.hostedTools.didNotRun", tool="web_search")))
+ return ExecutorResult(failed_record(failure(say, "modelHub.hostedTools.didNotRun", tool="web_search")))
results: list[dict[str, Any]] = []
errors: list[str] = []
for block in blocks:
@@ -486,7 +531,7 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
continue
if not isinstance(found, list):
# Only a list, possibly empty, is a result; anything else is not an answer.
- return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable")))
+ return ExecutorResult(failed_record(failure(say, "modelHub.hostedTools.unreadable")))
for result in found:
if isinstance(result, dict) and isinstance(result.get("url"), str) and result["url"]:
source = {"url": result["url"]}
@@ -510,8 +555,8 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
if errors:
# Any search the provider marked failed fails the call, as on Responses;
# the results that did arrive stay as partial sources.
- text = say("modelHub.hostedTools.callFailed", tool="web_search")
- return ExecutorResult(failed_record(f"{text} ({', '.join(errors)})", sources))
+ failed = failure(say, "modelHub.hostedTools.callFailed", tool="web_search", provider_says=", ".join(errors))
+ return ExecutorResult(failed_record(failed, sources))
# Success is an allow-list here too: an early stop is incomplete, anything else unknown fails.
stop = _text_field(message, "stop_reason")
if stop in {"end_turn", "stop_sequence"}:
@@ -522,9 +567,7 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
answered = [block.get("tool_use_id") for block in blocks if block.get("type") == "web_search_tool_result"]
if not all(isinstance(ident, str) and ident for ident in (*uses, *answered)) or not set(uses) <= set(answered):
# A finished response must carry every search's result block, even an empty one.
- return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable"), sources))
+ return ExecutorResult(failed_record(failure(say, "modelHub.hostedTools.unreadable"), sources))
return ExecutorResult({"status": "completed", "sources": sources})
- ended = say("modelHub.hostedTools.responseEnded", status=str(stop or "unknown"))
- if stop in {"max_tokens", "pause_turn"}:
- return ExecutorResult({"status": "incomplete", "error": failed_record(ended)["error"], "sources": sources})
- return ExecutorResult(failed_record(ended, sources))
+ ended = failure(say, "modelHub.hostedTools.responseEnded", status=str(stop or "unknown"))
+ return ExecutorResult(failed_record(ended, sources, status="incomplete" if stop in {"max_tokens", "pause_turn"} else "failed"))
diff --git a/core/handlers/model_hub/hosted_images.py b/core/handlers/model_hub/hosted_images.py
new file mode 100644
index 000000000..0c45215ac
--- /dev/null
+++ b/core/handlers/model_hub/hosted_images.py
@@ -0,0 +1,185 @@
+"""``image_generate`` direct execution (``vibey-hosted-tools.md`` §7.2, §7.4).
+
+The call names one model from its turn's frozen enum. This module owns what a
+call may carry, the images-endpoint request it becomes, and how the endpoint's
+answer becomes the canonical record and the image bytes; the service owns the
+call itself, and Vibey saves the images through its media sink.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import json
+from dataclasses import dataclass
+from typing import Any, Final, Mapping
+
+from core.agent_core.messages import IMAGE_MIME_TYPES
+# Vibey checks a call by the same bounds and size grammar before sending, so nothing it sends is refused here.
+from core.agent_core.tools.hosted import MAX_IMAGES, size_form
+from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES, detect_supported_image_mime_type
+from vibe.backend_model_catalog import ImageModelSpec
+
+from .hosted_executor import ExecutorCallRefused, Say, failed_record, failure
+
+IMAGE_TIMEOUT_SECONDS: Final = 300.0
+# The call's body: its reference images, each within read's inline limit as base64, plus the rest.
+IMAGE_CALL_MAX_BYTES: Final = MAX_IMAGES * ((MAX_INLINE_IMAGE_BYTES + 2) // 3 * 4) + 1024 * 1024
+# One delivered image, decoded, and every image of one answer.
+IMAGE_MAX_BYTES: Final = 24 * 1024 * 1024
+IMAGES_TOTAL_MAX_BYTES: Final = 64 * 1024 * 1024
+# The endpoint's answer as base64 JSON: the decoded budget, inflated, plus a margin for the rest.
+IMAGE_RESPONSE_MAX_BYTES: Final = IMAGES_TOTAL_MAX_BYTES * 4 // 3 + 1024 * 1024
+# Where each size form goes on the images endpoints.
+_SIZE_FIELDS: Final = {"pixels": "size", "ratio": "aspect_ratio"}
+
+
+@dataclass(frozen=True)
+class ImageCall:
+ model: str
+ prompt: str
+ size: str | None = None
+ n: int | None = None
+ # Each reference image's MIME type and base64 data, as read resolved them.
+ images: tuple[tuple[str, str], ...] = ()
+
+ @property
+ def given(self) -> tuple[str, ...]:
+ """The optional parameters this call names, in catalog order."""
+
+ return tuple(
+ name for name, value in (("images", self.images), ("n", self.n), ("size", self.size)) if value
+ )
+
+
+def parse_image_call(payload: object) -> ImageCall:
+ """Validate one ``image_generate`` body; parse it off the loop, its images are megabytes."""
+
+ if not isinstance(payload, dict) or set(payload) != {"arguments"}:
+ raise ExecutorCallRefused("invalid_request_error", 400)
+ arguments = payload["arguments"]
+ if not isinstance(arguments, dict) or set(arguments) - {"model", "prompt", "size", "images", "n"}:
+ raise ExecutorCallRefused("invalid_request_error", 400)
+ model, prompt = arguments.get("model"), arguments.get("prompt")
+ size, n, images = arguments.get("size"), arguments.get("n"), arguments.get("images")
+ if (
+ not isinstance(model, str) or not model
+ or not isinstance(prompt, str) or not prompt.strip()
+ or (size is not None and size_form(size) is None)
+ or (n is not None and (isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= MAX_IMAGES))
+ or (images is not None and (not isinstance(images, list) or not 1 <= len(images) <= MAX_IMAGES))
+ ):
+ raise ExecutorCallRefused("invalid_request_error", 400)
+ references = []
+ for encoded in images or ():
+ # Vibey read each one as ``read`` reads it; the gateway checks again as the execution boundary.
+ try:
+ data = base64.b64decode(encoded, validate=True) if isinstance(encoded, str) else b""
+ except (binascii.Error, ValueError):
+ data = b""
+ mime = _image_mime(data) if 0 < len(data) <= MAX_INLINE_IMAGE_BYTES else None
+ if mime is None:
+ raise ExecutorCallRefused("invalid_request_error", 400)
+ references.append((mime, encoded))
+ return ImageCall(model, prompt, size, n, tuple(references))
+
+
+def _image_mime(data: bytes) -> str | None:
+ """The type of an image a context holds as ``read`` attaches it and the media sink saves it, else None.
+
+ Checked over every byte: an animated PNG's ``acTL`` may sit past any prefix.
+ """
+
+ mime = detect_supported_image_mime_type(data)
+ return mime if mime in IMAGE_MIME_TYPES else None
+
+
+def unsupported_argument(call: ImageCall, spec: ImageModelSpec) -> str | None:
+ """The first argument the model does not take, or a size in a form it does not accept."""
+
+ for name in call.given:
+ if name not in spec.params:
+ return name
+ if call.size is not None and size_form(call.size) not in spec.size_forms:
+ return "size"
+ return None
+
+
+def image_request(call: ImageCall, spec: ImageModelSpec) -> dict[str, Any]:
+ """The images-endpoint body: the model's fixed fields, then what the call names.
+
+ The engine routes a body with reference images to ``/v1/images/edits``.
+ """
+
+ body: dict[str, Any] = {**spec.request, "prompt": call.prompt}
+ if call.n is not None:
+ body["n"] = call.n
+ if call.size is not None:
+ body[_SIZE_FIELDS[size_form(call.size)]] = call.size
+ if call.images:
+ body["images"] = [{"image_url": f"data:{mime};base64,{data}"} for mime, data in call.images]
+ return body
+
+
+@dataclass(frozen=True)
+class ImageResult:
+ """The record for the call, the images it delivered (base64, in order), and the endpoint's own facts."""
+
+ record: dict[str, Any]
+ images: tuple[str, ...] = ()
+ generation: Mapping[str, str] | None = None
+ usage: Mapping[str, Any] | None = None
+
+
+def image_result(body: bytes | bytearray, say: Say, *, asked: int) -> ImageResult:
+ """The canonical record of one images-endpoint answer to a call that asked for ``asked`` images; parse it off
+ the loop.
+
+ Completion is an allow-list: only an answer whose every item is a usable
+ base64 image, and that holds no more images than the call asked for,
+ completes. An endpoint that answers with URLs only fails, as the gateway
+ never fetches an arbitrary URL.
+ """
+
+ try:
+ answer = json.loads(body)
+ except (ValueError, RecursionError):
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.unreadable")))
+ data = answer.get("data") if isinstance(answer, dict) else None
+ if not isinstance(data, list) or not data or not all(isinstance(item, dict) for item in data):
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.imageMissing")))
+ if len(data) > asked:
+ # More is not what the call asked for, and none of it is kept.
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.tooLarge")))
+ images: list[str] = []
+ total = 0
+ for item in data:
+ encoded = item.get("b64_json")
+ if not isinstance(encoded, str) or not encoded:
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.imageMissing")))
+ try:
+ decoded = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError):
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.imageUnreadable")))
+ total += len(decoded)
+ if not decoded or len(decoded) > IMAGE_MAX_BYTES or total > IMAGES_TOTAL_MAX_BYTES:
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.tooLarge")))
+ if _image_mime(decoded) is None:
+ return ImageResult(failed_record(failure(say, "modelHub.hostedTools.imageUnreadable")))
+ images.append(encoded)
+ generation = {
+ name: value
+ for name, value in (
+ ("size", answer.get("size")),
+ ("quality", answer.get("quality")),
+ ("revised_prompt", data[0].get("revised_prompt")),
+ )
+ if isinstance(value, str) and value
+ }
+ usage = answer.get("usage")
+ return ImageResult(
+ {"status": "completed", "sources": []},
+ images=tuple(images),
+ generation=generation or None,
+ usage=usage if isinstance(usage, Mapping) else None,
+ )
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index d8a0d4cd9..4804a7c66 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -35,6 +35,7 @@ from config.v2_config import (
model_hub_executor_order,
)
from vibe.backend_model_catalog import (
+ IMAGE_PROTOCOLS,
HostedToolSpec,
ImageModelSpec,
bundled_provider_vendors,
@@ -246,15 +247,15 @@ def executor_vendors(tool: str) -> tuple[str, ...]:
@dataclass(frozen=True)
class ImageChoice:
- """One image model ``image_generate`` may name, on the Source that serves it."""
+ """One image model ``image_generate`` may name, on the Source that serves it, under that Source's identity."""
source_id: str
model_id: str
description: str
- endpoint: Literal["images", "chat_image"]
params: tuple[str, ...]
size_forms: tuple[str, ...]
spec: ImageModelSpec
+ identity: str = ""
@dataclass(frozen=True)
@@ -267,8 +268,20 @@ class ImageChoices:
saved_default_available: bool = False
-def _serves_image(source: ModelHubSourceConfig, model_id: str) -> bool:
- return source.supply_channel == "hub" and credential_eligible(source) and _serves(source, model_id)
+def _serves_image(source: ModelHubSourceConfig, spec: ImageModelSpec) -> bool:
+ """The image model's route was verified on this kind of credential, and the Source serves the model.
+
+ Only a Source whose protocol's engine entry serves the images endpoints is offered one: the engine refuses the
+ rest on its own, and that refusal is never learned, so it would be offered on every turn.
+ """
+
+ return (
+ source.supply_channel == "hub"
+ and source.protocol in IMAGE_PROTOCOLS
+ and source.kind in spec.kinds
+ and credential_eligible(source)
+ and _serves(source, spec.id)
+ )
def image_choices(config: ModelHubConfig, *, evidence: HostedEvidence) -> ImageChoices:
@@ -284,13 +297,13 @@ def image_choices(config: ModelHubConfig, *, evidence: HostedEvidence) -> ImageC
available: list[ImageChoice] = []
for source in _vibey_order(config):
for spec in provider_image_models(source.vendor):
- if not _serves_image(source, spec.id) or evidence.unsupported(
+ if not _serves_image(source, spec) or evidence.unsupported(
source, spec.id, EvidenceFeature.hosted("image_generate", "call")
):
continue
- available.append(
- ImageChoice(source.id, spec.id, spec.description, spec.endpoint, spec.params, spec.size_forms, spec)
- )
+ available.append(ImageChoice(
+ source.id, spec.id, spec.description, spec.params, spec.size_forms, spec, identity_digest(source),
+ ))
if not available:
return ImageChoices((), None, saved, False)
saved_choice = next(
@@ -310,6 +323,24 @@ def image_choices(config: ModelHubConfig, *, evidence: HostedEvidence) -> ImageC
return ImageChoices((default, *rest), default, saved, saved_choice is not None)
+def admitted_image(config: ModelHubConfig, choice: ImageChoice, *, evidence: HostedEvidence) -> ModelHubSourceConfig | None:
+ """The Source a frozen enum entry runs on, if this snapshot still admits it (§7.4): None otherwise.
+
+ The same Source under the same identity, still serving the model on a verified credential kind, with no
+ current refusal of the pair.
+ """
+
+ source = next((item for item in config.sources if item.id == choice.source_id), None)
+ if (
+ source is None
+ or identity_digest(source) != choice.identity
+ or not _serves_image(source, choice.spec)
+ or evidence.unsupported(source, choice.model_id, EvidenceFeature.hosted("image_generate", "call"))
+ ):
+ return None
+ return source
+
+
def freeze_turn_tools(config: ModelHubConfig, *, evidence: HostedEvidence, spec_for: SpecLookup) -> TurnHostedTools:
"""What a Vibey turn's first resolution freezes (§3.4). With no image model, ``image_generate`` is not declared."""
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 6aa117f38..fa971ed59 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -60,8 +60,10 @@ from vibe.backend_model_catalog import (
bundled_client_presets_once,
bundled_provider_overlay,
hosted_tool_spec,
+ provider_image_models,
)
from vibe.i18n import t as i18n_t
+from vibe.model_hub_runtime.client import RESPONSE_TOO_LARGE
from vibe.model_hub_runtime.api_key_vendors import (
catalog_api_key_vendor_label,
pinned_api_key_protocol,
@@ -103,6 +105,7 @@ from .catalog_admission import (
from .classification import (
ResolutionDecision,
classify_outcome,
+ machine_codes_name_model,
names_model_refusal,
source_settlement_allowed,
source_settlement_rule,
@@ -136,16 +139,27 @@ from .hosted_executor import (
call_timeout,
executor_request,
executor_streams,
+ Failure,
failed_record,
+ failure,
parse_call,
provider_charges,
responses_result,
)
-from .hosted_turn import ExecutorSlot, TurnHostedTools
+from .hosted_images import (
+ IMAGE_RESPONSE_MAX_BYTES,
+ IMAGE_TIMEOUT_SECONDS,
+ image_request,
+ image_result,
+ parse_image_call,
+ unsupported_argument,
+)
+from .hosted_turn import IMAGE_TOOL, ExecutorSlot, TurnHostedTools
from .hosted_tools import (
ExecutorCandidate,
HostedEvidence,
HostedToolSettingRefused,
+ admitted_image,
apply_hosted_tool_put,
clear_request,
engine_stamp,
@@ -831,22 +845,25 @@ def _call_usage(outcome: RawCallOutcome | None, observed: ProtocolSSEState | Non
return observed.usage if usage is None and observed is not None else usage
-def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *, refused: str | None) -> str | None:
- """How a proxied hosted call failed, in the user's language; None when it succeeded.
+def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *, refused: str | None) -> Failure | None:
+ """How a proxied hosted call failed, in the user's language and by its code; None when it succeeded.
``refused`` names a bound the response itself broke (size, nesting).
"""
if refused is not None:
- return say(refused)
+ return failure(say, refused)
if outcome is None or outcome.kind is RawOutcomeKind.SUCCESS:
return None
+ if outcome.error_code == RESPONSE_TOO_LARGE:
+ # The engine client cut an answer past its bound while it downloaded.
+ return failure(say, "modelHub.hostedTools.tooLarge")
if outcome.kind is RawOutcomeKind.TIMEOUT:
- return say("modelHub.hostedTools.timedOut")
+ return failure(say, "modelHub.hostedTools.timedOut")
if outcome.kind is RawOutcomeKind.NETWORK_ERROR:
- return say("modelHub.hostedTools.unreachable")
+ return failure(say, "modelHub.hostedTools.unreachable")
if outcome.kind is RawOutcomeKind.PROTOCOL_ERROR:
- return say("modelHub.hostedTools.unreadable")
+ return failure(say, "modelHub.hostedTools.unreadable")
# The provider's own machine code and its redacted, bounded detail stay verbatim.
detail = " ".join(
part for part in (
@@ -856,13 +873,28 @@ def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *
)
if outcome.upstream_detail:
detail = f"{detail}: {outcome.upstream_detail}" if detail else outcome.upstream_detail
- return say("modelHub.hostedTools.providerRefused", detail=detail or outcome.kind.value)
+ return failure(say, "modelHub.hostedTools.providerRefused", detail=detail or outcome.kind.value)
def _cost_payload(cost: HostedCost) -> dict[str, Any]:
return {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}
+@dataclass(frozen=True)
+class _HostedUpstreamCall:
+ """How one upstream call a hosted tool made ended (``ModelHubService._hosted_upstream_call``)."""
+
+ # The Source as the call's final admission saw it: what the call reports (billing, cost, name) follows it.
+ source: ModelHubSourceConfig
+ outcome: RawCallOutcome | None
+ # A bound the response broke, as a failure key to show.
+ refused: str | None
+ timed_out: bool
+ usage: ProtocolUsageReport | None
+ # Whether the provider could have charged for it: it reported tokens or produced a response.
+ billable: bool
+
+
@dataclass(frozen=True)
class _ExecutorAttempt:
"""One executor candidate a search chain called, as it settled (``vibey-hosted-tools.md`` §6)."""
@@ -6514,17 +6546,22 @@ class ModelHubService:
if not attempt.moves_on:
break
if not attempts:
- vendors = ", ".join(catalog_api_key_vendor_label(vendor) or vendor for vendor in executor_vendors(tool))
- return {"record": failed_record(say("modelHub.hostedTools.noExecutor", tool=tool, vendors=vendors))}
+ vendors = [catalog_api_key_vendor_label(vendor) or vendor for vendor in executor_vendors(tool)]
+ form = "one" if len(vendors) == 1 else "several"
+ listed = say("modelHub.hostedTools.listSeparator").join(vendors)
+ # Which providers to add is this call's own fact: worded in the user's language and shown as written.
+ no_source = Failure(say(f"modelHub.hostedTools.noExecutor.{tool}.{form}", vendors=listed), None)
+ return {"record": failed_record(no_source)}
# The record is the last attempt's; earlier billable ones are listed, each with its own billing.
last = attempts[-1]
record = last.record
if last.moves_on:
# Every candidate was tried and failed: say which, so the user sees whether retrying or those Sources is the issue.
tried = ", ".join(dict.fromkeys(attempt.source.display_name for attempt in attempts))
+ # Its reason keeps its code; the Sources tried follow in its text.
+ last_failure = Failure(record["error"], record["error_code"])
record = failed_record(
- f"{record.get('error') or ''} {say('modelHub.hostedTools.triedSources', sources=tried)}".strip(),
- record.get("sources"),
+ last_failure.also(say("modelHub.hostedTools.triedSources", sources=tried)), record.get("sources"),
)
execution = last.execution()
failed_attempts = [attempt.failed_attempt() for attempt in attempts[:-1] if attempt.billable]
@@ -6532,6 +6569,148 @@ class ModelHubService:
execution["failed_attempts"] = failed_attempts
return {"record": record, "execution": execution}
+ async def run_image_tool(self, payload: object, *, turn: TurnHostedTools | None, language: str = "en") -> dict:
+ """Run one ``image_generate`` call directly on the images endpoint of the model it names (§7.4).
+
+ ``turn`` is what the caller's live turn froze: a model outside its enum
+ is refused, unrun. There is no chain and no fallback: a failed call says
+ which other models the turn offers, and the model may call again with
+ one. The call is metered on its Source and never changes Source health.
+ """
+
+ def say(key: str, **params: str) -> str:
+ return i18n_t(key, language, **params)
+
+ try:
+ # Reference images are megabytes of base64: validated off the controller loop.
+ call = await asyncio.to_thread(parse_image_call, payload)
+ except ExecutorCallRefused as refused:
+ raise ModelHubError(refused.code, status=refused.status) from None
+ choice = next((item for item in (turn.images if turn is not None else ()) if item.model_id == call.model), None)
+ if turn is None or IMAGE_TOOL not in turn.tools or choice is None:
+ raise ModelHubError("tool_not_enabled", status=409)
+ others = [item.model_id for item in turn.images if item.model_id != call.model]
+
+ def failed(reason: Failure) -> dict:
+ # The other models follow the reason in its text; its code stays its own.
+ if others:
+ reason = reason.also(say("modelHub.hostedTools.imageAlternatives", models=", ".join(others)))
+ return {"record": failed_record(reason)}
+
+ unsupported = unsupported_argument(call, choice.spec)
+ if unsupported is not None:
+ takers = [item.model_id for item in turn.images if unsupported_argument(call, item.spec) is None]
+ text = say("modelHub.hostedTools.imageParamUnsupported", model=call.model, param=unsupported)
+ if takers:
+ text = f"{text} {say('modelHub.hostedTools.imageParamTakers', models=', '.join(takers))}"
+ return {"record": failed_record(Failure(text, "image_param_unsupported"))}
+
+ async def admitted() -> ModelHubSourceConfig | None:
+ # The config grows with use: read it off the controller loop.
+ config = await asyncio.to_thread(self.store.load)
+ return admitted_image(config, choice, evidence=self.hosted_evidence())
+
+ unavailable = Failure(say("modelHub.hostedTools.imageModelUnavailable", model=call.model), "image_model_unavailable")
+ source = await admitted()
+ if source is None:
+ return failed(unavailable)
+ # Its reference images become data URLs: megabytes, built off the controller loop.
+ request = ModelHubRequest(await asyncio.to_thread(image_request, call, choice.spec), protocol="openai_images")
+ body = bytearray()
+
+ async def feed(chunk: bytes) -> None:
+ if len(body) + len(chunk) > IMAGE_RESPONSE_MAX_BYTES:
+ raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")
+ body.extend(chunk)
+
+ called = await self._hosted_upstream_call(
+ source, call.model, request, stream=False,
+ deadline=asyncio.get_running_loop().time() + IMAGE_TIMEOUT_SECONDS, feed=feed,
+ admitted_now=admitted,
+ )
+ if called is None:
+ return failed(unavailable)
+ source = called.source
+ outcome = called.outcome
+ failed_reason = _executor_failure(outcome, say, refused=called.refused)
+ # The bytearray itself goes to the worker: no copy of the answer on the loop.
+ # Every images endpoint offered makes one image when the call names no n.
+ result = await asyncio.to_thread(image_result, body, say, asked=call.n or 1) if failed_reason is None else None
+ execution: dict[str, Any] = {
+ "mode": "direct",
+ "executor_origin": {"provider": source.vendor, "api": source.protocol, "model": call.model},
+ "executor_source_id": source.id,
+ "executor_billing": source.billing,
+ }
+ cost = self._image_call_cost(
+ source, choice.spec, usage=called.usage, images=len(result.images) if result is not None else 0,
+ generation=result.generation if result is not None else None,
+ )
+ if cost is not None:
+ execution["cost"] = _cost_payload(cost)
+ if result is None or result.record["status"] != "completed":
+ if outcome is not None and outcome.kind is not RawOutcomeKind.SUCCESS:
+ await self._learn_image_refusal(source, call.model, outcome)
+ if failed_reason is None and result is not None:
+ failed_reason = Failure(result.record["error"], result.record.get("error_code"))
+ answer = failed(failed_reason or failure(say, "modelHub.hostedTools.unreadable"))
+ return {**answer, "execution": execution}
+ await self.record_hosted_success(source, call.model, IMAGE_TOOL, "direct")
+ answer: dict[str, Any] = {"record": result.record, "execution": execution, "images": [
+ {"data": data} for data in result.images
+ ]}
+ if result.generation is not None:
+ answer["generation"] = dict(result.generation)
+ return answer
+
+ async def _learn_image_refusal(self, source: ModelHubSourceConfig, model_id: str, outcome: RawCallOutcome) -> None:
+ """The image narrow rule (§3.2): an upstream refusal of the model or of the endpoint, before any output.
+
+ The engine's own refusals reach here as local failures, never as an
+ upstream status, so they never teach. A refusal of the endpoint itself
+ (a 404: the path is not served) holds for every image model the Source
+ registers there, so sibling models do not each fail once.
+ """
+
+ if outcome.kind is not RawOutcomeKind.HTTP_ERROR or outcome.stream_started:
+ return
+ detail = f"{outcome.http_status} {outcome.error_code or outcome.error_type or 'error'}"[:64]
+ feature = EvidenceFeature.hosted(IMAGE_TOOL, "call")
+ if outcome.http_status in {400, 404} and machine_codes_name_model(outcome):
+ refused = [model_id]
+ elif outcome.http_status == 404:
+ refused = [
+ spec.id for spec in provider_image_models(source.vendor) if source.kind in spec.kinds
+ ] or [model_id]
+ else:
+ return
+ await self.record_hosted_refusals(source, [(refused_id, feature, detail) for refused_id in refused])
+
+ def _image_call_cost(
+ self,
+ source: ModelHubSourceConfig,
+ spec: ImageModelSpec,
+ *,
+ usage: Optional[ProtocolUsageReport],
+ images: int,
+ generation: Mapping[str, str] | None,
+ ) -> Optional[HostedCost]:
+ """One image call's cost: included, the list price per delivered image, else its tokens; None when unknown."""
+
+ if source.billing == "monthly":
+ return HostedCost(basis="included", usd=None)
+ size = (generation or {}).get("size")
+ quality = (generation or {}).get("quality")
+ matching = [
+ entry for entry in spec.prices
+ if entry.size in {None, size} and entry.quality in {None, quality}
+ ]
+ if matching and images:
+ # The most specific price that applies to what was delivered.
+ price = max(matching, key=lambda entry: (entry.size is not None) + (entry.quality is not None)).price
+ return HostedCost(basis="list", usd=round(price.usd_per_1k / 1000 * images, 6))
+ return self.hosted_call_cost(source, spec.id, (), usage=usage, counts={})
+
async def _executor_attempt(
self,
call: ExecutorCall,
@@ -6551,6 +6730,82 @@ class ModelHubService:
stream = executor_streams(source)
reader = ResponsesStreamReader() if stream else None
body = bytearray()
+
+ async def feed(chunk: bytes) -> None:
+ if reader is not None:
+ await asyncio.to_thread(reader.feed, chunk)
+ elif len(body) + len(chunk) > EXECUTOR_RESPONSE_MAX_BYTES:
+ raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")
+ else:
+ body.extend(chunk)
+
+ async def admitted_now() -> ModelHubSourceConfig | None:
+ final = await asyncio.to_thread(self._admitted_executor, slot, tool)
+ return final.source if final is not None else None
+
+ called = await self._hosted_upstream_call(
+ source, model_id, request, stream=stream, deadline=deadline, feed=feed, admitted_now=admitted_now,
+ )
+ if called is None:
+ return None
+ source = called.source
+ outcome = called.outcome
+ failed = _executor_failure(outcome, say, refused=called.refused)
+ if reader is not None:
+ result = await asyncio.to_thread(responses_result, tool, reader.readout, say, failed=failed)
+ elif failed is not None:
+ result = None
+ else:
+ # The bytearray itself goes to the worker: no copy of up to the response budget on the loop.
+ result = await asyncio.to_thread(anthropic_result, body, say)
+ # The call's cost is the pricing module's, from what the meter saw and what the provider reported.
+ counts, reported_usd = provider_charges(source.protocol, result.usage if result is not None else None)
+ cost = self.hosted_call_cost(
+ source, model_id, (tool,), usage=called.usage, counts=counts, reported_usd=reported_usd,
+ )
+ if outcome is not None and tool in outcome.hosted_tools and result is not None and result.record["status"] == "completed":
+ # A proxy call is a native call on the executor Source: the same positive evidence (§3.2).
+ await self.record_hosted_success(source, model_id, tool, "executor")
+ # A response that broke a bound reached nothing of Vibey's, so it is a failure before output here (§6
+ # step 4): the next candidate is tried. A timeout spent the chain's one deadline.
+ moves_on = called.refused is not None
+ if (
+ outcome is not None and outcome.kind is not RawOutcomeKind.SUCCESS
+ and called.refused is None and not called.timed_out
+ ):
+ moves_on = await self._executor_moves_on(source, model_id, tool, request, outcome)
+ return _ExecutorAttempt(
+ source=source,
+ model_id=model_id,
+ record=(
+ result.record if result is not None
+ else failed_record(failed or failure(say, "modelHub.hostedTools.unreadable"))
+ ),
+ cost=cost,
+ billable=called.billable,
+ moves_on=moves_on,
+ )
+
+ async def _hosted_upstream_call(
+ self,
+ source: ModelHubSourceConfig,
+ model_id: str,
+ request: ModelHubRequest,
+ *,
+ stream: bool,
+ deadline: float,
+ feed: Callable[[bytes], Awaitable[None]],
+ admitted_now: Callable[[], Awaitable[ModelHubSourceConfig | None]],
+ ) -> _HostedUpstreamCall | None:
+ """One upstream call a hosted tool makes on its own behalf; None when it was never admitted.
+
+ ``admitted_now`` admits the call again on the snapshot it is made on,
+ under the mutation lock. ``feed`` takes the response as it arrives and
+ raises ``ExecutorResponseRefused`` when it breaks a bound. The call is
+ metered on its Source however it ends, and it never settles Source
+ health: it is a tool call, not the turn's model hop.
+ """
+
handle = None
cancelled_observed: ProtocolSSEState | None = None
outcome: RawCallOutcome | None = None
@@ -6578,10 +6833,10 @@ class ModelHubService:
try:
# Admitted again on the snapshot the call is made on, under the lock. The call and
# everything it reports (billing, cost, the Source's name) follow that snapshot.
- final = await asyncio.to_thread(self._admitted_executor, slot, tool)
+ final = await admitted_now()
if final is None:
return
- source = final.source
+ source = final
if not self._engine_synced:
continue
try:
@@ -6602,12 +6857,7 @@ class ModelHubService:
if handle.stream is not None:
try:
async for chunk in handle.stream:
- if reader is not None:
- await asyncio.to_thread(reader.feed, chunk)
- elif len(body) + len(chunk) > EXECUTOR_RESPONSE_MAX_BYTES:
- raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")
- else:
- body.extend(chunk)
+ await feed(chunk)
except ExecutorResponseRefused as broken:
# The response broke a bound: the call failed, and nothing more
# of it is read. Its usage is still metered, from the outcome
@@ -6628,7 +6878,7 @@ class ModelHubService:
# not hold the call past its deadline or the gateway's shutdown.
await asyncio.wait_for(handle.close_stream(), timeout=ENGINE_TRANSPORT_TIMEOUT_SECONDS)
except (asyncio.TimeoutError, Exception):
- logger.warning("Model Hub hosted-tool executor stream did not close cleanly", exc_info=True)
+ logger.warning("Model Hub hosted-tool call stream did not close cleanly", exc_info=True)
finally:
if handle is not None or cancelled_observed is not None:
await self._meter_call(
@@ -6651,7 +6901,7 @@ class ModelHubService:
)
except ModelHubError as error:
if not admitted:
- logger.info("Model Hub hosted-tool executor was not reached: %s", error.code)
+ logger.info("Model Hub hosted-tool call was not reached: %s", error.code)
return None
outcome = RawCallOutcome(
kind=RawOutcomeKind.NETWORK_ERROR, http_status=None, error_code=error.code, redacted_message=None,
@@ -6671,39 +6921,17 @@ class ModelHubService:
raise cancelled
if not admitted:
return None
- failure = _executor_failure(outcome, say, refused=refused)
- if reader is not None:
- result = await asyncio.to_thread(responses_result, tool, reader.readout, say, failure=failure)
- elif failure is not None:
- result = None
- else:
- # The bytearray itself goes to the worker: no copy of up to the response budget on the loop.
- result = await asyncio.to_thread(anthropic_result, body, say)
usage = _call_usage(outcome, handle.observed if handle is not None else cancelled_observed)
- # The call's cost is the pricing module's, from what the meter saw and what the provider reported.
- counts, reported_usd = provider_charges(source.protocol, result.usage if result is not None else None)
- cost = self.hosted_call_cost(source, model_id, (tool,), usage=usage, counts=counts, reported_usd=reported_usd)
- if outcome is not None and tool in outcome.hosted_tools and result is not None and result.record["status"] == "completed":
- # A proxy call is a native call on the executor Source: the same positive evidence (§3.2).
- await self.record_hosted_success(source, model_id, tool, "executor")
- # A response that broke a bound reached nothing of Vibey's, so it is a failure before output here (§6
- # step 4): the next candidate is tried. A timeout spent the chain's one deadline.
- moves_on = refused is not None
- if outcome is not None and outcome.kind is not RawOutcomeKind.SUCCESS and refused is None and not timed_out:
- moves_on = await self._executor_moves_on(source, model_id, tool, request, outcome)
- return _ExecutorAttempt(
+ return _HostedUpstreamCall(
source=source,
- model_id=model_id,
- record=(
- result.record if result is not None
- else failed_record(failure or say("modelHub.hostedTools.unreadable"))
- ),
- cost=cost,
+ outcome=outcome,
+ refused=refused,
+ timed_out=timed_out,
+ usage=usage,
# A call that produced nothing and reported no tokens was not billed.
billable=usage is not None or (
outcome is not None and (outcome.stream_started or outcome.kind is RawOutcomeKind.SUCCESS)
),
- moves_on=moves_on,
)
async def _executor_moves_on(
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 887636a46..7ab89be2c 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -354,6 +354,14 @@ def _responses_terminal_event(
}
+def _images_terminal_event(
+ key: str,
+ message: str,
+ _next_sequence_number: int,
+) -> dict[str, object]:
+ return {"error": {"type": "server_error", "code": key, "message": message}}
+
+
def _chat_terminal_event(
key: str,
message: str,
@@ -829,6 +837,26 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
output_paths=(("completion_tokens",),),
),
),
+ # The engine's images endpoints (vibey-hosted-tools.md §7.4): a buffered JSON
+ # answer only; ``image_generate`` never streams, so nothing here is streamed.
+ "openai_images": ProtocolStreamTaxonomy(
+ terminal_envelopes=(),
+ model_output_envelopes=(),
+ success_literal=None,
+ sequence_number_path=None,
+ # https://platform.openai.com/docs/api-reference/images/object
+ buffered_error_envelope_paths=(("error",),),
+ buffered_output_array_path=("data",),
+ terminal_event_name=None,
+ render_terminal_event=_images_terminal_event,
+ usage=ProtocolUsageTaxonomy(
+ # https://platform.openai.com/docs/api-reference/images/object#images-object-usage
+ container_paths=(("usage",),),
+ input_paths=(("input_tokens",),),
+ cached_input_paths=(("input_tokens_details", "cached_tokens"),),
+ output_paths=(("output_tokens",),),
+ ),
+ ),
}
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 5d9a764ce..c690ba75c 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -46,7 +46,8 @@ from .provenance import (
render_turn_outcome_copy,
)
from .hosted_admission import PIN_MODEL_HEADER, PIN_SOURCE_HEADER, PIN_UNAVAILABLE_CODE
-from .hosted_turn import TurnHostedTools
+from .hosted_images import IMAGE_CALL_MAX_BYTES
+from .hosted_turn import IMAGE_TOOL, TurnHostedTools
from .request import FORWARDED_CALLER_HEADERS, ModelHubRequest
from .retry import RECOVERY_EXHAUSTED_CODE, RECOVERY_EXHAUSTED_MESSAGE
from .resolver import parse_model_hub_timestamp
@@ -710,6 +711,8 @@ class ModelHubTurnGateway:
token = self._authorized_token(request, "vibey")
if token is None:
return refused(401, "authentication_error")
+ tool = request.match_info["tool"]
+ image = tool == IMAGE_TOOL
def live_turn() -> tuple[str, TurnHostedTools | None] | None:
return self.correlation.live_hosted_turn(
@@ -720,13 +723,14 @@ class ModelHubTurnGateway:
if live_turn() is None:
return refused(409, "turn_not_live")
# Every step proportional to the request or the answer runs off the
- # controller loop; the call's arguments are small, so the body is bounded.
- # The bound is on the bytes parsed: an encoded body would be inflated
- # past it, and on the loop, before the check could see it.
+ # controller loop. A search call's arguments are small; an image call
+ # adds its reference images, each within read's inline limit. The bound
+ # is on the bytes parsed: an encoded body would be inflated past it, and
+ # on the loop, before the check could see it.
if (
request.headers.get("Content-Encoding", "identity").strip().lower() not in {"", "identity"}
or request.content_length is None
- or request.content_length > _HOSTED_TOOL_REQUEST_MAX_BYTES
+ or request.content_length > (IMAGE_CALL_MAX_BYTES if image else _HOSTED_TOOL_REQUEST_MAX_BYTES)
):
return refused(400, "invalid_request_error")
raw = await request.read()
@@ -741,15 +745,15 @@ class ModelHubTurnGateway:
return refused(409, "turn_not_live")
try:
with self._own_turn_call(live[0]):
- result = await self.service.run_hosted_tool(
- request.match_info["tool"],
- payload,
- # Only what the caller's live turn froze may run.
- turn=live[1],
- language=self._language_provider() or "en",
+ # Only what the caller's live turn froze may run.
+ language = self._language_provider() or "en"
+ result = await (
+ self.service.run_image_tool(payload, turn=live[1], language=language) if image
+ else self.service.run_hosted_tool(tool, payload, turn=live[1], language=language)
)
except ModelHubError as exc:
return refused(exc.status, exc.code)
+ # An image answer carries megabytes of base64: encode it off the loop.
body = await asyncio.to_thread(lambda: json.dumps(result).encode("utf-8"))
return web.Response(
body=body,
diff --git a/core/hosted_activity.py b/core/hosted_activity.py
index 8aa258dce..cd8d61423 100644
--- a/core/hosted_activity.py
+++ b/core/hosted_activity.py
@@ -54,7 +54,8 @@ class HostedActivity:
# How it ran: natively by the model's provider, by a search executor, or by an image endpoint directly.
mode: Literal["native", "proxy", "direct"]
status: str
- # Model-facing English; ``error_code`` names the reasons Avibe worded itself.
+ # The reason as text: the provider's own, or Avibe's, which always carries ``error_code``, the display key this
+ # module and the Web card render in the viewer's language (#2589).
error: Optional[str]
# What the call was about: the query, prompt, page or thread it named.
subject: Optional[str]
@@ -251,7 +252,8 @@ def proxy_activity(
return HostedActivity(
call_id=call.id,
tool=call.name,
- mode=execution.mode if execution is not None else "proxy",
+ # An image call is direct even when it was refused before it ran, with no execution to say so.
+ mode=execution.mode if execution is not None else ("direct" if call.name == "image_generate" else "proxy"),
status=result.record.status,
error=result.record.error,
error_code=result.record.error_code,
@@ -261,7 +263,12 @@ def proxy_activity(
provider=execution.executor_origin.provider if execution is not None else None,
source_id=execution.executor_source_id if execution is not None else None,
source_name=source_names(execution.executor_source_id) if execution is not None else None,
- model=execution.executor_origin.model if execution is not None else None,
+ model=(
+ execution.executor_origin.model
+ if execution is not None
+ # The model a refused image call named: it never moves to another (§7.4).
+ else ran.model if ran is not None else None
+ ),
sources=tuple(result.record.sources),
images=tuple(result.record.images or ()),
size=(ran.size if ran is not None and ran.size else size),
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index 526b3cf27..8d99133ec 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -47,10 +47,19 @@ commit input → loop:
Finality is decided before the response row is inserted, so a final (`result` or `error`) row is always the run's last
response. A final response with `stop_reason=length` is incomplete, even when it
-contains partial text or an image: commit it as `error`, preserve usable content,
+contains partial text: commit it as `error`, preserve usable content,
and end with an error of kind `length`. A no-answer length stop is not an
`empty_response`; the upstream already supplied the cause. Ordinary empty or
-reasoning-only `stop` responses still fail as `empty_response`. This does not
+reasoning-only `stop` responses still fail as `empty_response`, unless the run's
+calls generated images (a completed `image_generate` result): a final that ends
+normally then replies with them, delivered under their heading
+(`vibey-hosted-tools.md` §7.3). A refusal, safety or length stop stays a failure,
+its images still delivered. The loop decides whether a response replies once
+(`has_reply`), from the tool results as they committed (a settlement another
+writer won counts as it committed), and passes the decision to `append_response`
+as `replied`, with the images a final delivers as `images`. The row's type and
+display at commit carry both, so the committed final is the complete terminal
+reply even if delivery never runs; live settlement takes the same values. This does not
add a model call, increase an output limit, or replay a task. Non-final responses
with pending steer/follow-up keep continuing normally; truncated tool calls keep
the existing bounded reissue path without executing their partial arguments.
diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.json
index 8fc02c073..a5c33ddf9 100644
--- a/docs/plans/agent-core-contracts/message.schema.json
+++ b/docs/plans/agent-core-contracts/message.schema.json
@@ -943,7 +943,7 @@
"type": "string",
"minLength": 1,
"maxLength": 400,
- "description": "Bounded and redacted. Model-facing English: the provider's own reason, or one Avibe wrote."
+ "description": "Bounded and redacted: the reason as text, which the model reads, the provider's own or one Avibe wrote. Every reason Avibe writes carries an error_code, the display key surfaces render in the viewer's language (#2589); a reason without one is shown as written: the provider's own, or the gateway's no-provider reason, whose useful part (the providers to add) is that call's own fact and which Avibe writes in the user's language."
},
"error_code": {
"type": "string",
diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.md
index 8718ea1de..41539ca23 100644
--- a/docs/plans/agent-core-contracts/model-hub-consumer.md
+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md
@@ -158,7 +158,16 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
model (`model_not_found`) also writes negative `call` evidence for (Source, `executor_model`, tool). A
completed response that never ran the tool ends the chain. One deadline covers the whole chain (180 s).
- **An `image_generate` call** runs directly on the image endpoint of the (Source, model) the turn's frozen
- models name (`vibey-hosted-tools.md` §7.4).
+ models name (`vibey-hosted-tools.md` §7.4), admitted on the final snapshot; there is no chain and no
+ fallback. Its arguments are `{model, prompt, size?, images?, n?}`, `images` being at most 4 base64 strings,
+ each a supported image within `read`'s inline limit. An argument the model does not take, or a `size` in a
+ form it does not accept, is a `failed` record with `error_code: "image_param_unsupported"` naming the models
+ that take it; a model the snapshot no longer admits is one with `"image_model_unavailable"`. Nothing runs in
+ either case. The answer is `{"record", "execution"?, "images"?, "generation"?}`: `execution.mode` is
+ `direct`, with no `failed_attempts`; `images` is `[{"data": <base64>}]`, in order, only on a completed call,
+ and Vibey saves each one through its media sink and fills `record.images`; `generation` holds the
+ endpoint's own `size`, `quality` and `revised_prompt` when it reported them. A failed record names the
+ turn's other models. An endpoint that answers with URLs only is `failed`: the gateway never fetches one.
- Every outcome of a well-formed call is a 200 with `{"record", "execution"?}` in the
`ToolResultMessage.hosted` encoding. `execution` names the attempt whose response the record came from (the
last one tried when all failed), with its billing and cost; earlier billable attempts are listed in
@@ -167,7 +176,11 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
- Success is an allow-list: a call is `completed` only when the response says it completed (Responses
`status: completed`; Anthropic `end_turn` or `stop_sequence`) and nothing failed; a response that stopped
early is `incomplete`; any reported failure, or any other or missing ending, is `failed`. An unreadable
- response is `failed`. The record's `error` is in the user's language.
+ response is `failed`. The record's `error` is in the user's language, and every reason the gateway words
+ carries its `error_code` (`HOSTED_ERROR_CODES`), the key the surfaces show it by in their reader's language;
+ the provider's own detail, the Sources tried and an image call's other models stay in `error`. One reason has
+ no code: with no candidate, the record names the providers to add, which only that call knows, so it is shown
+ as written.
- The record's search `sources` keep the executor's order. A snippet is the answer text its citation belongs
to: the list item when that item cites only that source, else its sentence, with the citation markers
removed. An Anthropic result keeps its `cited_text`. X search lists the cited posts. A response's first 256
diff --git a/docs/plans/model-hub-capability-model.md b/docs/plans/model-hub-capability-model.md
index 04241225e..e5ac4715d 100644
--- a/docs/plans/model-hub-capability-model.md
+++ b/docs/plans/model-hub-capability-model.md
@@ -210,7 +210,7 @@ Fields of one vendor entry, mirrored by
| `wire_efforts` | a list of effort names, or `null` (or absent) to defer to models.dev |
| `hosted_tools` | optional; protocol (`anthropic`, `openai_responses`, `openai_chat`, `google`) → search tool (`web_search`, `x_search`) → `{declaration, price?, include?}`. `declaration` is required, has a `type`, and is sent verbatim. `price` is optional: absent means no list price is known, never zero. `include` lists Responses `include` values the tool needs (OpenAI web search: `web_search_call.action.sources`). v1's OpenAI `image_generation` entry is removed: no chat request declares a hosted image tool (`vibey-hosted-tools.md` §7). |
| `executor_model` | new, optional, at vendor scope (beside `models[]`): the vendor's lightweight model id that runs proxied search calls on this vendor's Sources (`vibey-hosted-tools.md` §6), e.g. a Haiku, mini or fast tier. The executor call's declaration and `include` are those of the family row that model id matches, on the Source's protocol. A vendor without it is never an executor. |
-| `image_models[]` | new, optional per vendor: `{id, description, endpoint: "images" \| "chat_image", params, size_forms, prices?, tokens_per_image?}`. `description` is the one line the `image_generate` enum shows; `endpoint` says how the gateway runs it (the engine's images endpoints, or the chat route with the image response modality); `params` lists which common parameters the model takes (`size`, `images`, `n`), and `size_forms` which forms of `size` it accepts (`pixels`, `ratio`); `prices[]` is optional, each entry a `price` with an `image` unit keyed by the `size` and `quality` it applies to (absent keys match any), so a vendor that prices sizes or qualities apart is valued at the size the call resolved. `tokens_per_image` is optional: the documented output tokens of one image, which the pricing module values at the model's output token rate as an estimate (shown with ≈) where no per-image price exists. Only models whose route the implementation verified through the shipped engine are listed. |
+| `image_models[]` | new, optional per vendor: `{id, description, params, size_forms, kinds?, request?, prices?, tokens_per_image?}`. Every image model runs through the engine's images endpoints (`/v1/images/generations`, or `/v1/images/edits` when the call carries reference images). `description` is the one line the `image_generate` enum shows; `params` lists which common parameters the model takes (`size`, `images`, `n`), and `size_forms` which forms of `size` it accepts (`pixels`, `ratio`); `kinds` names the credential kinds (`api_key`, `subscription`) its route was verified on, every kind when absent, so a subscription whose route is unverified is never offered the model; `request` holds the fixed scalar fields every call to it sends (an output format, base64 results), never a field the call names itself; `prices[]` is optional, each entry a `price` with an `image` unit keyed by the `size` and `quality` it applies to (absent keys match any), so a vendor that prices sizes or qualities apart is valued at the size the call resolved. `tokens_per_image` is optional: the documented output tokens of one image, which the pricing module values at the model's output token rate as an estimate (shown with ≈) where no per-image price exists. Only models whose route the implementation verified through the shipped engine are listed. |
| `price` | `unit` (`call`, `search`, `post`, `profile`, `image`), `usd_per_1k` ≥ 0, `as_of` (date) and `url` (https), all required; optional `extra[]` of `{unit, usd_per_1k}`. An `image` unit may carry `quality` and `size` when the vendor prices them apart. |
- The overlay records what the **provider** offers, and it is the prior every hop starts from: a hosted tool is
assumed where the overlay offers it, until a real request refuses it. Whether a Source (a relay, a subscription)
diff --git a/docs/plans/model-hub-contracts/provider-overlay.schema.json b/docs/plans/model-hub-contracts/provider-overlay.schema.json
index 133b7167f..c0b2a1dcd 100644
--- a/docs/plans/model-hub-contracts/provider-overlay.schema.json
+++ b/docs/plans/model-hub-contracts/provider-overlay.schema.json
@@ -210,7 +210,6 @@
"required": [
"id",
"description",
- "endpoint",
"params",
"size_forms"
],
@@ -226,13 +225,6 @@
"pattern": "^\\S(?:.*\\S)?$",
"description": "One short line; it goes into every request's tool block."
},
- "endpoint": {
- "enum": [
- "images",
- "chat_image"
- ],
- "description": "images: the engine's /v1/images/generations and /v1/images/edits; chat_image: the chat route with the image response modality."
- },
"params": {
"type": "array",
"uniqueItems": true,
@@ -256,6 +248,43 @@
},
"description": "Which forms of size the model accepts; non-empty exactly when params lists size."
},
+ "kinds": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": {
+ "enum": [
+ "api_key",
+ "subscription"
+ ]
+ },
+ "description": "The credential kinds the model's route was verified on through the shipped engine; absent means every kind. Every image model runs through the engine's /v1/images/generations and /v1/images/edits."
+ },
+ "request": {
+ "type": "object",
+ "propertyNames": {
+ "not": {
+ "enum": [
+ "model",
+ "prompt",
+ "size",
+ "aspect_ratio",
+ "n",
+ "images",
+ "stream"
+ ]
+ }
+ },
+ "additionalProperties": {
+ "type": [
+ "string",
+ "integer",
+ "number",
+ "boolean"
+ ]
+ },
+ "description": "Fixed fields every call to the model sends, such as an output format or base64 results; never a field a call names itself."
+ },
"prices": {
"type": "array",
"description": "Per-image list prices, each for the output size and quality it applies to (absent keys match any).",
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 3f9275015..71e70fb5e 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -150,13 +150,14 @@ The evidence store, its record and its owner are the capability model's §3. v2
- `Unsupported tool type: <type>` for a declared type → hosted tool `call`;
- `Invalid encrypted_content in search_result block` while the request replays a web-search result → `web_search`
`replay`;
- - **new:** an upstream image endpoint that refuses the model or the endpoint before producing anything (a 404, or a
- 400 naming the model or endpoint as unsupported, as a relay without the vendor's image endpoint answers) →
- `image_generate` `call` for that (Source, model); a refusal of the endpoint itself (the path is not served) is
- written for every image model the overlay lists for that Source on that endpoint kind, so sibling models do not
- each fail once. Only an upstream refusal counts: the images path goes through
- `_is_local_model_registration_failure`, and the engine's own refusals never teach, neither CPA's "only supported
- on /v1/images/generations and /v1/images/edits" nor a route 404 that Avibe's own engine config caused. The record
+ - **new:** an upstream image endpoint that refuses the model or the endpoint before producing anything →
+ `image_generate` `call`. A 400 or 404 whose machine code names the model (`model_not_found`, `unknown_model`) is
+ written for that (Source, model); any other 404 is a refusal of the endpoint itself (the path is not served, as a
+ relay without the vendor's image endpoint answers) and is written for every image model the Source registers
+ there, so sibling models do not each fail once. Only an upstream refusal counts: the images path goes through
+ `_is_local_model_registration_failure`, which recognizes the engine's own refusals as local, so they never
+ teach: neither "unknown provider for model <routed>" nor its images handler's "Model <routed> is not supported
+ on /v1/images/generations or /v1/images/edits". The record
is stamped and retired by the wire stamp like any negative. The enum drops that pair from the next turn (§7.2), and the refusal shows and
clears on the image card like a search refusal (§8.1);
- **new:** xAI's plain-text refusal of a replayed payload, `Could not decrypt the provided encrypted_content`,
@@ -549,8 +550,8 @@ E2E stay.
```json
{"name": "image_generate",
"parameters": {"type": "object", "required": ["model", "prompt"], "properties": {
- "model": {"enum": ["gpt-image-2", "grok-imagine-image", "gemini-3.1-flash-image"],
- "description": "gpt-image-2: … (default) · grok-imagine-image: … · gemini-3.1-flash-image: …"},
+ "model": {"enum": ["gpt-image-2", "gemini-2.5-flash-image", "gemini-3-pro-image-preview"],
+ "description": "gpt-image-2: … (default) · gemini-2.5-flash-image: … · gemini-3-pro-image-preview: …"},
"prompt": {"type": "string"},
"size": {"type": "string", "description": "e.g. 1024x1024, 1536x1024; or an aspect ratio such as 16:9"},
"images": {"type": "array", "items": {"type": "string"}, "maxItems": 4, "description": "paths of reference images to edit"},
@@ -606,24 +607,34 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
(relative to the session's cwd, under the same file permissions) and with its checks (a supported image type,
within `read`'s inline limit), and sends the bytes base64 in `images`. A path the agent could not `read` is
refused before any call, with a `failed` record whose error names the path.
-- **Per model kind** (the overlay entry says which):
- - **OpenAI gpt-image family** (an OpenAI API key, or the Codex subscription backend) and **xAI grok-imagine**:
- the engine's `/v1/images/generations`, or `/v1/images/edits` when `images` is present.
- - **Gemini image models** (Nano Banana): the chat route with the image response modality, on the Source's own
- protocol.
-- **Every route is unverified today** (gateway lane, 2026-10-15). The pinned engine (v8.0.23-3) contains the images
- code (the Codex executor's direct Image API path, `gpt-image-2` entries, `grok-imagine-image-quality`, and
- "model %s is only supported on /v1/images/generations and /v1/images/edits"), and `passthrough` keeps the images
- endpoints enabled. None of it is reachable from Avibe yet:
- - the engine adapter and `EngineClient` post only to the protocol endpoints, so they gain an images invoke path;
- - `stream_wire` has no images taxonomy (outcome and usage), so it gains one;
- - a custom (OpenAI-compatible chat) Source's image model needs the engine's per-model `image: true` flag, which
- `config.py` never writes.
-- **Route verification is the implementation's job, not the user's.** Each image path gets one hermetic engine E2E
- (the real engine, a stub upstream), like §7.1's harness: Codex OAuth images, an OpenAI API key, xAI
- grok-imagine, and a Gemini image model (e.g. Nano Banana 2, `gemini-3.1-flash-image`) through the chat route
- with the image modality. A model whose route is not verified ships without an overlay entry, so it is never
- offered and the UI never needs an "unverified" tag.
+- **One path: the engine's images endpoints.** Every image model runs through `/v1/images/generations`, or
+ `/v1/images/edits` when the call carries reference images, as a buffered JSON call (`EngineClient`'s
+ `openai_images` request protocol, with its own `stream_wire` taxonomy for the outcome and usage). The overlay
+ entry's `request` holds the fixed fields the model needs (JPEG at quality 90 for GPT Image, so a file fits `read`'s
+ inline cap; base64 results for Gemini), and the call adds `prompt`, `n`, `size` in pixels or `aspect_ratio` for a
+ ratio, and each reference image as a `data:` URL. An API-key Source's engine entry registers its vendor's image
+ models, and an OpenAI-compatible entry flags each with the engine's per-model `image: true`, without which the
+ engine's images handler refuses a non-GPT-Image name.
+- **What was verified** (gateway lane, 2026-10-15, the pinned engine v8.0.23-3 against a stub upstream,
+ `tests/e2e/test_model_hub_images.py`):
+ - **An OpenAI API key** (`gpt-image-2`): generations and edits reach `{base}/images/generations|edits` with the
+ body unchanged but for the bare model id, and the answer comes back byte for byte. The engine serves it through
+ its Codex executor's direct Image API path.
+ - **A Gemini API key** (`gemini-2.5-flash-image`, `gemini-3-pro-image-preview`): the flagged entry reaches
+ Google's OpenAI-compatible `images/generations`, the only image path Google documents on that layer (its chat
+ route does not return images for these models). No reference images: Google documents generation only.
+ - **xAI grok-imagine is not reachable**: the engine's images handler accepts an xAI image model only under an
+ empty, `xai` or `grok` prefix and then routes the bare id, which `force-model-prefix` never registers (unchanged
+ in v8.0.28). That 400 is the engine's own refusal, recognized as local, never learned. xAI ships with no image
+ models until the engine or the xAI rendering changes.
+ - **A Codex (ChatGPT) subscription is not offered images.** The engine runs it through the same direct Image API
+ function against `https://chatgpt.com/backend-api/codex`, a host no stub can stand in for (an OAuth auth file
+ takes no base URL), so no hermetic E2E verifies it. The overlay's `kinds: ["api_key"]` keeps the subscription
+ out. Codex CLI itself calls `chatgpt.com/backend-api/codex/images/generations`, so the path very likely works;
+ one real call at a release E2E, with the owner's approval, can turn it on.
+- **Route verification is the implementation's job, not the user's.** A model whose route is not verified ships
+ without an overlay entry, or without the credential kind it was not verified on, so it is never offered and the
+ UI never needs an "unverified" tag.
- **Authorized by the turn's enum.** The gateway resolves the Source from the turn's frozen `image_generate` enum
(§3.4): a model outside it is 409 `tool_not_enabled`, and the chosen (Source, model) is admitted on the final
snapshot (`runs_on`, identity, and no current refusal: a pair refused earlier in the turn fails locally with
@@ -636,12 +647,8 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
- **No idle cut for a buffered call.** The engine client's 120 s socket-read bound applies only to streamed calls on
the measured Sources, so a buffered images call longer than 120 s is not cut; the tool's call deadline bounds it.
If an images path ever streams partial images, those partials must keep feeding the idle bound.
-- **A Codex-subscription image runs through a chat model inside the engine.** The engine's Codex executor uses
- either the direct Image API or the hosted `image_generation` tool on a base model
- (`multimedia.gpt-image-2-base-model`, default `gpt-5.4-mini`), so such a call is billed and limited as a model
- call. The subscription E2E covers whichever path the engine takes.
-- **No silent fallback.** A failed call returns a `failed` record whose error names the alternatives ("gpt-image-2
- failed: <reason>. Available: grok-imagine-image, gemini-3.1-flash-image"). The model may call again with another
+- **No silent fallback.** A failed call returns a `failed` record whose error names the alternatives ("<reason>.
+ Available: gemini-2.5-flash-image, gemini-3-pro-image-preview"). The model may call again with another
model; the gateway never switches on its own.
- **The result names the model used**, in `ProxyExecution` and in the path record.
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index 694a0e86d..c98b90f29 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -61,7 +61,8 @@ from core.agent_core.harness.store import ContextEntry
from core.agent_core.tools.base import CallInstance
from core.agent_core.tools.jobs import call_instance
from core.agent_core.messages import (
- HOSTED_TOOLS,
+ HOSTED_RESULT_TOOLS,
+ HostedImage,
IMAGE_MIME_TYPES,
AssistantMessage,
TextBlock,
@@ -192,6 +193,10 @@ class _Run:
tool_calls: dict[str, ToolCallBlock] = field(default_factory=dict)
# This run's committed responses by row id, for delivering them; released with the run.
responses: dict[str, AssistantMessage] = field(default_factory=dict)
+ # The loop's decision for each response whether it replies (``has_reply``), committed with its row.
+ replied: dict[str, bool] = field(default_factory=dict)
+ # The images each final delivers with its reply, as committed with its row.
+ reply_images: dict[str, tuple[HostedImage, ...]] = field(default_factory=dict)
# Steer attempts ``Agent.steer`` accepted into this run: reconcile's in-process evidence.
accepted_steers: set[str] = field(default_factory=set)
stop_requested: bool = False
@@ -631,7 +636,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, self._gateway_client, self.media),
+ *hosted_tools(turn.router, self._gateway_client, self.media, language=self._language),
*suite.create_tools(agent.jobs, self.media.image_sink(session_id)),
)
)
@@ -694,11 +699,15 @@ class VibeyAgent(BaseAgent):
if run.stop_requested and reason == "aborted":
reason = "completed"
run_failed_after_commit = reason not in _COMPLETED
- failed = final_outcome(final) == "failed" or run_failed_after_commit
+ # Whether the final replies is the run's decision, committed with its row (``final_outcome``).
+ # Whether the final replies, and the images it delivers, are the run's, committed with its row.
+ replied = run.replied.get(run.final_row)
+ failed = final_outcome(final, replied=replied) == "failed" or run_failed_after_commit
if failed:
self._log_failure(run, reason, kind, origin, diagnostic)
- body, citations = self._display_with_citations(final, final=True)
- body = self._with_hosted_images(run, body)
+ body, citations = self._display_with_citations(
+ final, final=True, replied=bool(replied), images=run.reply_images.get(run.final_row, ())
+ )
if failed and not body.strip():
# A silent final whose run failed after the commit: like a final without text
# of its own (``_display_source``), its row carries the explanation.
@@ -1070,21 +1079,25 @@ class VibeyAgent(BaseAgent):
content = ([text_block(rendered)] if rendered or not images else []) + images
return UserMessage(content=tuple(content))
- def _display_source(self, message: AssistantMessage, *, final: bool) -> str:
+ def _display_source(
+ self, message: AssistantMessage, *, final: bool, replied: bool = False, images: Sequence[HostedImage] = ()
+ ) -> str:
"""The text a surface renders a response from: its text blocks without silent blocks.
Also the row's commit-time display (the store's renderer). A final without
text of its own (``final_outcome`` failed) is explained by localized copy:
the refusal or safety explanation, else the empty-reply one, so the row
- never shows nothing for a failed Turn (loop-control.md section 2).
+ never shows nothing for a failed Turn (loop-control.md section 2). A final
+ carries the images its Turn generated (``images``), so its committed row is
+ the complete reply even if delivery never runs.
"""
value = render_text(message)
- # A final whose reply is a generated image has no text to show; its image
- # is attached on delivery (``_with_hosted_images``), so there is nothing to explain.
- if final and not value.strip() and not has_reply(message):
+ # A final that replies without text replies with its Turn's images, so there is nothing to explain.
+ if final and not value.strip() and not replied:
kind = message.stop_reason if message.stop_reason in _EXPLAINED_STOPS else "empty_response"
- return error_text(kind, self._language())
- return strip_silent_blocks(value)
+ return self._with_images(error_text(kind, self._language()), images)
+ body = strip_silent_blocks(value)
+ return self._with_images(body, images) if final else body
async def _avibe_sections(self, request: AgentRequest, cwd: str) -> tuple[str, Optional[dict]]:
"""Avibe's injected prompt sections and the skill catalog they offered.
@@ -1219,7 +1232,7 @@ class VibeyAgent(BaseAgent):
logger.exception("Vibey could not show narration %s", row_id)
def _display_with_citations(
- self, message: AssistantMessage, *, final: bool
+ self, message: AssistantMessage, *, final: bool, replied: bool = False, images: Sequence[HostedImage] = ()
) -> tuple[str, Optional[CitationBundle]]:
"""The display text and, when the provider cited sources, the bundle that links them.
@@ -1229,24 +1242,24 @@ class VibeyAgent(BaseAgent):
"""
blocks = [(block.text, block.citations or ()) for block in message.content if isinstance(block, TextBlock) and block.text]
if not any(citations for _, citations in blocks):
- return self._display_source(message, final=final), None
+ return self._display_source(message, final=final, replied=replied, images=images), None
body, bundle = register_text_citations(
blocks,
unresolved_label=i18n_t("message.citationUnresolved", self._language()),
transform=strip_silent_blocks,
)
if final and not body.strip():
- return self._display_source(message, final=True), None
- return body, bundle
+ return self._display_source(message, final=True, replied=replied, images=images), None
+ return (self._with_images(body, images) if final else body), bundle
- def _with_hosted_images(self, run: _Run, body: str) -> str:
- """The final reply with the run's generated images attached, as file links.
+ def _with_images(self, body: str, images: Sequence[HostedImage]) -> str:
+ """A final reply with its Turn's generated images attached, as file links.
A file link is how every surface delivers a local file: IM uploads it as an
attachment, and the Web shows it inline from the same media token its card
registered. An image the reply already links is not attached twice.
"""
- links = self._hosted_image_links(run, body)
+ links = self._image_links([(image.path, Path(image.path).name) for image in images], body)
if not links:
return body
# A reply that is only images still says what it carries, as the Codex backend's does.
@@ -1254,15 +1267,15 @@ class VibeyAgent(BaseAgent):
return f"{lead}\n\n{links}"
@staticmethod
- def _hosted_image_links(run: _Run, body: str) -> str:
- """File links for the run's images that ``body`` does not already link.
+ def _image_links(images: Sequence[tuple[str, str]], body: str) -> str:
+ """File links for the ``(path, label)`` images that ``body`` does not already link.
Only a link counts: the model is given each image's path as text, and a
reply that mentions it in prose has still not delivered the file. A path
that is not absolute names no file a surface could send, so it is skipped.
"""
links = []
- for path, label in run.hosted_images:
+ for path, label in images:
if not os.path.isabs(path):
logger.warning("Vibey skipped a hosted image with a relative path: %s", path)
continue
@@ -1275,7 +1288,7 @@ class VibeyAgent(BaseAgent):
async def _emit_orphan_images(self, run: _Run) -> None:
"""A run's generated images when it ends with no final reply to carry them."""
- links = self._hosted_image_links(run, "")
+ links = self._image_links(run.hosted_images, "")
if not links:
return
try:
@@ -1320,7 +1333,7 @@ class VibeyAgent(BaseAgent):
"""A proxied hosted call, once its result is committed: the record its executor returned."""
call = run.tool_calls.get(event.tool_call_id)
started = run.tool_started.pop(event.tool_call_id, None)
- if call is None or call.name not in HOSTED_TOOLS:
+ if call is None or call.name not in HOSTED_RESULT_TOOLS:
return
try:
result = await asyncio.to_thread(self._committed_tool_result, event.event_id)
@@ -1347,7 +1360,7 @@ class VibeyAgent(BaseAgent):
return message if isinstance(message, ToolResultMessage) else None
async def _emit_tool_started(self, run: _Run, event: ToolStarted) -> None:
- if event.name in HOSTED_TOOLS:
+ if event.name in HOSTED_RESULT_TOOLS:
# A proxied hosted call shows once, as its card, when its result lands.
return
call = run.tool_calls.get(event.tool_call_id)
@@ -1366,12 +1379,23 @@ class VibeyAgent(BaseAgent):
except Exception:
logger.exception("Vibey could not show tool %s", name)
- def _on_response(self, session_id: str, row_id: str, message: AssistantMessage) -> None:
+ def _on_response(
+ self,
+ session_id: str,
+ row_id: str,
+ message: AssistantMessage,
+ replied: Optional[bool],
+ images: tuple[HostedImage, ...] = (),
+ ) -> None:
"""A response committed for the Session's run: keep what its delivery and tool events need."""
run = self._run_for(session_id, None)
if run is None:
return
run.responses[row_id] = message
+ if replied is not None:
+ run.replied[row_id] = replied
+ if images:
+ run.reply_images[row_id] = images
run.tool_calls.update({call.id: call for call in message.tool_calls})
self._note_tokens(run, message)
diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.py
index c4bcfd47a..438c206e6 100644
--- a/modules/agents/vibey/store.py
+++ b/modules/agents/vibey/store.py
@@ -13,7 +13,8 @@ Two adapter rules live at this boundary, where the loop consumes an input:
after the backend accepts the steer. The loop can reach that input first, so
consumption waits, bounded, for the row to exist.
-Each committed response is handed to ``on_response`` once, for the run that
+Each committed response is handed to ``on_response`` once, with the loop's
+decision whether it replies and the images a final delivers, for the run that
owns it; nothing here keeps responses after that.
"""
@@ -30,7 +31,7 @@ from sqlalchemy.engine import Engine
from core.agent_core.harness.projection import context_view
from core.agent_core.harness.store import ContextEntry
-from core.agent_core.messages import AssistantMessage, ToolResultMessage, UserMessage
+from core.agent_core.messages import AssistantMessage, HostedImage, ToolResultMessage, UserMessage
from modules.agents.vibey.prompt import (
EnvironmentValue,
displayed_environment,
@@ -43,7 +44,7 @@ from storage.agent_transcript import SQLiteTranscriptStore, fork_link
from storage.models import agent_sessions, messages
EnvironmentSource = Callable[[str], Mapping[str, EnvironmentValue]]
-ResponseObserver = Callable[[str, str, AssistantMessage], None]
+ResponseObserver = Callable[[str, str, AssistantMessage, Optional[bool], tuple[HostedImage, ...]], None]
#: How long consumption waits for an accepted steer's row before failing the run.
INPUT_ROW_TIMEOUT_S = 10.0
@@ -122,12 +123,25 @@ class AdapterTranscriptStore:
return entry
async def append_response(
- self, session_id: str, message: AssistantMessage, *, final: bool, request: Optional[Mapping[str, Any]] = None
+ self,
+ session_id: str,
+ message: AssistantMessage,
+ *,
+ final: bool,
+ request: Optional[Mapping[str, Any]] = None,
+ replied: Optional[bool] = None,
+ images: Sequence[HostedImage] = (),
) -> ContextEntry:
entry = await self._store.append_response(
- session_id, message, final=final, request=request, agent_name=self._agents.get(session_id)
+ session_id,
+ message,
+ final=final,
+ request=request,
+ replied=replied,
+ images=images,
+ agent_name=self._agents.get(session_id),
)
- self._on_response(session_id, entry.row_id, message)
+ self._on_response(session_id, entry.row_id, message, replied, tuple(images))
return entry
async def append_tool_result(
diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.py
index dd16f1919..36ba3cd0c 100644
--- a/modules/agents/vibey/tools.py
+++ b/modules/agents/vibey/tools.py
@@ -16,6 +16,9 @@ keeps the command in the foreground.
from __future__ import annotations
import asyncio
+import base64
+import json
+import re
from dataclasses import dataclass, field, replace
from typing import Any, Awaitable, Callable, Mapping, Optional, Sequence
@@ -24,8 +27,9 @@ import httpx
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 failure, generate_action, image_dimensions, record_text
-from core.agent_core.ai.provider import MediaSink, ModelEndpoint
+from core.agent_core.ai.provider import ImageModel, ImageModels, MediaSink, ModelEndpoint
from core.agent_core.messages import (
+ HostedAction,
HostedImage,
HostedRecord,
HostedResult,
@@ -34,9 +38,12 @@ from core.agent_core.messages import (
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.hosted import MAX_IMAGES, hosted_tool_spec, image_generate_spec, size_form
+from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES, ImageUnreadable, read_image
+from core.agent_core.tools.truncate import format_size
from core.agent_core.tools.shell import default_shell
from modules.agents.vibey.models import HubModelRouter
+from vibe.i18n import t as i18n_t
ImageSink = Callable[[bytes, str, str], Awaitable[str]]
#: Whether a job's tool call has a durable ``tool_result`` (the adapter's half of J5).
@@ -109,13 +116,9 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOver
)
-#: The search tools a Turn registers, each serving both modes (§4.1).
-PARSED_HOSTED_TOOLS = ("web_search", "x_search")
-
-
@dataclass(frozen=True)
class HostedTool:
- """One hosted tool of the Turn (``vibey-hosted-tools.md`` §3.4, §4.1), with one name and schema in both modes.
+ """One search tool of the Turn (``vibey-hosted-tools.md`` §3.4, §4.1), with one name and schema in both modes.
On a hop whose route for it is native, the adapter sends the provider's declaration in its spec's place and the
provider runs the call. A call that reaches ``execute`` is proxied: the gateway runs it on its executor chain,
@@ -128,59 +131,72 @@ class HostedTool:
#: call. A re-resolve can move the Turn to another Source, and the gateway answers only the hop it now holds.
route: Callable[[], 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))
- # 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)
-
- async def _run(self, arguments: dict[str, Any]) -> HostedResult:
- endpoint = self.route()
- url = join_endpoint_url(endpoint.base_url, f"/hosted-tools/{self.spec.name}")
- body = {"arguments": arguments}
- headers = auth_headers(endpoint, provider="openai", gateway=True)
- # The gateway bounds the call (180 s for a search); only connecting is bounded here.
- timeout = httpx.Timeout(None, connect=CONNECT_TIMEOUT_S)
- try:
- if self.client is not None:
- response = await self.client.post(url, json=body, headers=headers, timeout=timeout)
- else:
- # The Model Hub gateway is loopback: an environment or system proxy must never carry it.
- 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:
- reason = f"the gateway could not run the call ({type(error).__name__})"
- return _failed(self.spec.name, reason, "gateway_unreachable")
- if response.status_code != 200:
- reason = f"the gateway refused the call (HTTP {response.status_code} {_error_code(response)})"
- return _failed(self.spec.name, reason, "gateway_refused")
+ hosted, _ = await _gateway_call(self.route(), self.client, self.spec.name, dict(arguments))
+ query = arguments.get("query")
+ return _result(self.spec.name, hosted, query=query if isinstance(query, str) else None)
+
+
+@dataclass(frozen=True)
+class ImageGenerateTool:
+ """``image_generate`` (``vibey-hosted-tools.md`` §7): one of the Turn's image models, called directly on the
+ gateway's image endpoint, never through a chat model.
+
+ The Turn's first resolution freezes ``models``, the enum the spec offers (§3.4). A call that names a model outside
+ them, or an argument its model does not take, fails before anything runs; reference images are read as ``read``
+ reads them. The images the endpoint returns are saved through the media sink, and the model reads where they are.
+ """
+
+ spec: ToolSpec
+ models: ImageModels
+ #: The hop the Turn runs on now: where the executor endpoint lives, and the token and headers that authorize the
+ #: call. A re-resolve can move the Turn to another Source, and the gateway answers only the hop it now holds.
+ route: Callable[[], ModelEndpoint] = field(repr=False)
+ client: Optional[httpx.AsyncClient] = field(default=None, repr=False)
+ media: Optional[MediaSink] = field(default=None, repr=False)
+ #: The user's language, in which the tool words the reasons it writes (the gateway words its own the same way).
+ language: Callable[[], str] = field(default=lambda: "en", repr=False)
+
+ async def execute(self, arguments: Mapping[str, Any], ctx: ToolContext) -> ToolResult:
+ model, prompt = arguments.get("model"), arguments.get("prompt")
+ hosted = await self._run(dict(arguments), ctx.cwd)
+ if isinstance(model, str) and model:
+ # The model the call ran on, or was refused for: the call never moves to another (§7.4).
+ ran = hosted.action or HostedAction("generate")
+ hosted = replace(hosted, action=replace(ran, model=model))
+ notes = (_image_facts(hosted),) if hosted.record.status == "completed" else ()
+ return _result(self.spec.name, hosted, query=prompt if isinstance(prompt, str) else None, notes=notes)
+
+ def _say(self, key: str, **params: str) -> str:
+ return i18n_t(key, self.language(), **params)
+
+ async def _run(self, arguments: dict[str, Any], cwd: str) -> HostedResult:
+ refusal = _image_refusal(self.models, arguments, self._say)
+ if refusal is not None:
+ return _failed(self.spec.name, *refusal)
try:
- # 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(self.spec.name, "the gateway answered with no hosted result", "gateway_no_result")
- if self.spec.name == "image_generate" and hosted.record.status == "completed":
- hosted = await self._saved(hosted, answer)
- return hosted
+ references = await asyncio.to_thread(_reference_images, arguments.get("images") or (), cwd)
+ except _ReferenceUnreadable as refused:
+ return _failed(self.spec.name, _reference_refusal(refused, self._say), "image_reference_unreadable")
+ if references:
+ arguments["images"] = references
+ hosted, answer = await _gateway_call(self.route(), self.client, self.spec.name, arguments)
+ if answer is None or hosted.record.status != "completed":
+ return hosted
+ return await self._saved(hosted, answer)
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."""
+ """The endpoint's images, saved through the media sink (§7.3): the record lists the files. 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"))
images = answer.get("images")
if not isinstance(images, list) or not images:
- failed = _failed_record(self.spec.name, "the executor returned no image", "executor_no_image")
+ failed = _failed_record(self.spec.name, "the endpoint returned no image", "executor_no_image")
return replace(hosted, record=failed)
if self.media is None:
failed = _failed_record(self.spec.name, "nothing here can keep a generated image", "image_no_store")
@@ -190,23 +206,184 @@ class HostedTool:
for item in images:
encoded = item.get("data") if isinstance(item, Mapping) else None
if not isinstance(encoded, str):
- raise ValueError("the executor's image is not base64 text")
+ raise ValueError("the endpoint's image is not base64 text")
saved.append(replace(await self.media.save_image(encoded), width=width, height=height))
except (ValueError, OSError) as error:
failed = _failed_record(self.spec.name, f"the image could not be saved: {error}", "image_not_saved")
return replace(hosted, record=failed)
- # The executor's rendered prompt and resolved size and quality: where a native call's block carries them.
+ # What the endpoint reports it did: its revision of the prompt and the delivered size and quality.
return replace(hosted, record=replace(hosted.record, images=tuple(saved)), action=generate_action(generation))
-def _failed_record(tool: str, reason: str, code: str) -> HostedRecord:
+_IMAGE_ARGUMENTS = ("model", "prompt", "size", "images", "n")
+#: Words a reason the image tool writes, in the user's language: ``say(key, **params)``.
+Say = Callable[..., str]
+
+
+def _image_refusal(models: ImageModels, arguments: dict[str, Any], say: Say) -> Optional[tuple[str, str]]:
+ """Why the Turn's frozen image models refuse ``arguments`` before anything runs (§7.2), worded by ``say``, with the
+ error code every reason Avibe writes carries, which a surface shows in its reader's language (#2589); None when
+ the call may go out. It refuses what the gateway, the execution boundary,
+ would, so a bad call costs nothing, and words the reasons the gateway also writes as the gateway does; a refusal
+ names the models that do take the call. An empty ``images`` is no reference image, and is left out of the call."""
+
+ if arguments.get("images") == []:
+ del arguments["images"]
+ unknown = sorted(set(arguments) - set(_IMAGE_ARGUMENTS))
+ if unknown:
+ return say("hostedTools.image.unknownArguments", names=", ".join(unknown)), "image_argument_invalid"
+ chosen = next((model for model in models.models if model.model_id == arguments.get("model")), None)
+ if chosen is None:
+ available = ", ".join(model.model_id for model in models.models)
+ reason = say("hostedTools.image.notOffered", model=str(arguments.get("model")))
+ return f"{reason} {say('modelHub.hostedTools.imageAlternatives', models=available)}", "image_model_unavailable"
+ prompt = arguments.get("prompt")
+ if not isinstance(prompt, str) or not prompt.strip():
+ return say("hostedTools.image.noPrompt"), "image_argument_invalid"
+ if "size" in arguments and size_form(arguments["size"]) is None:
+ forms = {form: say(f"hostedTools.image.form.{form}") for form in ("pixels", "ratio")}
+ return say("hostedTools.image.sizeForm", **forms), "image_argument_invalid"
+ images = arguments.get("images")
+ if "images" in arguments and (
+ not isinstance(images, list) or not all(isinstance(path, str) and path for path in images) or len(images) > MAX_IMAGES
+ ):
+ return say("hostedTools.image.badImages", max=str(MAX_IMAGES)), "image_argument_invalid"
+ n = arguments.get("n", 1)
+ if isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= MAX_IMAGES:
+ return say("hostedTools.image.badCount", max=str(MAX_IMAGES)), "image_argument_invalid"
+ unsupported = _unsupported(chosen, arguments)
+ if unsupported is None:
+ return None
+ if unsupported == "size" and "size" in chosen.params:
+ # Two forms exist, so a model that refuses one takes the other.
+ (form,) = chosen.size_forms
+ reason = say(
+ "hostedTools.image.sizeFormUnsupported",
+ model=chosen.model_id,
+ size=str(arguments["size"]),
+ form=say(f"hostedTools.image.form.{form}"),
+ )
+ else:
+ reason = say("modelHub.hostedTools.imageParamUnsupported", model=chosen.model_id, param=unsupported)
+ takers = [model.model_id for model in models.models if _unsupported(model, arguments) is None]
+ if takers:
+ reason += " " + say("modelHub.hostedTools.imageParamTakers", models=", ".join(takers))
+ return reason, "image_param_unsupported"
+
+
+def _unsupported(model: ImageModel, arguments: Mapping[str, Any]) -> Optional[str]:
+ """The first optional argument ``model`` does not take, or ``size`` in a form it does not accept."""
+
+ for param in ("images", "n", "size"):
+ if param in arguments and param not in model.params:
+ return param
+ if "size" in arguments and size_form(arguments["size"]) not in model.size_forms:
+ return "size"
+ return None
+
+
+class _ReferenceUnreadable(Exception):
+ def __init__(self, path: str, error: ImageUnreadable) -> None:
+ super().__init__(path)
+ self.path, self.error = path, error
+
+
+def _reference_images(paths: Sequence[str], cwd: str) -> list[str]:
+ """The reference images at ``paths``, base64, each read as ``read`` reads it (§7.4). Blocking."""
+
+ encoded = []
+ for path in paths:
+ try:
+ _, data = read_image(path, cwd)
+ except ImageUnreadable as error:
+ raise _ReferenceUnreadable(path, error) from None
+ encoded.append(base64.b64encode(data).decode("ascii"))
+ return encoded
+
+
+def _reference_refusal(refused: _ReferenceUnreadable, say: Say) -> str:
+ """Why a reference image cannot be sent, worded by ``say``; the system's own words for a file it could not open."""
+
+ error, path = refused.error, refused.path
+ if error.kind == "not_image":
+ return say("hostedTools.image.reference.notImage", path=path)
+ if error.kind == "too_large" and error.size is not None:
+ limit = format_size(MAX_INLINE_IMAGE_BYTES)
+ return say("hostedTools.image.reference.tooLarge", path=path, size=format_size(error.size), limit=limit)
+ if error.kind == "unsupported":
+ return say("hostedTools.image.reference.unsupported", path=path, mime=error.mime_type or "")
+ return say("hostedTools.image.reference.unreadable", path=path, reason=error.reason)
+
+
+def _image_facts(hosted: HostedResult) -> str:
+ """The line of a generated image's record that says what made it and what it cost (§7.3)."""
+
+ model = hosted.action.model if hosted.action is not None else None
+ execution = hosted.execution
+ facts = [f"Model: {model}" if model else "Model: unknown"]
+ if execution is not None:
+ facts[0] += f" via {execution.executor_origin.provider}"
+ cost = execution.cost
+ if cost is not None and cost.usd is None:
+ facts.append("cost: included in the subscription")
+ elif cost is not None:
+ facts.append(f"cost: {'' if cost.basis == 'reported' else '≈ '}${_usd(cost.usd)}")
+ return " · ".join(facts)
+
+
+def _usd(value: float) -> str:
+ # Small per-call figures keep their first significant digits: $0.006, not $0.01.
+ return f"{value:.2f}" if value >= 0.1 else f"{value:.4f}".rstrip("0").rstrip(".")
+
+
+def _result(tool: str, hosted: HostedResult, *, query: Optional[str], notes: Sequence[str] = ()) -> ToolResult:
+ """A hosted call's result: its record, and the text the model reads, rendered as a replayed call's is."""
+
+ text = record_text(tool, hosted.record, query=query, notes=notes)
+ failed = hosted.record.status in ("failed", "incomplete")
+ return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted)
+
+
+async def _gateway_call(
+ endpoint: ModelEndpoint, client: Optional[httpx.AsyncClient], tool: str, arguments: Mapping[str, Any]
+) -> tuple[HostedResult, Optional[Mapping[str, Any]]]:
+ """One call on the gateway's executor endpoint (§6, §7.4): its result, and the answer it was read from (None
+ when the gateway gave none)."""
+
+ url = join_endpoint_url(endpoint.base_url, f"/hosted-tools/{tool}")
+ # Reference images make the body megabytes of base64: serialized off the controller loop.
+ content = await asyncio.to_thread(json.dumps, {"arguments": dict(arguments)})
+ headers = {**auth_headers(endpoint, provider="openai", gateway=True), "content-type": "application/json"}
+ # The gateway bounds the call; only connecting is bounded here.
+ timeout = httpx.Timeout(None, connect=CONNECT_TIMEOUT_S)
+ try:
+ if client is not None:
+ response = await client.post(url, content=content, headers=headers, timeout=timeout)
+ else:
+ # The Model Hub gateway is loopback: an environment or system proxy must never carry it.
+ async with httpx.AsyncClient(timeout=timeout, trust_env=False) as own:
+ response = await own.post(url, content=content, headers=headers)
+ except httpx.HTTPError as error:
+ return _failed(tool, f"the gateway could not run the call ({type(error).__name__})", "gateway_unreachable"), None
+ if response.status_code != 200:
+ reason = f"the gateway refused the call (HTTP {response.status_code} {_error_code(response)})"
+ return _failed(tool, reason, "gateway_refused"), None
+ try:
+ # An image's answer carries megabytes of base64: parsed off the controller loop.
+ answer = await asyncio.to_thread(response.json)
+ return _hosted_result(tool, answer), answer
+ except (TypeError, ValueError):
+ return _failed(tool, "the gateway answered with no hosted result", "gateway_no_result"), None
+
+
+def _failed_record(tool: str, reason: str, code: Optional[str]) -> HostedRecord:
error, error_code = failure(reason, code)
return HostedRecord(
status="failed", error=error, error_code=error_code, images=() if tool == "image_generate" else None
)
-def _failed(tool: str, reason: str, code: str) -> HostedResult:
+def _failed(tool: str, reason: str, code: Optional[str]) -> HostedResult:
"""A call that never reached an executor: a failed record, and no execution (§4.2)."""
return HostedResult(record=_failed_record(tool, reason, code))
@@ -249,19 +426,23 @@ def hosted_tools(
router: HubModelRouter,
client: Optional[httpx.AsyncClient] = None,
media: Optional[MediaSink] = None,
+ *,
+ language: Callable[[], str] = lambda: "en",
) -> 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. Each call goes out on the hop the Turn runs on then (``HubModelRouter.current``)."""
+ """The Turn's hosted tools from its first resolution (§3.4): every search tool the user enabled, in Model Hub's
+ order, whatever a hop runs it as, then ``image_generate`` when an image model is available. They lead the Turn's
+ tools, so its last tool stays a local one whatever a hop renders them as, and the list and the image enum stay the
+ same for the whole Turn. Each call goes out on the hop the Turn runs on then (``HubModelRouter.current``)."""
if router.preflight is None:
return ()
+ frozen = router.preflight.endpoint
def route() -> ModelEndpoint:
return router.current.endpoint
- return tuple(
- HostedTool(hosted_tool_spec(name), route, client, media)
- for name in router.preflight.endpoint.hosted_tools
- if name in PARSED_HOSTED_TOOLS
- )
+ tools: list[Tool] = [HostedTool(hosted_tool_spec(name), route, client) for name in frozen.hosted_tools]
+ if frozen.image_models is not None:
+ spec = image_generate_spec(frozen.image_models)
+ tools.append(ImageGenerateTool(spec, frozen.image_models, route, client, media, language))
+ return tuple(tools)
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 8c6f7d1d5..920bc9c97 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -76,6 +76,7 @@ from core.agent_core.harness.projection import open_tool_calls
from core.agent_core.harness.store import ContextEntry, EntryKind
from core.agent_core.messages import (
AssistantMessage,
+ HostedImage,
HostedToolBlock,
TextBlock,
ToolResultMessage,
@@ -115,33 +116,40 @@ _EVENT_TYPE_BY_KIND: dict[str, str] = {
}
_KIND_BY_EVENT_TYPE = {event_type: kind for kind, event_type in _EVENT_TYPE_BY_KIND.items()}
-# ``render(message, final=...)``: a response row's commit-time display text.
+# ``render(message, final=..., replied=..., images=...)``: a response row's commit-time display text; ``replied`` is
+# the decision ``final_outcome`` takes, and ``images`` those a final delivers with its reply.
DisplayRenderer = Callable[..., str]
_T = TypeVar("_T")
FinalOutcome = Literal["completed", "failed"]
-def final_outcome(message: AssistantMessage) -> FinalOutcome:
- """The Turn outcome a committed final response determines by itself.
+def final_outcome(message: AssistantMessage, *, replied: Optional[bool] = None) -> FinalOutcome:
+ """The Turn outcome of a committed final response.
The one rule, shared by the row's type at commit and live settlement: a final
- reply without usable content, or explicitly stopped at its output limit,
- failed. Partial text must not turn a provider's incomplete final into a
- successful result. Pending-input responses are not finals. Failures only
- a live run can observe after the commit are applied by the live caller.
+ that does not reply, or explicitly stopped at its output limit, failed. Whether
+ it replies is the loop's decision (``has_reply``), taken as given; without one
+ (``replied`` None), the response alone decides. Partial text must not turn a
+ provider's incomplete final into a successful result. Pending-input responses
+ are not finals. Failures only a live run can observe after the commit are
+ applied by the live caller.
"""
- return "completed" if has_reply(message) and message.stop_reason != "length" else "failed"
+ if replied is None:
+ replied = has_reply(message)
+ return "completed" if replied and message.stop_reason != "length" else "failed"
-def _response_type(message: AssistantMessage, *, final: bool, display_text: str) -> str:
+def _response_type(message: AssistantMessage, *, final: bool, display_text: str, replied: bool) -> str:
if not final:
return "assistant"
- if final_outcome(message) == "failed":
+ if final_outcome(message, replied=replied) == "failed":
return "error"
return "result" if display_text.strip() else "assistant"
-def render_text(message: AssistantMessage, *, final: bool = False) -> str:
+def render_text(
+ message: AssistantMessage, *, final: bool = False, replied: bool = True, images: Sequence[HostedImage] = ()
+) -> str:
"""Default display copy of a response: its text blocks, verbatim, in order."""
return "\n\n".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
@@ -229,6 +237,8 @@ class SQLiteTranscriptStore:
*,
final: bool,
request: Optional[Mapping[str, Any]] = None,
+ replied: Optional[bool] = None,
+ images: Sequence[HostedImage] = (),
agent_name: Optional[str] = None,
) -> ContextEntry:
if not isinstance(message, AssistantMessage):
@@ -237,7 +247,9 @@ class SQLiteTranscriptStore:
if request is not None:
response["request"] = dict(request) # C-9 ``ModelResponse.request``: the anchor's request facts
model = _canonical(response, "response")
- display_text = self._render(message, final=final)
+ if replied is None:
+ replied = has_reply(message)
+ display_text = self._render(message, final=final, replied=replied, images=tuple(images))
def work(conn: Connection) -> ContextEntry:
origin = _turn_origin(conn, session_id, agent_name)
@@ -250,7 +262,7 @@ class SQLiteTranscriptStore:
author="agent",
source="agent",
author_name=origin.agent_name,
- message_type=_response_type(message, final=final, display_text=display_text),
+ message_type=_response_type(message, final=final, display_text=display_text, replied=replied),
text=display_text,
content={"model": model},
)
diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.py
index 7db4e0eeb..1a4c6057e 100644
--- a/tests/agent_core/agent/test_loop.py
+++ b/tests/agent_core/agent/test_loop.py
@@ -66,6 +66,7 @@ from core.agent_core.messages import (
)
from core.agent_core.tools.base import CallInstance, ToolResult
from tests.agent_core.fakes import (
+ ORIGIN,
FakeJobHost,
FakeModelRouter,
FakeTool,
@@ -446,11 +447,11 @@ async def test_C4_pending_steer_prevents_finality_and_late_steer_is_refused_duri
super().__init__()
self.final_entered, self.final_release = asyncio.Event(), asyncio.Event()
- async def append_response(self, session_id, message, *, final):
+ async def append_response(self, session_id, message, *, final, replied=None, images=()):
if final:
self.final_entered.set()
await self.final_release.wait()
- return await super().append_response(session_id, message, final=final)
+ return await super().append_response(session_id, message, final=final, replied=replied, images=images)
entered, release = asyncio.Event(), asyncio.Event()
@@ -785,7 +786,7 @@ async def test_retry_keeps_a_usage_only_partial_out_of_the_context():
class _FailingResponses(InMemoryTranscriptStore):
- async def append_response(self, session_id, message, *, final, request=None):
+ async def append_response(self, session_id, message, *, final, request=None, replied=None, images=()):
raise RuntimeError("disk full")
@@ -1379,7 +1380,7 @@ async def test_failed_queued_input_commit_keeps_pending_input_and_announces_prio
async def test_partial_response_commit_failure_still_emits_a_terminal_error():
class Store(InMemoryTranscriptStore):
- async def append_response(self, session_id, message, *, final):
+ async def append_response(self, session_id, message, *, final, replied=None, images=()):
raise OSError("response persistence unavailable")
provider = ScriptedProvider(
@@ -1921,3 +1922,38 @@ async def test_a_terminating_call_ends_the_run_after_its_whole_group_commits():
assert await committed_results(agent) == [("a", "a", False), ("b", "b", False)]
assert events[-1].reason == "completed" and len(agent.models.provider.requests) == 1
+
+
+def _image_result(call_id: str, *, completed: bool) -> ToolResultMessage:
+ from core.agent_core.messages import HostedResult, ProxyExecution
+
+ if completed:
+ record = HostedRecord(status="completed", images=(HostedImage(path="/media/winner.png", mime="image/png"),))
+ execution = ProxyExecution(ORIGIN, "src_executor01", "metered", mode="direct")
+ return ToolResultMessage(call_id, "image_generate", (text("saved"),), hosted=HostedResult(record, execution))
+ record = HostedRecord(status="failed", error="refused", images=())
+ return ToolResultMessage(call_id, "image_generate", (text("failed"),), True, hosted=HostedResult(record))
+
+
[email protected](("ours", "theirs"), [(False, True), (True, False)], ids=["they-saved-it", "they-failed-it"])
+async def test_a_reply_counts_the_images_of_the_tool_result_that_committed_not_the_writer_that_lost(ours, theirs):
+ """MH-HOSTED-UI-012: a call instance is settled once, whoever writes (a recovery pass may settle it first), and the
+ store returns the row that committed. Whether a final that says nothing after it replies with an image follows
+ that row, never the result this execution produced and lost."""
+
+ store = InMemoryTranscriptStore()
+
+ async def execute(arguments, ctx):
+ # Another writer settles the call while it runs: its result is the one that commits.
+ await store.append_tool_result(ctx.session_id, _image_result(ctx.tool_call_id, completed=theirs), details={})
+ mine = _image_result(ctx.tool_call_id, completed=ours)
+ return ToolResult(mine.content, mine.is_error, hosted=mine.hosted)
+
+ tool = FakeTool("image_generate", execute=execute)
+ provider = ScriptedProvider(
+ [[Done(assistant("", calls=[ToolCallBlock("call_img", "image_generate", {})]))], [Done(assistant(""))]]
+ )
+ events = await collect(make_agent(provider, store=store, tools=[tool]))
+
+ ended = events[-1]
+ assert isinstance(ended, RunEnded) and ended.reason == ("completed" if theirs else "error")
diff --git a/tests/agent_core/fakes.py b/tests/agent_core/fakes.py
index 211896178..34dc3b45b 100644
--- a/tests/agent_core/fakes.py
+++ b/tests/agent_core/fakes.py
@@ -165,7 +165,9 @@ class InMemoryTranscriptStore:
return entry
return (await self._append(session_id, [("input", message, {}, message_id)]))[0]
- async def append_response(self, session_id, message: AssistantMessage, *, final: bool, request=None) -> ContextEntry:
+ async def append_response(
+ self, session_id, message: AssistantMessage, *, final: bool, request=None, replied=None, images=()
+ ) -> ContextEntry:
payload = {"request": dict(request)} if request is not None else {}
row = (await self._append(session_id, [("response", message, payload, None)]))[0]
self.final[row.row_id] = final
diff --git a/tests/e2e/test_model_hub_images.py b/tests/e2e/test_model_hub_images.py
new file mode 100644
index 000000000..c3bf6e6f6
--- /dev/null
+++ b/tests/e2e/test_model_hub_images.py
@@ -0,0 +1,153 @@
+"""MH-HOSTED-GATEWAY-007, once per release (``vibey-hosted-tools.md`` §7.4): each image path through the real engine.
+
+A Vibey turn's ``image_generate`` call goes through the production gateway and
+the pinned engine to a loopback upstream that answers as the vendor's images
+endpoint does. Each path the bundled overlay offers must reach that upstream
+with the request the gateway built, and come back as the canonical answer; an
+image model the engine itself refuses must never be learned as the upstream's
+refusal.
+
+A model whose path is not here ships without an overlay entry. Run it with
+``-m e2e_model_hub`` and ``VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH`` set to an
+offline manifest of the engine under test.
+"""
+
+from __future__ import annotations
+
+from contextlib import AsyncExitStack, asynccontextmanager
+
+import aiohttp
+import pytest
+from aiohttp import web
+
+from core.handlers.model_hub import hosted_tools as hosted_tools_module
+from core.handlers.model_hub.capability_evidence import EvidenceFeature
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from tests.e2e.test_model_hub_runtime import _isolated_engine_adapter
+from tests.scenario_harness.model_hub import MemoryModelHubStore, service_for
+from tests.test_model_hub_google import _server
+from tests.test_model_hub_hosted_evidence import latest_ok
+from tests.test_model_hub_l3 import _source
+from tests.test_model_hub_vibey_consumer import _vibey_service
+from vibe import backend_model_catalog
+
+pytestmark = pytest.mark.e2e_model_hub
+
+# A 1x1 PNG, as an images endpoint returns it in b64_json.
+PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+
+
+@asynccontextmanager
+async def _image_turn(tmp_path, monkeypatch, *, vendor, protocol, chat_model, base_path, answer):
+ """A Vibey turn on one API-key Source, through the production gateway and the pinned engine."""
+
+ requests: list[dict] = []
+
+ async def respond(request):
+ requests.append({"path": request.path, "body": await request.json()})
+ status, payload = answer
+ return web.json_response(payload, status=status)
+
+ with _isolated_engine_adapter(tmp_path / "engine", monkeypatch) as adapter:
+ async with AsyncExitStack() as stack:
+ root = await stack.enter_async_context(_server(respond))
+ source = _source("src_imagee2e01", "Image key", vendor=vendor, protocol=protocol, model_id=chat_model)
+ source.base_url = root + base_path
+ source.credential_ref = adapter.state_store.store_api_key(
+ "sk-synthetic-image-e2e", vendor=vendor, protocol=protocol, base_url=source.base_url,
+ )
+ (tmp_path / "service").mkdir()
+ config = _vibey_service(tmp_path / "service", [source]).store.config
+ service = service_for(tmp_path / "service", MemoryModelHubStore(config), adapter)
+ await service.runtime_start()
+ gateway = ModelHubTurnGateway(service)
+ try:
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:image", turn_id="turn-image-e2e")
+
+ async def call(arguments):
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/hosted-tools/image_generate',
+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]},
+ json={"arguments": arguments},
+ ) as response:
+ return response.status, await response.json(content_type=None)
+
+ yield service, source, hop, call, requests
+ finally:
+ await gateway.close()
+
+
+SERVED = (200, {"created": 1, "data": [{"b64_json": PNG}], "size": "1536x1024", "quality": "medium",
+ "usage": {"input_tokens": 20, "output_tokens": 1056, "total_tokens": 1076}})
+
+
[email protected](("vendor", "protocol", "chat_model", "base_path", "arguments", "upstream"), [
+ # An OpenAI API key, which the engine serves through its Codex executor's direct Image API path.
+ ("openai", "openai_responses", "gpt-6-astra", "/v1",
+ {"model": "gpt-image-2", "prompt": "a lighthouse at dusk", "size": "1536x1024"},
+ ("/v1/images/generations", {"model": "gpt-image-2", "prompt": "a lighthouse at dusk", "size": "1536x1024",
+ "output_format": "jpeg", "output_compression": 90})),
+ # An edit: the reference image goes as a data URL, and the engine routes the body to the edits endpoint.
+ ("openai", "openai_responses", "gpt-6-astra", "/v1",
+ {"model": "gpt-image-2", "prompt": "make it blue", "images": [PNG], "n": 1},
+ ("/v1/images/edits", {"model": "gpt-image-2", "prompt": "make it blue", "n": 1,
+ "images": [{"image_url": f"data:image/png;base64,{PNG}"}],
+ "output_format": "jpeg", "output_compression": 90})),
+ # A Gemini API key: Google's OpenAI-compatible images endpoint, which the engine serves for a flagged model.
+ ("gemini", "openai_chat", "gemini-3-flash", "/v1beta/openai",
+ {"model": "gemini-2.5-flash-image", "prompt": "a lighthouse at dusk", "size": "16:9", "n": 1},
+ ("/v1beta/openai/images/generations", {"model": "gemini-2.5-flash-image", "prompt": "a lighthouse at dusk",
+ "aspect_ratio": "16:9", "n": 1, "response_format": "b64_json"})),
+], ids=["openai-generate", "openai-edit", "gemini-generate"])
+async def test_each_offered_image_path_reaches_the_vendors_images_endpoint(
+ tmp_path, monkeypatch, vendor, protocol, chat_model, base_path, arguments, upstream,
+):
+ """MH-HOSTED-GATEWAY-007: the offered model, the request the gateway built, and the canonical answer."""
+
+ async with _image_turn(
+ tmp_path, monkeypatch, vendor=vendor, protocol=protocol, chat_model=chat_model, base_path=base_path,
+ answer=SERVED,
+ ) as (service, source, hop, call, requests):
+ assert arguments["model"] in {model["model_id"] for model in hop["hosted_tools"]["image_generate"]["models"]}
+ status, answer = await call(arguments)
+ assert status == 200, answer
+ assert requests == [{"path": upstream[0], "body": upstream[1]}]
+ assert answer["record"] == {"status": "completed", "sources": []}
+ assert answer["images"] == [{"data": PNG}]
+ assert answer["execution"] == {
+ "mode": "direct",
+ "executor_origin": {"provider": vendor, "api": protocol, "model": arguments["model"]},
+ "executor_source_id": source.id,
+ "executor_billing": "metered",
+ **({"cost": answer["execution"]["cost"]} if "cost" in answer["execution"] else {}),
+ }
+ assert latest_ok(service, "image_generate") == (source.id, arguments["model"], "direct")
+
+
[email protected]("refusal", ["engine", "upstream"])
+async def test_only_an_upstream_refusal_teaches_that_a_source_lacks_an_image_model(tmp_path, monkeypatch, refusal):
+ """MH-HOSTED-GATEWAY-007: the engine's own refusal is never learned; the upstream's 404 is, for the endpoint."""
+
+ if refusal == "engine":
+ # xAI's image model as the overlay might list it: the pinned engine refuses it on its own.
+ grok = backend_model_catalog.ImageModelSpec(
+ "grok-imagine-image", "Grok Imagine", ("size",), ("ratio",), kinds=("api_key",),
+ )
+ monkeypatch.setattr(hosted_tools_module, "provider_image_models", lambda vendor: (grok,) if vendor == "xai" else ())
+ vendor, chat_model, model = "xai", "grok-4.6", "grok-imagine-image"
+ else:
+ vendor, chat_model, model = "openai", "gpt-6-astra", "gpt-image-2"
+ not_served = (404, {"error": {"message": "Not Found", "type": "invalid_request_error"}})
+ async with _image_turn(
+ tmp_path, monkeypatch, vendor=vendor, protocol="openai_responses", chat_model=chat_model, base_path="/v1",
+ answer=not_served,
+ ) as (service, source, _hop, call, requests):
+ status, answer = await call({"model": model, "prompt": "a lighthouse"})
+ refused = service.hosted_evidence().unsupported(source, model, EvidenceFeature.hosted("image_generate", "call"))
+ assert status == 200 and answer["record"]["status"] == "failed", answer
+ assert (len(requests), refused) == ((0, False) if refusal == "engine" else (1, True))
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index cdf7ae555..90bab9037 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -46,6 +46,7 @@ capabilities:
- tests/e2e/test_model_hub_usage_events.py
- tests/e2e/test_model_hub_service_acceptance.py
- tests/e2e/test_model_hub_codex_image.py
+ - tests/e2e/test_model_hub_images.py
harness:
- tests/scenario_harness/model_hub.py
unit_or_contract_tests:
@@ -101,6 +102,7 @@ capabilities:
- tests/test_model_hub_l3.py
- tests/test_model_hub_hosted_executor.py
- tests/test_model_hub_hosted_evidence.py
+ - tests/test_model_hub_hosted_images.py
- tests/test_model_hub_usage.py
- tests/test_ui_server_fastapi.py
- tests/test_model_hub_quota.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 894ffce6a..3d962bdd8 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -45,6 +45,7 @@ capability:
- tests/test_model_hub_l3.py
- tests/test_model_hub_hosted_executor.py
- tests/test_model_hub_hosted_evidence.py
+ - tests/test_model_hub_hosted_images.py
- tests/test_model_hub_usage.py
- tests/test_ui_server_fastapi.py
- tests/test_model_hub_quota.py
@@ -104,6 +105,7 @@ capability:
- tests/e2e/test_model_hub_usage_events.py
- tests/e2e/test_model_hub_service_acceptance.py
- tests/e2e/test_model_hub_codex_image.py
+ - tests/e2e/test_model_hub_images.py
status_legend:
covered:
description: closed-loop coverage exists at the declared layer
@@ -264,10 +266,14 @@ scenarios:
related_tests:
- tests/test_hosted_activity.py::test_the_im_line_names_a_subscription_and_a_shared_response_cost
- id: MH-HOSTED-UI-012
- name: A turn whose image_generate call completed reaches the user with the image as an attachment, even when the model says nothing after it (hosted tools v2 C2)
- status: gap
+ name: A turn whose image_generate call completed reaches the user with the image as an attachment, and a final that says nothing after it is still a reply, never the empty-reply error; the turn keeps its first hop's image models
+ status: covered
kind: contract
layer: contract
+ test: tests/test_vibey_agent.py::test_a_generated_image_reaches_the_user_with_the_turns_reply_even_when_the_model_says_nothing
+ related_tests:
+ - tests/test_agent_transcript.py::test_a_final_commits_as_the_loops_reply_decision_says
+ - tests/agent_core/agent/test_loop.py::test_a_reply_counts_the_images_of_the_tool_result_that_committed_not_the_writer_that_lost
- id: MH-HOSTED-UI-011
name: Vibey delivers a native hosted call as its IM line and Web card, and its answer with provider citations as links
status: covered
@@ -402,12 +408,14 @@ scenarios:
- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has
- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_continued_response_is_verified_only_when_every_response_in_it_was_from_one_origin
- id: MH-HOSTED-VIBEY-007
- name: A generated image the endpoint returns is saved through the media sink and its record names that file; no base64 enters history, and a call that saved no file is a failed record with its code
+ name: An image_generate call goes to the gateway's image endpoint with its arguments alone, after the turn's frozen models accept every argument and its reference images are read as read reads them; the images it returns are saved through the media sink and its record names those files; no base64 enters history, and a call that saved no file is a failed record with its code
status: covered
kind: contract
layer: contract
test: tests/test_vibey_agent.py::test_an_image_the_endpoint_returns_is_saved_through_the_media_sink_and_its_record_names_the_file
related_tests:
+ - tests/test_vibey_agent.py::test_an_image_call_is_checked_against_the_turns_models_and_its_references_read_before_it_runs
+ - tests/test_vibey_agent.py::test_vibeys_image_tool_runs_on_the_gateways_image_endpoint_from_the_hop_it_resolves
- tests/test_vibey_agent.py::test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type
- tests/test_agent_transcript.py::test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans
- id: MH-HOSTED-UI-001
@@ -2498,8 +2506,25 @@ scenarios:
test: tests/test_model_hub_hosted_evidence.py::test_a_served_response_proves_only_its_own_completed_search_item
related_tests:
- tests/test_model_hub_hosted_evidence.py::test_a_native_success_is_recorded_at_settlement_for_a_tool_the_request_declared
+ - id: MH-HOSTED-GATEWAY-007
+ name: image_generate runs directly on the images endpoint of a model its turn's frozen enum names, admitted on the final snapshot with no fallback; an argument the model does not take or a model no longer admitted fails before anything runs; only usable base64 images complete; only an upstream refusal of the model or its endpoint is learned; each offered path is verified through the pinned engine
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/test_model_hub_hosted_images.py::test_an_image_call_runs_directly_on_the_named_models_source
+ related_tests:
+ - tests/test_model_hub_hosted_images.py::test_a_ratio_and_reference_images_map_to_the_endpoints_fields
+ - tests/test_model_hub_hosted_images.py::test_an_image_call_its_turn_cannot_make_is_refused_unrun
+ - tests/test_model_hub_hosted_images.py::test_an_argument_the_model_does_not_take_fails_before_anything_runs
+ - tests/test_model_hub_hosted_images.py::test_a_model_gone_mid_turn_is_unavailable_and_the_record_names_the_others
+ - tests/test_model_hub_hosted_images.py::test_only_usable_images_complete_the_call
+ - tests/test_model_hub_hosted_images.py::test_only_an_upstream_refusal_of_the_model_or_endpoint_is_learned
+ - tests/test_model_hub_hosted_images.py::test_a_malformed_image_call_is_refused_before_anything_runs
+ - tests/test_model_hub_hosted_images.py::test_an_image_call_body_is_bounded_by_its_reference_images
+ - tests/test_model_hub_hosted_images.py::test_an_image_call_costs_its_delivered_images_at_their_list_price
+ - tests/e2e/test_model_hub_images.py::test_each_offered_image_path_reaches_the_vendors_images_endpoint
+ - tests/e2e/test_model_hub_images.py::test_only_an_upstream_refusal_teaches_that_a_source_lacks_an_image_model
next_priority:
- - MH-HOSTED-UI-012
- MH-PROTOCOL-004
- MH-RUNTIME-001
- MH-OAUTH-B-001
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index df937a415..919684c5e 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -443,7 +443,7 @@ async def test_the_display_copy_commits_with_its_row_and_never_reaches_the_conte
_session(conn, "ses_main", home)
consumed = _row(conn, "ses_main", home, "go")
- def render(message, *, final):
+ def render(message, *, final, replied, images):
body = "\n".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
return f"{body} (shown)" if final else body.upper()
@@ -469,6 +469,47 @@ async def test_the_display_copy_commits_with_its_row_and_never_reaches_the_conte
]
+ ("replied", "display", "row_type"),
+ [
+ # Its display carries the turn's images: a terminal result as committed.
+ (True, "Generated image:\n\n![a.png](file:///a.png)", "result"),
+ # A reply the model kept silent shows nothing.
+ (True, "", "assistant"),
+ (False, "", "error"),
+ (None, "", "error"),
+ ],
+ ids=["replies-with-its-turns-images", "replies-silently", "does-not-reply", "no-decision"],
+)
+async def test_a_final_commits_as_the_loops_reply_decision_says(engine, replied, display, row_type) -> None:
+ """MH-HOSTED-UI-012: whether a final replies is the loop's decision (``has_reply``), and the row commits with the type
+ it gives, so a final that replies with its turn's images is no failed final even if the process stops before its
+ delivery rewrites the row. The renderer gets the same decision and the images the final delivers. Without a
+ decision, the response alone decides."""
+ with engine.begin() as conn:
+ home = _scope(conn, "C-home")
+ _session(conn, "ses_main", home)
+ consumed = _row(conn, "ses_main", home, "draw a lighthouse")
+ from core.agent_core.messages import HostedImage
+
+ image = HostedImage(path="/a.png", mime="image/png")
+ given: list[tuple] = []
+
+ def render(message, *, final, replied, images):
+ given.append((replied, images))
+ return display
+
+ store = SQLiteTranscriptStore(engine, render=render)
+ await store.consume_input("ses_main", consumed, _user("draw a lighthouse"))
+ final = await store.append_response(
+ "ses_main", AssistantMessage((), ORIGIN, "stop"), final=True, replied=replied, images=(image,)
+ )
+
+ with engine.connect() as conn:
+ committed = conn.execute(select(messages.c.type).where(messages.c.id == final.row_id)).scalar_one()
+ assert committed == row_type and given == [(bool(replied), (image,))]
+
+
async def test_a_call_instance_is_settled_once_whoever_writes(engine) -> None:
with engine.begin() as conn:
home = _scope(conn, "C-home")
diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.py
index a0df24fdc..c72fedf07 100644
--- a/tests/test_model_hub_hosted_executor.py
+++ b/tests/test_model_hub_hosted_executor.py
@@ -346,10 +346,10 @@ FAILED_WITH_PARTIAL = {**WEB_CALL, "status": "failed"}
@pytest.mark.asyncio
@pytest.mark.parametrize(("case", "bound", "handles", "error", "sources", "executed"), [
# No Source can run it: the record says which providers' Sources could.
- ("no_candidate", None, [], "No Source can run web_search right now", [], False),
- ("source_removed", (XAI, "grok-4.6"), [], "No Source can run web_search right now", [], False),
+ ("no_candidate", None, [], "No Source can run web search right now. Add an API key from one of Anthropic, OpenAI, xAI.", [], False),
+ ("source_removed", (XAI, "grok-4.6"), [], "No Source can run web search right now. Add an API key from one of Anthropic, OpenAI, xAI.", [], False),
# A new base URL or credential is a new identity, which the turn's chain was not built for.
- ("source_identity_changed", (XAI, "grok-4.6"), [], "No Source can run web_search right now", [], False),
+ ("source_identity_changed", (XAI, "grok-4.6"), [], "No Source can run web search right now. Add an API key from one of Anthropic, OpenAI, xAI.", [], False),
# The only candidate failed: its failure, and the Sources tried.
("provider_refused", (XAI, "grok-4.6"),
[InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=XAI))],
@@ -392,6 +392,14 @@ async def test_a_proxied_call_that_cannot_complete_is_a_failed_record(
assert status == 200
assert answer["record"]["status"] == "failed"
assert error in answer["record"]["error"]
+ # Each reason the gateway words carries the code its reader's surface shows it by (#2589).
+ # Which providers to add is the call's own fact: that reason has no code and is shown as written.
+ assert answer["record"].get("error_code") == {
+ "no_candidate": None, "source_removed": None,
+ "source_identity_changed": None, "provider_refused": "provider_refused",
+ "tool_never_ran": "search_not_run", "call_failed_with_partial_results": "search_failed",
+ "stream_failed_after_items": "provider_refused",
+ }[case]
assert answer["record"]["sources"] == sources
assert ("execution" in answer) is executed
assert len(service.adapter.invocations) == int(executed)
@@ -506,7 +514,7 @@ async def test_failure_text_is_in_the_users_language(tmp_path):
service, "x_search", {"arguments": {"query": "q"}}, language="zh",
)
assert status == 200
- assert answer["record"]["error"] == "当前没有可运行 x_search 的来源。添加以下任一供应商的来源即可使用:xAI。"
+ assert answer["record"]["error"] == "当前没有能运行 X 搜索的供应商。请添加 xAI 的 API Key。"
@pytest.mark.asyncio
@@ -709,6 +717,7 @@ async def test_only_a_response_that_completed_completes_the_call(tmp_path, case,
assert answer_status == 200
assert answer["record"]["status"] == status
assert error in answer["record"]["error"]
+ assert answer["record"]["error_code"] == ("provider_unreadable" if "could not be read" in error else "response_ended_early")
assert answer["record"]["sources"] == sources
assert _hosted_result("web_search", answer).record.status == status
@@ -741,7 +750,7 @@ async def test_a_turn_keeps_its_tools_and_executor_order_until_the_next_turn(tmp
_bind(service, "web_search", (OPENAI, "gpt-6-astra"))
_bind(service, "x_search", (XAI, "grok-4.6"))
again = await router.resolve_hop("menu-alias", process_scope="vibey:freeze", turn_id="turn-freeze")
- assert again["hosted_tools"].keys() == first["hosted_tools"].keys() == {"web_search"}
+ assert again["hosted_tools"].keys() == first["hosted_tools"].keys() == {"web_search", "image_generate"}
status, answer = await search(again, "web_search")
assert status == 200 and answer["execution"]["executor_source_id"] == XAI
assert (await search(again, "x_search"))[0] == 409
diff --git a/tests/test_model_hub_hosted_images.py b/tests/test_model_hub_hosted_images.py
new file mode 100644
index 000000000..4b9d65676
--- /dev/null
+++ b/tests/test_model_hub_hosted_images.py
@@ -0,0 +1,335 @@
+"""MH-HOSTED-GATEWAY-007: ``image_generate`` direct execution at the gateway (``vibey-hosted-tools.md`` §7.2, §7.4).
+
+Each case posts an ``image_generate`` call to the real gateway endpoint for a
+Vibey turn, with a recording engine adapter answering as the images endpoint
+does; ``tests/e2e/test_model_hub_images.py`` runs the same paths through the
+real engine. The turn's enum comes from the bundled overlay.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import struct
+from dataclasses import replace
+
+import aiohttp
+import pytest
+
+from config.v2_config import ModelHubHostedToolConfig
+from core.handlers.model_hub import hosted_images as images_module
+from core.handlers.model_hub import hosted_tools as hosted_tools_module
+from core.handlers.model_hub.adapter import RawOutcomeKind
+from core.handlers.model_hub.capability_evidence import EvidenceFeature
+from core.handlers.model_hub.stream_wire import ProtocolUsageReport
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from tests.agent_core.tools.test_read import _png
+from tests.test_model_hub_hosted_evidence import latest_ok
+from tests.test_model_hub_l3 import InvokeHandle, LiveInvokeHandle, _outcome, _source, _usage_of
+from tests.test_model_hub_vibey_consumer import _vibey_service
+from vibe.backend_model_catalog import HostedToolPrice, ImageModelPrice, ImageModelSpec
+
+OPENAI = "src_oaiimage01"
+GEMINI = "src_gemimage01"
+PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+IMAGE = "image_generate"
+FEATURE = EvidenceFeature.hosted(IMAGE, "call")
+
+
+def _sources():
+ return [
+ _source(OPENAI, "OpenAI key", vendor="openai", protocol="openai_responses", model_id="gpt-6-astra"),
+ _source(GEMINI, "Gemini key", vendor="gemini", protocol="openai_chat", model_id="gemini-3-flash"),
+ ]
+
+
+def _served(*images, size="1024x1024", quality="medium", usage=None, source_id=OPENAI):
+ body = {"created": 1, "data": [{"b64_json": data} for data in images], "size": size, "quality": quality}
+ tokens = usage or ProtocolUsageReport.of(input_tokens=20, cached_input_tokens=0, output_tokens=1056)
+ return LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, source_id=source_id, usage=tokens), (json.dumps(body).encode(),),
+ )
+
+
+async def _call(service, arguments, *, after_launch=None, raw=None, turns=1):
+ """Post one call in the first of ``turns`` turns; return its answer and each turn's offered models."""
+
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ offered = []
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:image", turn_id="turn-image")
+ offered.append([model["model_id"] for model in hop["hosted_tools"].get(IMAGE, {}).get("models", [])])
+ if after_launch is not None:
+ after_launch()
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/hosted-tools/{IMAGE}',
+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]},
+ data=raw if raw is not None else json.dumps({"arguments": arguments}),
+ ) as response:
+ answer = response.status, await response.json(content_type=None)
+ for number in range(1, turns):
+ nxt = await router.resolve_hop("menu-alias", process_scope="vibey:image", turn_id=f"turn-image-{number}")
+ offered.append([model["model_id"] for model in nxt["hosted_tools"].get(IMAGE, {}).get("models", [])])
+ return answer, offered
+ finally:
+ await gateway.close()
+
+
+async def test_an_image_call_runs_directly_on_the_named_models_source(tmp_path):
+ """MH-HOSTED-GATEWAY-007: the model's fixed fields and the call's own, one buffered call, the agreed answer."""
+
+ service = _vibey_service(tmp_path, _sources(), handles=[_served(PNG, PNG, size="1536x1024")])
+ (status, answer), (offered,) = await _call(
+ service, {"model": "gpt-image-2", "prompt": "a lighthouse", "size": "1536x1024", "n": 2},
+ )
+ assert status == 200, answer
+ # The default first, then the rest by id.
+ assert offered == ["gpt-image-2", "gemini-2.5-flash-image", "gemini-3-pro-image-preview"]
+ assert service.adapter.invocations == [(OPENAI, "gpt-image-2", "vibey")]
+ sent = service.adapter.requests[0]
+ assert sent.protocol == "openai_images"
+ assert dict(sent) == {
+ "prompt": "a lighthouse", "size": "1536x1024", "n": 2, "output_format": "jpeg", "output_compression": 90,
+ }
+ assert answer == {
+ "record": {"status": "completed", "sources": []},
+ "execution": {
+ "mode": "direct",
+ "executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image-2"},
+ "executor_source_id": OPENAI,
+ "executor_billing": "metered",
+ },
+ "images": [{"data": PNG}, {"data": PNG}],
+ "generation": {"size": "1536x1024", "quality": "medium"},
+ }
+ assert _usage_of(service, OPENAI)
+ assert latest_ok(service, IMAGE) == (OPENAI, "gpt-image-2", "direct")
+
+
+async def test_a_ratio_and_reference_images_map_to_the_endpoints_fields(tmp_path):
+ """MH-HOSTED-GATEWAY-007: a ratio goes as aspect_ratio; reference images go as data URLs and make an edit."""
+
+ service = _vibey_service(tmp_path, _sources(), handles=[_served(PNG, source_id=GEMINI), _served(PNG)])
+ (status, _answer), _ = await _call(service, {"model": "gemini-2.5-flash-image", "prompt": "a cat", "size": "16:9"})
+ assert status == 200
+ assert dict(service.adapter.requests[0]) == {"prompt": "a cat", "aspect_ratio": "16:9", "response_format": "b64_json"}
+ (status, _answer), _ = await _call(service, {"model": "gpt-image-2", "prompt": "make it blue", "images": [PNG]})
+ assert status == 200
+ assert service.adapter.requests[1]["images"] == [{"image_url": f"data:image/png;base64,{PNG}"}]
+
+
[email protected]("case", ["model_outside_the_enum", "tool_turned_off", "turned_on_mid_turn"])
+async def test_an_image_call_its_turn_cannot_make_is_refused_unrun(tmp_path, case):
+ """MH-HOSTED-GATEWAY-007: the frozen enum authorizes every call; nothing outside it runs or is billed."""
+
+ service = _vibey_service(tmp_path, _sources())
+ if case != "model_outside_the_enum":
+ service.store.config.hosted_tools[IMAGE] = ModelHubHostedToolConfig(enabled=False)
+
+ def turned_on():
+ if case == "turned_on_mid_turn":
+ service.store.config.hosted_tools[IMAGE] = ModelHubHostedToolConfig(enabled=True)
+
+ model = "dall-e-3" if case == "model_outside_the_enum" else "gpt-image-2"
+ (status, answer), _ = await _call(service, {"model": model, "prompt": "a cat"}, after_launch=turned_on)
+ assert (status, answer["error"]["code"]) == (409, "tool_not_enabled")
+ assert service.adapter.invocations == []
+
+
[email protected](("arguments", "error"), [
+ # Gemini takes no reference images: the record names the models that do.
+ ({"model": "gemini-2.5-flash-image", "prompt": "edit", "images": [PNG]},
+ "gemini-2.5-flash-image does not take images. Models that take it: gpt-image-2."),
+ # GPT Image takes sizes in pixels only.
+ ({"model": "gpt-image-2", "prompt": "wide", "size": "16:9"},
+ "gpt-image-2 does not take size. Models that take it: gemini-2.5-flash-image, gemini-3-pro-image-preview."),
+])
+async def test_an_argument_the_model_does_not_take_fails_before_anything_runs(tmp_path, arguments, error):
+ """MH-HOSTED-GATEWAY-007: never silently dropped, so an edit never becomes an unrelated generation."""
+
+ service = _vibey_service(tmp_path, _sources())
+ (status, answer), _ = await _call(service, arguments)
+ assert status == 200
+ assert answer == {"record": {"status": "failed", "error": error, "sources": [], "error_code": "image_param_unsupported"}}
+ assert service.adapter.invocations == []
+
+
+async def test_a_model_gone_mid_turn_is_unavailable_and_the_record_names_the_others(tmp_path):
+ """MH-HOSTED-GATEWAY-007: admitted on the final snapshot; no fallback, but the alternatives are named."""
+
+ service = _vibey_service(tmp_path, _sources())
+
+ def removed():
+ service.store.config.sources = [item for item in service.store.config.sources if item.id != GEMINI]
+
+ (status, answer), _ = await _call(
+ service, {"model": "gemini-3-pro-image-preview", "prompt": "a cat"}, after_launch=removed,
+ )
+ assert status == 200
+ assert answer["record"]["error_code"] == "image_model_unavailable"
+ assert answer["record"]["error"].endswith("Available: gpt-image-2, gemini-2.5-flash-image.")
+ assert "execution" not in answer and service.adapter.invocations == []
+
+
+NOT_AN_IMAGE = base64.b64encode(b"plain text, not an image").decode()
+# Images read and the media sink do not take: a BMP, and an animated PNG whose acTL sits past any sniffed prefix.
+BMP = base64.b64encode(struct.pack("<2sIHHIIiiHH", b"BM", 58, 0, 0, 54, 40, 1, 1, 1, 24) + bytes(28)).decode()
+LATE_APNG = base64.b64encode(_png(animated=True, padding=10_000)).decode()
+
+
[email protected](("answer_body", "error"), [
+ ({"created": 1, "data": [{"url": "https://cdn.example/image.png"}]}, "returned no image data"),
+ ({"created": 1, "data": []}, "returned no image data"),
+ ({"created": 1, "data": [{"b64_json": "not base64!"}]}, "could not be used"),
+ ({"created": 1, "data": [{"b64_json": NOT_AN_IMAGE}]}, "could not be used"),
+ ({"created": 1, "data": [{"b64_json": BMP}]}, "could not be used"),
+ ({"created": 1, "data": [{"b64_json": LATE_APNG}]}, "could not be used"),
+ ({"created": 1, "data": [{"b64_json": PNG}, {"b64_json": PNG}], "oversized": True, "n": 2}, "larger than allowed"),
+ # An answer with more images than the call asked for, or than one when it named no n, is not kept at all.
+ ({"created": 1, "data": [{"b64_json": PNG}] * 2}, "larger than allowed"),
+ ({"created": 1, "data": [{"b64_json": PNG}] * 5, "n": 4}, "larger than allowed"),
+])
+async def test_only_usable_images_complete_the_call(tmp_path, monkeypatch, answer_body, error):
+ """MH-HOSTED-GATEWAY-007: completion is an allow-list; a URL is never fetched; the call is still metered."""
+
+ if answer_body.pop("oversized", False):
+ monkeypatch.setattr(images_module, "IMAGES_TOTAL_MAX_BYTES", len(base64.b64decode(PNG)) + 1)
+ asked = {"n": answer_body.pop("n")} if "n" in answer_body else {}
+ handle = LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI, usage=ProtocolUsageReport.of(
+ input_tokens=20, cached_input_tokens=0, output_tokens=10,
+ )), (json.dumps(answer_body).encode(),))
+ service = _vibey_service(tmp_path, _sources(), handles=[handle])
+ (status, answer), _ = await _call(service, {"model": "gpt-image-2", "prompt": "a cat", **asked})
+ assert status == 200
+ assert answer["record"]["status"] == "failed" and error in answer["record"]["error"]
+ # The gateway's own reason carries the code each surface shows it by (#2589); the other models follow in its text.
+ assert answer["record"]["error_code"] == {
+ "returned no image data": "provider_no_image", "could not be used": "provider_image_unusable",
+ "larger than allowed": "provider_too_large",
+ }[error]
+ assert "images" not in answer and answer["execution"]["executor_source_id"] == OPENAI
+ assert _usage_of(service, OPENAI)
+ assert latest_ok(service, IMAGE) is None
+
+
[email protected](("outcome", "refused"), [
+ # The endpoint itself is not served: every image model the Source registers there.
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="not_found_error", source_id=GEMINI),
+ {"gemini-2.5-flash-image", "gemini-3-pro-image-preview"}),
+ # A refusal naming the model: that model only.
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="model_not_found", source_id=GEMINI),
+ {"gemini-3-pro-image-preview"}),
+ # Anything else teaches nothing: a request error, the provider's failure, the engine's own refusal.
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_request_error", source_id=GEMINI), set()),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=503, code="server_error", source_id=GEMINI), set()),
+ (_outcome(RawOutcomeKind.NETWORK_ERROR, code="engine_down", source_id=GEMINI), set()),
+], ids=["endpoint-not-served", "model-refused", "request-error", "server-error", "engine-refused"])
+async def test_only_an_upstream_refusal_of_the_model_or_endpoint_is_learned(tmp_path, outcome, refused):
+ """MH-HOSTED-GATEWAY-007: the image narrow rule (§3.2); the next turn's enum drops what was refused."""
+
+ service = _vibey_service(tmp_path, _sources(), handles=[InvokeHandle(outcome)])
+ (status, answer), offered = await _call(service, {"model": "gemini-3-pro-image-preview", "prompt": "a cat"}, turns=2)
+ assert status == 200 and answer["record"]["status"] == "failed"
+ gemini = next(item for item in service.store.config.sources if item.id == GEMINI)
+ learned = {
+ model for model in ("gemini-2.5-flash-image", "gemini-3-pro-image-preview")
+ if service.hosted_evidence().unsupported(gemini, model, FEATURE)
+ }
+ assert learned == refused
+ assert offered[1] == [model for model in offered[0] if model not in refused]
+
+
[email protected]("arguments", [
+ {"model": "gpt-image-2", "prompt": "a cat", "style": "vivid"},
+ {"model": "gpt-image-2", "prompt": " "},
+ {"model": "gpt-image-2", "prompt": "a cat", "n": 5},
+ {"model": "gpt-image-2", "prompt": "a cat", "size": "large"},
+ {"model": "gpt-image-2", "prompt": "a cat", "images": [PNG] * 5},
+ {"model": "gpt-image-2", "prompt": "a cat", "images": ["not base64!"]},
+ {"model": "gpt-image-2", "prompt": "a cat", "images": [NOT_AN_IMAGE]},
+ {"model": "gpt-image-2", "prompt": "a cat", "images": [BMP]},
+])
+async def test_a_malformed_image_call_is_refused_before_anything_runs(tmp_path, arguments):
+ """MH-HOSTED-GATEWAY-007: Vibey checks the same before calling; the gateway is the execution boundary."""
+
+ service = _vibey_service(tmp_path, _sources())
+ (status, answer), _ = await _call(service, arguments)
+ assert (status, answer["error"]["code"]) == (400, "invalid_request_error")
+ assert service.adapter.invocations == []
+
+
+async def test_an_image_call_body_is_bounded_by_its_reference_images(tmp_path, monkeypatch):
+ """MH-HOSTED-GATEWAY-007: four reference images at read's inline limit fit; more is refused before parsing."""
+
+ service = _vibey_service(tmp_path, _sources())
+ padded = json.dumps({"arguments": {"model": "gpt-image-2", "prompt": "x" * images_module.IMAGE_CALL_MAX_BYTES}})
+ (status, answer), _ = await _call(service, None, raw=padded.encode())
+ assert (status, answer["error"]["code"]) == (400, "invalid_request_error")
+ assert images_module.IMAGE_CALL_MAX_BYTES > 4 * (images_module.MAX_INLINE_IMAGE_BYTES * 4 // 3)
+
+
+PRICED = ImageModelSpec(
+ "gpt-image-2", "GPT Image 2", ("n", "size"), ("pixels",), kinds=("api_key",),
+ prices=(
+ ImageModelPrice(HostedToolPrice("image", 40, None, "https://example.test/pricing"), size="1024x1024"),
+ ImageModelPrice(HostedToolPrice("image", 70, None, "https://example.test/pricing"), size="1536x1024"),
+ ),
+)
+
+
[email protected](("size", "cost"), [
+ ("1536x1024", {"basis": "list", "usd": 0.14}),
+ # No price for the size it delivered, and no token price held: unpriced, never zero.
+ ("1024x1536", None),
+])
+async def test_an_image_call_costs_its_delivered_images_at_their_list_price(tmp_path, monkeypatch, size, cost):
+ """MH-HOSTED-GATEWAY-007: the price that applies to what was delivered, times the images delivered."""
+
+ monkeypatch.setattr(
+ hosted_tools_module, "provider_image_models", lambda vendor: (PRICED,) if vendor == "openai" else (),
+ )
+ service = _vibey_service(tmp_path, [replace(_sources()[0])], handles=[_served(PNG, PNG, size=size)])
+ (status, answer), _ = await _call(service, {"model": "gpt-image-2", "prompt": "a cat", "n": 2})
+ assert status == 200 and answer["record"]["status"] == "completed"
+ assert answer["execution"].get("cost") == cost
+
+
[email protected]("status", [200, 502], ids=["served", "refused"])
+async def test_an_image_answer_is_bounded_while_it_downloads(monkeypatch, status):
+ """MH-HOSTED-GATEWAY-007: a relay that never stops is cut at the bound, before it reaches the disk spool."""
+
+ from aiohttp import web
+
+ from tests.test_model_hub_retry_advice import _engine, _source as _engine_source
+ from vibe.model_hub_runtime import client as client_module
+
+ monkeypatch.setitem(client_module._BUFFERED_RESPONSE_MAX_BYTES, "openai_images", 256 * 1024)
+ sent = []
+
+ async def respond(request):
+ response = web.StreamResponse(status=status, headers={"Content-Type": "application/json"})
+ await response.prepare(request)
+ try:
+ for _ in range(64):
+ chunk = b"x" * (64 * 1024)
+ await response.write(chunk)
+ sent.append(len(chunk))
+ except (ConnectionResetError, RuntimeError):
+ pass
+ return response
+
+ async with _engine(respond) as (client, requests):
+ handle = await client.invoke(
+ _engine_source("openai_responses"), "model-a", {"prompt": "a cat"}, stream=False,
+ request_protocol="openai_images",
+ )
+ outcome = await handle.outcome()
+ await handle.close_stream()
+ assert requests[0][0] == "/v1/images/generations"
+ assert (outcome.kind, outcome.error_code, outcome.http_status) == (
+ RawOutcomeKind.NETWORK_ERROR, "response_too_large", status,
+ )
+ assert handle.stream is None
diff --git a/tests/test_model_hub_hosted_tools_config.py b/tests/test_model_hub_hosted_tools_config.py
index cb7befe15..3680181db 100644
--- a/tests/test_model_hub_hosted_tools_config.py
+++ b/tests/test_model_hub_hosted_tools_config.py
@@ -327,8 +327,8 @@ def test_an_image_models_card_price_is_only_an_unqualified_list_price(tmp_path,
from vibe.backend_model_catalog import HostedToolPrice, ImageModelPrice, ImageModelSpec
spec = ImageModelSpec(
- "gpt-image-2", "OpenAI image model", "images", ("images", "size"), ("pixels",),
- tuple(
+ "gpt-image-2", "OpenAI image model", ("images", "size"), ("pixels",),
+ prices=tuple(
ImageModelPrice(HostedToolPrice("image", usd, date(2026, 10, 15), "https://openai.com/api/pricing"), size, quality)
for size, quality, usd in prices
),
@@ -349,7 +349,7 @@ def test_an_estimated_image_price_of_zero_is_no_unit_price(tmp_path, monkeypatch
from core.handlers.model_hub import hosted_tools as hosted_tools_module
from vibe.backend_model_catalog import ImageModelSpec
- spec = ImageModelSpec("gemini-3-image", "Nano Banana", "images", ("images",), (), tokens_per_image=1290)
+ spec = ImageModelSpec("gemini-3-image", "Nano Banana", ("images",), (), tokens_per_image=1290)
monkeypatch.setattr(hosted_tools_module, "provider_image_models", lambda vendor: (spec,) if vendor == "xai" else ())
service, _store = _api_service(tmp_path)
monkeypatch.setattr(service, "hosted_call_cost", lambda *_args, **_kwargs: SimpleNamespace(usd=valued))
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index 74845321e..543241f4c 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -62,17 +62,18 @@ SPECS = {
EXECUTOR_MODELS = {"xai": "grok-fast", "openai": "gpt-mini", "anthropic": "claude-haiku"}
-def _image(model_id: str, description: str, *, price: float | None = None) -> ImageModelSpec:
+def _image(model_id: str, description: str, *, price: float | None = None, kinds=("api_key", "subscription")) -> ImageModelSpec:
prices = (
(ImageModelPrice(HostedToolPrice("image", price * 1000, date(2026, 10, 15), "https://docs.x.ai/pricing")),)
if price is not None
else ()
)
- return ImageModelSpec(model_id, description, "images", ("images", "size"), ("pixels",), prices)
+ return ImageModelSpec(model_id, description, ("images", "size"), ("pixels",), kinds=kinds, prices=prices)
IMAGE_MODELS = {
- "openai": (_image("gpt-image-2", "OpenAI's image model"),),
+ # Verified on API keys only: a subscription that lists the model is not offered it.
+ "openai": (_image("gpt-image-2", "OpenAI's image model", kinds=("api_key",)),),
"xai": (_image("grok-imagine-image", "Grok Imagine", price=0.02),),
}
@@ -195,6 +196,11 @@ def test_the_image_enum_is_deterministic_with_the_default_first(tmp_path):
assert [choice.model_id for choice in choices.models] == ["grok-imagine-image"]
assert (choices.saved_default_available, choices.default.model_id) == (False, "grok-imagine-image")
assert image_choices(_config(sources=[CLAUDE_SUB, GEMINI]), evidence=evidence).models == ()
+ codex_sub = _source("src_osub0001", "openai", "openai_responses", "gpt-image-2", kind="subscription")
+ assert image_choices(_config(sources=[codex_sub]), evidence=evidence).models == ()
+ # An OpenAI key on a protocol whose engine entry has no images endpoints is never offered one.
+ on_messages = _source("src_oanth001", "openai", "anthropic", "gpt-6-astra")
+ assert image_choices(_config(sources=[on_messages]), evidence=evidence).models == ()
def test_a_turn_freezes_its_tools_executors_and_image_enum_and_each_hop_states_its_own_facts(tmp_path):
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 813df5f2b..43e4d7746 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -56,7 +56,7 @@ from vibe.model_hub_runtime import supervisor as supervisor_module
from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog, official_models_dev_provider
from vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnection
-from vibe.model_hub_runtime.config import write_engine_config
+from vibe.model_hub_runtime.config import expected_model_names, write_engine_config
from vibe.model_hub_runtime.environment import engine_subprocess_environment
from vibe.model_hub_runtime.installer import (
EngineRuntimeManager,
@@ -1702,7 +1702,9 @@ def test_config_generation_is_private_and_never_logs_secrets(
"alias": "model-a",
"display-name": "model-a #0",
"thinking": {"levels": ["high", "low"]},
- }
+ },
+ # An OpenAI key's engine entry registers the vendor's image models too (vibey-hosted-tools.md §7.4).
+ {"name": "gpt-image-2", "alias": "gpt-image-2", "display-name": "gpt-image-2 #0"},
]
assert stat.S_IMODE(config_path.stat().st_mode) == 0o600
assert stat.S_IMODE(store.auth_dir.stat().st_mode) == 0o700
@@ -1790,9 +1792,50 @@ def test_engine_config_declares_text_only_input_only_on_openai_compatibility_mod
]
for key in ("codex-api-key", "claude-api-key"):
[entry] = payload[key]
- assert entry["models"] == [
- {"name": "text-model", "alias": "text-model", "display-name": "text-model #0"}
- ]
+ assert entry["models"][0] == {"name": "text-model", "alias": "text-model", "display-name": "text-model #0"}
+ assert all("input-modalities" not in model for model in entry["models"])
+
+
+def test_an_api_key_engine_entry_registers_its_vendors_image_models(tmp_path: Path) -> None:
+ """MH-HOSTED-GATEWAY-007: image_generate routes only models the engine registered; an OpenAI-compatible entry
+ serves the images endpoints only for a model it flags, and reload verification expects them all."""
+
+ store = EngineStateStore(tmp_path / "state")
+ instance_dir, runtime_secrets = store.prepare_instance("install-1")
+ refs = {
+ "openai": store.store_api_key("openai-secret", vendor="openai", protocol="openai_responses"),
+ "gemini": store.store_api_key("gemini-secret", vendor="gemini", protocol="openai_chat"),
+ "custom": store.store_api_key("custom-secret", base_url="https://api.example.test/v1"),
+ }
+ store.sync_sources([
+ _binding(refs["openai"], source_id="src_openai0001", vendor="openai", protocol="openai_responses",
+ base_url=None, model_ids=("gpt-6-astra",)),
+ _binding(refs["gemini"], source_id="src_gemini0001", vendor="gemini", protocol="openai_chat",
+ base_url=None, model_ids=("gemini-3-flash", "gemini-2.5-flash-image")),
+ _binding(refs["custom"], source_id="src_custom0001", model_ids=("model-a",)),
+ ])
+ config_path = instance_dir / "config.yaml"
+ write_engine_config(
+ config_path, host="127.0.0.1", port=18231, auth_dir=store.auth_dir, runtime_secrets=runtime_secrets,
+ sources=store.list_sources(), state_store=store,
+ )
+ payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+
+ def models(entry):
+ return {model["name"]: model.get("image") for model in entry["models"]}
+
+ [openai] = payload["codex-api-key"]
+ assert models(openai) == {"gpt-6-astra": None, "gpt-image-2": None}
+ custom, gemini = sorted(payload["openai-compatibility"], key=lambda entry: entry["base-url"])
+ # Listed as a chat model or not, an image model is flagged, and registered once.
+ assert models(gemini) == {
+ "gemini-3-flash": None, "gemini-2.5-flash-image": True, "gemini-3-pro-image-preview": True,
+ }
+ assert models(custom) == {"model-a": None}
+ sources = {source.source_id: source for source in store.list_sources()}
+ expected = expected_model_names(store.list_sources(), store, "0")
+ assert f'{sources["src_openai0001"].prefix}/gpt-image-2' in expected
+ assert f'{sources["src_gemini0001"].prefix}/gemini-3-pro-image-preview' in expected
def _rendered_text_only(tmp_path: Path, model_ids: tuple[str, ...], text_only: tuple[str, ...]) -> set[str]:
@@ -7499,8 +7542,8 @@ def test_slow_source_prelude_is_bounded_without_blocking_other_routes(
return None
class Session:
- async def post(self, *_args, json=None, **_kwargs):
- source_id = "src_slow0001" if str(json["model"]).startswith("slow/") else "src_fast0001"
+ async def post(self, *_args, data=None, **_kwargs):
+ source_id = "src_slow0001" if str(json.loads(data)["model"]).startswith("slow/") else "src_fast0001"
return Response(source_id)
async def close(self) -> None:
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index c657dbb7f..e235939a8 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -245,8 +245,10 @@ MODEL_OUTPUT_ENVELOPE_FIXTURES = (
("openai_chat", None, ("choices", "*", "delta", "function_call"), None, True),
)
BUFFERED_ERROR_TRUST_ROOT_FIXTURES = {
- protocol: (("error",),) for protocol in ("anthropic", "openai_responses", "openai_chat", "google")
+ protocol: (("error",),) for protocol in ("anthropic", "openai_responses", "openai_chat", "google", "openai_images")
}
+# Answered only buffered (image_generate's images endpoints): no stream envelope is ever read.
+BUFFERED_ONLY_PROTOCOLS = frozenset({"openai_images"})
ACCEPTED_SSE_LINE_ENDINGS = (b"\r\n", b"\n", b"\r")
STREAM_BOUNDARY_DIMENSIONS = {
"transport_event": ("eof", "client_error"),
@@ -708,7 +710,7 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:
# than forwarding a Turn to the gateway. They reuse the same metering owner,
# exactly once.
consumers = (
- invoke, _functions(service_tree)["_user_test_call"], _functions(service_tree)["_executor_attempt"],
+ invoke, _functions(service_tree)["_user_test_call"], _functions(service_tree)["_hosted_upstream_call"],
)
assert len(meter_calls) == len(consumers)
assert all(
@@ -1400,7 +1402,9 @@ def _assert_stream_taxonomy_matches(
def test_stream_authority_and_acceptance_fixtures_match_both_ways() -> None:
- assert set(PROTOCOL_STREAM_TAXONOMY) == {str(fixture["protocol"]) for fixture in STREAM_ENVELOPE_FIXTURES}
+ assert set(PROTOCOL_STREAM_TAXONOMY) - BUFFERED_ONLY_PROTOCOLS == {
+ str(fixture["protocol"]) for fixture in STREAM_ENVELOPE_FIXTURES
+ }
assert set(SSE_LINE_ENDINGS) == set(ACCEPTED_SSE_LINE_ENDINGS)
assert all(str(fixture["source"]).startswith("https://") for fixture in STREAM_ENVELOPE_FIXTURES)
for protocol, taxonomy in PROTOCOL_STREAM_TAXONOMY.items():
diff --git a/tests/test_model_hub_vibey_consumer.py b/tests/test_model_hub_vibey_consumer.py
index 8d37c48e7..a6b204c98 100644
--- a/tests/test_model_hub_vibey_consumer.py
+++ b/tests/test_model_hub_vibey_consumer.py
@@ -1099,6 +1099,15 @@ async def test_hop_resolution_states_each_enabled_hosted_tool(tmp_path):
"include": ["web_search_call.action.sources"],
"replay": "assumed",
},
+ # The bundled overlay's verified image model on an OpenAI key, its params as sorted lists.
+ "image_generate": {
+ "models": [{
+ "source_id": "src_primary01", "model_id": "gpt-image-2",
+ "description": "GPT Image 2: precise prompts, legible text, edits",
+ "params": ["images", "n", "size"], "size_forms": ["pixels"],
+ }],
+ "default": {"source_id": "src_primary01", "model_id": "gpt-image-2"},
+ },
}
_assert_mandatory_fields("hop-resolution.schema.json", hop, HOSTED_TOOL_MANDATORY_FIELDS)
image = {"source_id": "src_primary01", "model_id": "gpt-image-2", "description": "OpenAI images",
diff --git a/tests/test_provider_overlay.py b/tests/test_provider_overlay.py
index ac8861f09..99d42d92b 100644
--- a/tests/test_provider_overlay.py
+++ b/tests/test_provider_overlay.py
@@ -185,9 +185,10 @@ def _image_edit(path: tuple, value: object):
_IMAGE_MODEL = {
"id": "grok-imagine-image",
"description": "Grok Imagine: fast photoreal images",
- "endpoint": "images",
"params": ["size", "images"],
"size_forms": ["ratio"],
+ "kinds": ["api_key"],
+ "request": {"response_format": "b64_json"},
"prices": [{"price": {"unit": "image", "usd_per_1k": 20, "as_of": "2026-10-15", "url": "https://docs.x.ai/developers/pricing"}}],
}
_FAMILY = ("models", 0)
@@ -235,7 +236,13 @@ _PRICE = (*_X_SEARCH, "price")
pytest.param("xai", _edit((*_PRICE, "extra", 0, "unit"), "image"), id="extra-unit-per-image"),
pytest.param("xai", _edit(("executor_model",), " "), id="executor-model-blank"),
pytest.param("xai", _edit(("image_models",), {}), id="image-models-not-a-list"),
- pytest.param("xai", _image_edit(("endpoint",), "edits"), id="image-endpoint-unknown"),
+ pytest.param("xai", _image_edit(("kinds",), ["oauth"]), id="image-kind-unknown"),
+ pytest.param("xai", _image_edit(("kinds",), []), id="image-kinds-empty"),
+ # A fixed request field never overrides what the call itself names.
+ pytest.param("xai", _image_edit(("request",), {"n": 4}), id="image-request-sets-a-call-field"),
+ # A ratio-form size is sent as aspect_ratio: fixing it would override, or be overridden by, the call.
+ pytest.param("xai", _image_edit(("request",), {"aspect_ratio": "1:1"}), id="image-request-sets-the-ratio-field"),
+ pytest.param("xai", _image_edit(("request",), {"style": {"nested": True}}), id="image-request-not-scalar"),
pytest.param("xai", _image_edit(("description",), "x" * 81), id="image-description-too-long"),
pytest.param("xai", _image_edit(("params",), ["images", "quality"]), id="image-param-unknown"),
pytest.param("xai", _image_edit(("size_forms",), []), id="image-size-without-forms"),
@@ -271,8 +278,8 @@ def test_an_image_model_entry_is_read_in_a_stable_form(monkeypatch, tmp_path):
_use_bundled(monkeypatch, tmp_path, providers)
(model,) = catalog.provider_image_models("xai")
- assert (model.id, model.endpoint, model.params, model.size_forms) == (
- "grok-imagine-image", "images", ("images", "size"), ("ratio",),
+ assert (model.id, model.params, model.size_forms, model.kinds, model.request) == (
+ "grok-imagine-image", ("images", "size"), ("ratio",), ("api_key",), {"response_format": "b64_json"},
)
assert [(price.price.unit, price.price.usd_per_1k, price.size) for price in model.prices] == [("image", 20, None)]
assert catalog.provider_image_models("anthropic") == ()
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 3c1316b56..b4ecd6632 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -2673,58 +2673,79 @@ async def test_a_proxied_hosted_call_runs_on_the_turns_executor_chain_and_keeps_
assert sent["type"] == "tool_result" and seen in json.dumps(sent)
-_IMAGE_SPEC = ToolSpec(
- "image_generate",
- "Generate an image.",
- {"type": "object", "properties": {"model": {"type": "string"}, "prompt": {"type": "string"}}},
-)
_JPEG = b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8
_DIRECT = {
"mode": "direct",
"executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image-2"},
"executor_source_id": "src_executor01",
"executor_billing": "metered",
+ "cost": {"basis": "list", "usd": 0.04},
}
+# The turn's image models as HopResolution freezes them (§3.4): the default first, then by id.
+_IMAGE_MODELS = (
+ ("gpt-image-2", "OpenAI's image model", ("images", "n", "size"), ("pixels",)),
+ ("gemini-3.1-flash-image", "Google's fast image model", ("size",), ("ratio",)),
+)
+
+
+def _image_tool(client, *, media=None, language="en"):
+ from core.agent_core.ai.provider import ImageModel, ImageModels, ModelEndpoint
+ from core.agent_core.tools.hosted import image_generate_spec
+ from modules.agents.vibey.tools import ImageGenerateTool
+
+ models = ImageModels(tuple(ImageModel("src_executor01", *entry) for entry in _IMAGE_MODELS))
+ endpoint = ModelEndpoint("anthropic", "http://hub.invalid/vibey/v1", "claude-opus-5-5", "hub-token")
+ return ImageGenerateTool(image_generate_spec(models), models, lambda: endpoint, client, media, lambda: language)
+
+
+def _tool_context(cwd: Path):
+ from core.agent_core.cancel import CancelToken
+ from core.agent_core.tools.base import ToolContext
+
+ return ToolContext("session", "call_1", None, str(cwd), {}, CancelToken())
@pytest.mark.parametrize(
("images", "stored", "error", "code"),
[
- ([{"mime": "image/jpeg", "data": base64.b64encode(_JPEG).decode()}], True, None, None),
- ([], True, "the executor returned no image", "executor_no_image"),
- ([{"mime": "image/jpeg", "data": "@@@ not base64 @@@"}], True, "the image could not be saved: ", "image_not_saved"),
- ([{"mime": "image/jpeg", "data": "/9j/4AAQ"}], False, "nothing here can keep a generated image", "image_no_store"),
+ ([{"data": base64.b64encode(_JPEG).decode()}], True, None, None),
+ ([], True, "the endpoint returned no image", "executor_no_image"),
+ ([{"data": "@@@ not base64 @@@"}], True, "the image could not be saved: ", "image_not_saved"),
+ ([{"data": "/9j/4AAQ"}], False, "nothing here can keep a generated image", "image_no_store"),
],
ids=["saved", "no-image", "unreadable", "no-store"],
)
async def test_an_image_the_endpoint_returns_is_saved_through_the_media_sink_and_its_record_names_the_file(
tmp_path, images, stored, error, code
):
- """MH-HOSTED-VIBEY-007 (vibey-hosted-tools.md §7.3): the gateway answers an ``image_generate`` call's bytes beside
- its record; Vibey saves them through the session media sink, the record lists the file, the result keeps the
- model and what the endpoint rendered, and no base64 reaches the transcript. A completed call that saved no file is
- a failed record whose reason carries its code (#2589), never a completed one listing nothing."""
+ """MH-HOSTED-VIBEY-007 (vibey-hosted-tools.md §7.3, §7.4): Vibey calls the gateway's image endpoint with the call's
+ arguments alone, and the gateway answers the images' bytes beside the record. Vibey saves them through the session
+ media sink and the record lists the files. The result keeps the model the call ran on and what the endpoint
+ reported, and the model reads the path, the model and the cost, never the bytes. A completed call that saved no
+ file is a failed record whose reason carries its code (#2589), never a completed one listing nothing."""
import httpx
- from core.agent_core.ai.provider import ModelEndpoint
- from modules.agents.vibey.tools import HostedTool
-
answer = {
"record": {"status": "completed", "sources": []},
"execution": _DIRECT,
- "generation": {"model": "gpt-image-2", "revised_prompt": "A lighthouse at dusk", "size": "1536x1024", "quality": "high"},
+ "generation": {"revised_prompt": "A lighthouse at dusk", "size": "1536x1024", "quality": "high"},
"images": images,
}
- endpoint = ModelEndpoint("anthropic", "http://hub.invalid/vibey/v1", "claude-opus-5-5", "hub-token")
- async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=answer))) as client:
- tool = HostedTool(
- _IMAGE_SPEC,
- lambda: endpoint,
- client,
- media=MediaSnapshots(None, tmp_path / "media") if stored else None, # type: ignore[arg-type]
+ sent: list[httpx.Request] = []
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ sent.append(request)
+ return httpx.Response(200, json=answer)
+
+ media = MediaSnapshots(None, tmp_path / "media") if stored else None # type: ignore[arg-type]
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ result = await _image_tool(client, media=media).execute(
+ {"model": "gpt-image-2", "prompt": "a lighthouse"}, _tool_context(tmp_path)
)
- result = await tool.execute({"model": "gpt-image-2", "prompt": "a lighthouse"}, None) # type: ignore[arg-type]
+ (request,) = sent
+ assert request.url.path == "/vibey/v1/hosted-tools/image_generate"
+ assert json.loads(request.content) == {"arguments": {"model": "gpt-image-2", "prompt": "a lighthouse"}}
record = result.hosted.record
if error is None:
(image,) = record.images
@@ -2735,17 +2756,278 @@ async def test_an_image_the_endpoint_returns_is_saved_through_the_media_sink_and
assert result.hosted.action == HostedAction(
"generate", prompt="A lighthouse at dusk", size="1536x1024", quality="high", model="gpt-image-2"
)
- assert result.content[0].text.startswith('[image_generate: "A lighthouse at dusk"]')
- assert f"Image saved: {image.path}" in result.content[0].text
+ text = result.content[0].text
+ assert text.startswith('[image_generate: "a lighthouse"]\nModel: gpt-image-2 via openai · cost: ≈ $0.04\n')
+ assert f"Image saved: {image.path}" in text
assert images[0]["data"] not in json.dumps(message_to_dict(
ToolResultMessage("call_1", "image_generate", result.content, hosted=result.hosted)
))
else:
assert result.is_error and record.status == "failed" and record.images == ()
assert record.error.startswith(error) and record.error_code == code
+ assert result.hosted.action == HostedAction("generate", model="gpt-image-2")
assert not (tmp_path / "media").exists() or not any((tmp_path / "media").iterdir())
+ ("arguments", "error", "code", "language"),
+ [
+ ({"model": "dall-e-3", "prompt": "a cat"}, "dall-e-3 is not an image model of this turn. Available: "
+ "gpt-image-2, gemini-3.1-flash-image.", "image_model_unavailable", "en"),
+ ({"model": "gemini-3.1-flash-image", "prompt": "a cat", "images": ["cat.jpg"]},
+ "gemini-3.1-flash-image does not take images. Models that take it: gpt-image-2.", "image_param_unsupported",
+ "en"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "size": "16:9"},
+ "gpt-image-2 does not take size 16:9: it takes WIDTHxHEIGHT, such as 1024x1024. Models that take it: "
+ "gemini-3.1-flash-image.", "image_param_unsupported", "en"),
+ # No model takes both: no alternative is named.
+ ({"model": "gemini-3.1-flash-image", "prompt": "a cat", "size": "16:9", "n": 2},
+ "gemini-3.1-flash-image does not take n.", "image_param_unsupported", "en"),
+ # The forms the image endpoint accepts, no wider.
+ ({"model": "gpt-image-2", "prompt": "a cat", "size": "8x8"}, "size must be WIDTHxHEIGHT",
+ "image_argument_invalid", "en"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "quality": "high"},
+ "image_generate takes only model, prompt, size, images and n; it was given quality.", "image_argument_invalid",
+ "en"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "images": ["missing.jpg"]},
+ "Cannot read the reference image missing.jpg: ", "image_reference_unreadable", "en"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "images": ["notes.txt"]},
+ "The reference image notes.txt is not an image (jpg, png, gif, webp).", "image_reference_unreadable", "en"),
+ # Every reason is worded in the user's language, the ones the gateway also writes as the gateway does.
+ ({"model": "gemini-3.1-flash-image", "prompt": "a cat", "images": ["cat.jpg"]},
+ "gemini-3.1-flash-image 不支持 images。 支持它的模型:gpt-image-2。", "image_param_unsupported", "zh"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "size": "8x8"},
+ "size 必须是宽x高,例如 1024x1024,或宽高比,例如 16:9。", "image_argument_invalid", "zh"),
+ ({"model": "gpt-image-2", "prompt": "a cat", "images": ["notes.txt"]},
+ "参考图片 notes.txt 不是图片(jpg、png、gif、webp)。", "image_reference_unreadable", "zh"),
+ ({"model": "gpt-image-2", "prompt": "make it blue", "images": ["cat.jpg"], "n": 2}, None, None, "en"),
+ # An empty list is no reference image: the call goes out without it.
+ ({"model": "gemini-3.1-flash-image", "prompt": "a cat", "images": [], "size": "16:9"}, None, None, "en"),
+ ],
+ ids=["model-outside-the-turn", "param-the-model-does-not-take", "size-form-the-model-does-not-take",
+ "no-model-takes-the-call", "size-in-no-form", "unknown-argument", "reference-missing",
+ "reference-not-an-image", "zh-param", "zh-size-in-no-form", "zh-reference-not-an-image", "reference-sent",
+ "no-reference"],
+)
+async def test_an_image_call_is_checked_against_the_turns_models_and_its_references_read_before_it_runs(
+ tmp_path, arguments, error, code, language
+):
+ """§7.2, §7.4: Vibey refuses an argument the turn's frozen models do not take before anything runs, and names
+ what does take it; a reference image is read as ``read`` reads it, relative to the session's directory, and sent
+ as base64. A path the agent could not read fails the call before it is sent. Every reason carries its code, the
+ display key the card and the IM line render in the viewer's language (#2589), and its text is in the user's."""
+ import httpx
+
+ (tmp_path / "cat.jpg").write_bytes(_JPEG)
+ (tmp_path / "notes.txt").write_text("not an image")
+ sent: list[httpx.Request] = []
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ sent.append(request)
+ return httpx.Response(200, json={"record": {"status": "failed", "error": "upstream refused"}})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ result = await _image_tool(client, language=language).execute(arguments, _tool_context(tmp_path))
+
+ if error is None:
+ (request,) = sent
+ expected = {key: value for key, value in arguments.items() if value != []}
+ if "images" in expected:
+ expected["images"] = [base64.b64encode(_JPEG).decode()]
+ assert json.loads(request.content) == {"arguments": expected}
+ else:
+ assert sent == [] and result.is_error
+ record = result.hosted.record
+ assert record.error.startswith(error) and record.error_code == code and result.hosted.execution is None
+
+
+async def test_vibeys_image_tool_runs_on_the_gateways_image_endpoint_from_the_hop_it_resolves(tmp_path, monkeypatch):
+ """MH-HOSTED-VIBEY-007, closed loop at the seam: Vibey builds ``image_generate`` from the hop the real gateway
+ resolves, reads a reference image from the session's directory, and calls the gateway's real image endpoint,
+ whose recording engine answers as the images endpoint does. What Vibey sends is what the endpoint accepts, and
+ what it answers is what Vibey saves. Each result reaches the user through the hosted-activity reader the card and
+ the IM line render (``core/hosted_activity``): direct, the model, its Source, the files and the cost, and a call
+ refused before it ran in the user's language."""
+ from dataclasses import replace as replaced
+
+ import httpx
+
+ from core.agent_core.messages import ToolCallBlock
+ from core.handlers.model_hub import hosted_tools as hosted_tools_module
+ from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+ from core.hosted_activity import hosted_line, proxy_activity
+ from modules.agents.model_hub import ModelHubRuntimeRouter
+ from modules.agents.vibey.models import HubModelRouter, selection_from_hop
+ from modules.agents.vibey.tools import hosted_tools
+ from tests.test_model_hub_hosted_images import GEMINI, OPENAI, PNG, PRICED, _served, _sources
+ from tests.test_model_hub_vibey_consumer import _vibey_service
+
+ # GPT Image at a list price per delivered size, taking reference images.
+ bundled = hosted_tools_module.provider_image_models
+ priced = replaced(PRICED, params=("images", "n", "size"))
+ monkeypatch.setattr(
+ hosted_tools_module, "provider_image_models", lambda vendor: (priced,) if vendor == "openai" else bundled(vendor)
+ )
+ (tmp_path / "cat.png").write_bytes(base64.b64decode(PNG))
+ service = _vibey_service(tmp_path, _sources(), handles=[_served(PNG, source_id=GEMINI), _served(PNG, size="1536x1024")])
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ names = {GEMINI: "Gemini key", OPENAI: "OpenAI key"}
+
+ async def resolve():
+ return selection_from_hop(await router.resolve_hop("menu-alias", process_scope="vibey:image", turn_id="turn-image"))
+
+ calls = (
+ {"model": "gemini-2.5-flash-image", "prompt": "a cat", "size": "16:9"},
+ {"model": "gpt-image-2", "prompt": "make it blue", "images": ["cat.png"]},
+ # Refused before it ran: Gemini takes no reference images.
+ {"model": "gemini-2.5-flash-image", "prompt": "make it red", "images": ["cat.png"]},
+ )
+ try:
+ turn = HubModelRouter(resolve, lambda protocol: None, first=await resolve())
+ async with httpx.AsyncClient(trust_env=False) as client:
+ tools = hosted_tools(turn, client, MediaSnapshots(None, tmp_path / "media"), language=lambda: "zh")
+ (tool,) = [tool for tool in tools if tool.spec.name == "image_generate"]
+ results = [await tool.execute(arguments, _tool_context(tmp_path)) for arguments in calls]
+ finally:
+ await gateway.close()
+
+ assert service.adapter.invocations == [(GEMINI, "gemini-2.5-flash-image", "vibey"), (OPENAI, "gpt-image-2", "vibey")]
+ assert service.adapter.requests[1]["images"] == [{"image_url": f"data:image/png;base64,{PNG}"}]
+ drawn, edited, refused = (
+ proxy_activity(ToolCallBlock(f"call_{n}", "image_generate", arguments), result.hosted, source_names=names.get)
+ for n, (arguments, result) in enumerate(zip(calls, results))
+ )
+ for activity, result, (source, model) in (
+ (drawn, results[0], (GEMINI, "gemini-2.5-flash-image")),
+ (edited, results[1], (OPENAI, "gpt-image-2")),
+ ):
+ assert not result.is_error, result.content[0].text
+ (image,) = result.hosted.record.images
+ assert Path(image.path).read_bytes() == base64.b64decode(PNG) and image.mime == "image/png"
+ card = activity.to_payload()
+ assert (card["mode"], card["status"], card["model"]) == ("direct", "completed", model)
+ assert (card["source_id"], card["source_name"]) == (source, names[source])
+ assert [item["path"] for item in card["images"]] == [image.path]
+ assert edited.to_payload()["images"][0]["width"] == 1536 and edited.to_payload()["cost"] == {
+ "basis": "list", "calls": 1, "usd": 0.07,
+ }
+ assert "cost" not in drawn.to_payload() # unpriced, never zero
+ assert hosted_line(edited, "en") == '🖼 Image generation “make it blue” · gpt-image-2 · 1536×1024 · ≈ $0.07'
+ # Refused before it ran: still direct, naming the model it was refused for, and why in the user's language.
+ card = refused.to_payload()
+ assert (card["mode"], card["status"], card["model"], card["error_code"]) == (
+ "direct", "failed", "gemini-2.5-flash-image", "image_param_unsupported",
+ )
+ assert card["error"] == "gemini-2.5-flash-image 不支持 images。 支持它的模型:gpt-image-2。"
+ assert hosted_line(refused, "zh") == "🖼 图片生成 “make it red” · 失败:所选图片模型不支持其中一个参数"
+
+
+def _image_entry(*model_ids: str) -> dict:
+ """``HopResolution.hosted_tools.image_generate`` for ``model_ids``, the first the default."""
+ entries = {model_id: (description, list(params), list(forms)) for model_id, description, params, forms in _IMAGE_MODELS}
+ models = [
+ {"source_id": "src_executor01", "model_id": model_id, "description": entries[model_id][0],
+ "params": sorted(entries[model_id][1]), "size_forms": entries[model_id][2]}
+ for model_id in model_ids
+ ]
+ return {"models": models, "default": {"source_id": "src_executor01", "model_id": model_ids[0]}}
+
+
+ ("said", "stop", "status", "replied"),
+ [
+ ("Here is your lighthouse.", "stop", "completed", True),
+ (None, "stop", "completed", True),
+ # A refusal is the turn's outcome even after an image: the image is still delivered.
+ (None, "refusal", "completed", False),
+ # Only a completed call's images count: a final that says nothing after a failed one is an empty reply.
+ (None, "stop", "failed", False),
+ ],
+ ids=["with-text", "image-only", "refusal-after-an-image", "after-a-failed-call"],
+)
+async def test_a_generated_image_reaches_the_user_with_the_turns_reply_even_when_the_model_says_nothing(
+ engine, session, tmp_path, published, said, stop, status, replied
+) -> None:
+ """MH-HOSTED-UI-012 (vibey-hosted-tools.md §3.4, §7.3): the turn declares ``image_generate`` with the image models
+ its first hop offers, and keeps that enum for the whole turn even when a later hop offers others. A completed
+ image is delivered with the turn's reply as an attachment. A final that ends normally without text after it is
+ still a reply, the image under its heading, never the empty-reply error; a refusal stays the turn's failure. The
+ final row is that complete reply as it commits, before delivery rewrites it, so a process that stops in between
+ still leaves the image's terminal result."""
+ import httpx
+
+ from modules.agents.vibey.store import AdapterTranscriptStore
+
+ completed = {
+ "record": {"status": "completed", "sources": []},
+ "execution": _DIRECT,
+ "generation": {"size": "1024x1024"},
+ "images": [{"data": base64.b64encode(_JPEG).decode()}],
+ }
+ answer = completed if status == "completed" else {"record": {"status": "failed", "error": "upstream refused"}}
+ harness: Optional[_Harness] = None
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/vibey/v1/hosted-tools/image_generate"
+ # An image refusal recorded mid-turn changes later hops' image models, never this turn's tools.
+ harness.controller.hub_hosted_tools = {"image_generate": _image_entry("gemini-3.1-flash-image")}
+ return httpx.Response(200, json=answer)
+
+ call = ToolCallBlock(id="call_img", name="image_generate", arguments={"model": "gpt-image-2", "prompt": "a lighthouse"})
+ final = AssistantMessage((TextBlock(text=said),) if said else (), ORIGIN, stop)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(
+ engine,
+ tmp_path,
+ "telegram",
+ [[Done(AssistantMessage((call,), ORIGIN, "tool_use"))], [Done(final)]],
+ gateway_client=client,
+ )
+ harness.controller.hub_hosted_tools = {"image_generate": _image_entry("gpt-image-2", "gemini-3.1-flash-image")}
+ # The final row as it commits, before delivery rewrites it.
+ committed: list[dict] = []
+ append = AdapterTranscriptStore.append_response
+
+ async def append_response(self, session_id, message, **kwargs):
+ entry = await append(self, session_id, message, **kwargs)
+ if kwargs.get("final"):
+ with engine.connect() as conn:
+ row = conn.execute(select(messages).where(messages.c.id == entry.row_id)).mappings().one()
+ committed.append({"type": row["type"], "text": row["content_text"]})
+ return entry
+
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(AdapterTranscriptStore, "append_response", append_response)
+ await harness.agent.handle_message(harness.request("draw a lighthouse"))
+
+ first, second = (
+ next(tool for tool in request.tools if tool.name == "image_generate") for request in harness.provider.requests
+ )
+ assert first == second
+ assert first.input_schema["properties"]["model"]["enum"] == ["gpt-image-2", "gemini-3.1-flash-image"]
+ assert harness.controller.terminals[-1]["is_error"] is not replied
+ result = next(row.message for row in await harness.context_rows() if isinstance(row.message, ToolResultMessage))
+ images = result.hosted.record.images
+ assert harness.controller.im_client.uploads == [str(Path(image.path).resolve()) for image in images]
+ assert len(images) == (1 if status == "completed" else 0)
+ empty = i18n_t("vibeyAgent.error.emptyResponse", "en")
+ (as_committed,) = committed
+ links = [f"]({Path(image.path).as_uri()})" for image in images]
+ assert all(link in as_committed["text"] for link in links)
+ if replied:
+ [row] = harness.rows("result")
+ assert row["content_text"].startswith(said or i18n_t("info.generatedImagesFallback", "en"))
+ assert not any(empty in item for item in harness.controller.im_client.sent)
+ assert as_committed["type"] == "result"
+ assert as_committed["text"].startswith(said or i18n_t("info.generatedImagesFallback", "en"))
+ else:
+ assert as_committed["type"] == "error"
+ [row] = harness.rows("error")
+ assert harness.rows("result") == []
+ assert (empty in row["content_text"]) is (stop == "stop")
+
+
async def test_a_proxied_call_after_the_turn_moved_to_another_source_runs_on_the_hop_it_now_holds(
tmp_path, monkeypatch
):
@@ -3729,14 +4011,13 @@ async def test_a_proxied_hosted_result_shows_once_its_result_is_committed(engine
def test_an_image_is_attached_unless_the_reply_already_links_it(tmp_path) -> None:
"""A prose mention of the path is not a delivered file; a relative path names no file to send."""
- from modules.agents.vibey.agent import _Run, VibeyAgent
+ from modules.agents.vibey.agent import VibeyAgent
image = tmp_path / "image-3f2a.png"
- run = _Run(request=None, session_id=SESSION, turn_id="turn", instance="test")
- run.hosted_images = [("relative.png", "relative.png"), (str(image), image.name)]
+ images = [("relative.png", "relative.png"), (str(image), image.name)]
- assert VibeyAgent._hosted_image_links(run, f"Saved it to {image}.") == f"![{image.name}]({image.as_uri()})"
- assert VibeyAgent._hosted_image_links(run, f"Here: ![night]({image.as_uri()})") == ""
+ assert VibeyAgent._image_links(images, f"Saved it to {image}.") == f"![{image.name}]({image.as_uri()})"
+ assert VibeyAgent._image_links(images, f"Here: ![night]({image.as_uri()})") == ""
async def test_a_hosted_named_call_without_a_record_still_shows_its_tool_line(engine, session, tmp_path, published) -> None:
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 3c3e64cf9..8db915b22 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4967,7 +4967,18 @@
"gateway_refused": "The model gateway refused the call.",
"gateway_no_result": "The model gateway returned no result.",
"image_param_unsupported": "The chosen image model doesn't take one of the arguments.",
- "image_model_unavailable": "The chosen image model isn't available."
+ "image_model_unavailable": "The chosen image model isn't available.",
+ "image_argument_invalid": "The image call had an argument it can't send.",
+ "image_reference_unreadable": "A reference image couldn't be read.",
+ "provider_refused": "The provider refused the call.",
+ "provider_timed_out": "The call timed out.",
+ "provider_unreachable": "Couldn't reach the provider.",
+ "provider_unreadable": "The provider's response couldn't be read.",
+ "provider_too_large": "The provider's response was larger than allowed.",
+ "provider_image_unusable": "The provider returned an image that couldn't be used.",
+ "search_not_run": "The model answered without searching.",
+ "search_failed": "The provider's search failed.",
+ "response_ended_early": "The response ended early."
},
"mode": {
"native": "Native · {{provider}}",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 78226ab9c..d4d276192 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4967,7 +4967,18 @@
"gateway_refused": "模型网关拒绝了这次调用。",
"gateway_no_result": "模型网关没有返回结果。",
"image_param_unsupported": "所选图片模型不支持其中一个参数。",
- "image_model_unavailable": "所选图片模型当前不可用。"
+ "image_model_unavailable": "所选图片模型当前不可用。",
+ "image_argument_invalid": "图片调用的参数无法发送。",
+ "image_reference_unreadable": "无法读取参考图片。",
+ "provider_refused": "供应商拒绝了这次调用。",
+ "provider_timed_out": "调用超时。",
+ "provider_unreachable": "无法连接供应商。",
+ "provider_unreadable": "无法读取供应商的回复。",
+ "provider_too_large": "供应商的回复超出了大小上限。",
+ "provider_image_unusable": "供应商返回的图片无法使用。",
+ "search_not_run": "模型没有搜索就直接作答了。",
+ "search_failed": "供应商的搜索失败了。",
+ "response_ended_early": "回复提前结束了。"
},
"mode": {
"native": "原生 · {{provider}}",
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index 6936b32b9..09e6832b7 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -679,7 +679,13 @@ _HOSTED_TOOL_PRICE_UNITS = ("call", "search", "post", "profile")
_IMAGE_PRICE_UNITS = ("image",)
# The tools a chat request may declare natively. Image generation is never one (vibey-hosted-tools.md §7).
OVERLAY_SEARCH_TOOLS: tuple[str, ...] = ("web_search", "x_search")
-IMAGE_MODEL_ENDPOINTS: tuple[str, ...] = ("images", "chat_image")
+# The credential kinds an image model's route may be offered on; absent means every kind.
+IMAGE_MODEL_KINDS: tuple[str, ...] = ("api_key", "subscription")
+# What a call names itself; an image model's fixed request fields may not set them.
+IMAGE_CALL_FIELDS: frozenset[str] = frozenset({"model", "prompt", "size", "aspect_ratio", "n", "images", "stream"})
+# The protocols whose engine entries serve the images endpoints (vibey-hosted-tools.md §7.4): an image model is
+# offered, registered and called on a Source of one of them only.
+IMAGE_PROTOCOLS: frozenset[str] = frozenset({"openai_responses", "openai_chat"})
IMAGE_MODEL_PARAMS: tuple[str, ...] = ("images", "n", "size")
IMAGE_SIZE_FORMS: tuple[str, ...] = ("pixels", "ratio")
# One line in every request's tool block: bounded so a catalog line cannot grow every prompt prefix.
@@ -744,18 +750,26 @@ class ImageModelPrice:
class ImageModelSpec:
"""One image model a vendor offers to ``image_generate`` (capability model §4).
+ Every one runs through the engine's images endpoints (``vibey-hosted-tools.md`` §7.4).
``params`` and ``size_forms`` are sorted, so anything built from them is stable.
+ ``kinds`` are the credential kinds its route was verified on. ``request`` holds the
+ fixed fields every call to it sends (an output format, base64 results).
``tokens_per_image`` lets the pricing module estimate a model with no per-image price.
"""
id: str
description: str
- endpoint: Literal["images", "chat_image"]
params: tuple[str, ...]
size_forms: tuple[str, ...]
+ kinds: tuple[str, ...] = IMAGE_MODEL_KINDS
+ request_json: str = "{}"
prices: tuple[ImageModelPrice, ...] = ()
tokens_per_image: int | None = None
+ @property
+ def request(self) -> dict[str, Any]:
+ return json.loads(self.request_json)
+
@dataclass(frozen=True)
class ProviderModelOverlay:
@@ -880,17 +894,22 @@ def _overlay_image_model(raw: object) -> ImageModelSpec:
model = _overlay_object(
raw,
"image model",
- required=("id", "description", "endpoint", "params", "size_forms"),
- optional=("prices", "tokens_per_image"),
+ required=("id", "description", "params", "size_forms"),
+ optional=("kinds", "request", "prices", "tokens_per_image"),
)
description = model["description"]
if not isinstance(description, str) or not _OVERLAY_TOKEN.fullmatch(description) or (
len(description) > IMAGE_MODEL_DESCRIPTION_MAX_CHARS
):
raise ValueError(f"image model description must be one line of at most {IMAGE_MODEL_DESCRIPTION_MAX_CHARS} characters")
- endpoint = model["endpoint"]
- if endpoint not in IMAGE_MODEL_ENDPOINTS:
- raise ValueError("image model endpoint is not known")
+ kinds = _overlay_tokens(model.get("kinds", list(IMAGE_MODEL_KINDS)), "image model kinds")
+ if not kinds or set(kinds) - set(IMAGE_MODEL_KINDS):
+ raise ValueError("image model kinds name an unknown credential kind")
+ request = model.get("request", {})
+ if not isinstance(request, dict) or set(request) & IMAGE_CALL_FIELDS or not all(
+ isinstance(value, (str, int, float, bool)) for value in request.values()
+ ):
+ raise ValueError("image model request holds fixed scalar fields a call does not name")
params = _overlay_tokens(model["params"], "image model params")
size_forms = _overlay_tokens(model["size_forms"], "image model size_forms")
if set(params) - set(IMAGE_MODEL_PARAMS) or set(size_forms) - set(IMAGE_SIZE_FORMS):
@@ -906,9 +925,10 @@ def _overlay_image_model(raw: object) -> ImageModelSpec:
return ImageModelSpec(
id=_overlay_token(model["id"], "image model id"),
description=description,
- endpoint=endpoint,
params=tuple(sorted(params)),
size_forms=tuple(sorted(size_forms)),
+ kinds=tuple(sorted(kinds)),
+ request_json=json.dumps(request, sort_keys=True),
prices=tuple(_overlay_image_price(item) for item in prices),
tokens_per_image=tokens,
)
diff --git a/vibe/data/backend_models.json b/vibe/data/backend_models.json
index 7e9cf09d3..9e80174c0 100644
--- a/vibe/data/backend_models.json
+++ b/vibe/data/backend_models.json
@@ -81,6 +81,39 @@
}
}
}
+ ],
+ "image_models": [
+ {
+ "id": "gpt-image-2",
+ "description": "GPT Image 2: precise prompts, legible text, edits",
+ "params": ["images", "n", "size"],
+ "size_forms": ["pixels"],
+ "kinds": ["api_key"],
+ "request": {"output_format": "jpeg", "output_compression": 90}
+ }
+ ]
+ },
+ "gemini": {
+ "models": [],
+ "image_models": [
+ {
+ "id": "gemini-2.5-flash-image",
+ "description": "Gemini 2.5 Flash Image (Nano Banana): fast generation",
+ "params": ["n", "size"],
+ "size_forms": ["ratio"],
+ "kinds": ["api_key"],
+ "request": {"response_format": "b64_json"},
+ "tokens_per_image": 1290
+ },
+ {
+ "id": "gemini-3-pro-image-preview",
+ "description": "Gemini 3 Pro Image (Nano Banana Pro): high fidelity, text rendering",
+ "params": ["n", "size"],
+ "size_forms": ["ratio"],
+ "kinds": ["api_key"],
+ "request": {"response_format": "b64_json"},
+ "tokens_per_image": 1120
+ }
]
},
"xai": {
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index f57710b18..5c729840a 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1165,7 +1165,11 @@
"upstream_error": "The upstream service returned an error."
},
"hostedTools": {
- "noExecutor": "No Source can run {tool} right now. Add a Source from one of these providers to use it: {vendors}.",
+ "noExecutor": {
+ "web_search": {"one": "No Source can run web search right now. Add an API key from {vendors}.", "several": "No Source can run web search right now. Add an API key from one of {vendors}."},
+ "x_search": {"one": "No Source can run X search right now. Add an API key from {vendors}.", "several": "No Source can run X search right now. Add an API key from one of {vendors}."}
+ },
+ "listSeparator": ", ",
"providerRefused": "The executor's provider refused the call ({detail}).",
"timedOut": "The executor call timed out.",
"unreachable": "The executor could not be reached.",
@@ -1174,7 +1178,13 @@
"didNotRun": "The executor did not run {tool}.",
"responseEnded": "The executor's response ended as {status}.",
"callFailed": "The provider's {tool} call failed.",
- "triedSources": "Tried: {sources}."
+ "triedSources": "Tried: {sources}.",
+ "imageMissing": "The image endpoint returned no image data.",
+ "imageUnreadable": "The image endpoint returned an image that could not be used.",
+ "imageModelUnavailable": "{model} is no longer available this turn.",
+ "imageParamUnsupported": "{model} does not take {param}.",
+ "imageParamTakers": "Models that take it: {models}.",
+ "imageAlternatives": "Available: {models}."
},
"events": {
"sourceFallback": "source",
@@ -1807,7 +1817,18 @@
"gateway_refused": "the model gateway refused the call",
"gateway_no_result": "the model gateway returned no result",
"image_param_unsupported": "the chosen image model doesn't take one of the arguments",
- "image_model_unavailable": "the chosen image model isn't available"
+ "image_model_unavailable": "the chosen image model isn't available",
+ "image_argument_invalid": "the image call had an argument it can't send",
+ "image_reference_unreadable": "a reference image couldn't be read",
+ "provider_refused": "the provider refused the call",
+ "provider_timed_out": "the call timed out",
+ "provider_unreachable": "couldn't reach the provider",
+ "provider_unreadable": "the provider's response couldn't be read",
+ "provider_too_large": "the provider's response was larger than allowed",
+ "provider_image_unusable": "the provider returned an image that couldn't be used",
+ "search_not_run": "the model answered without searching",
+ "search_failed": "the provider's search failed",
+ "response_ended_early": "the response ended early"
},
"tool": {
"web_search": "Web search",
@@ -1840,6 +1861,25 @@
"failed": "failed: {error}",
"incomplete": "incomplete: {error}",
"pending": "cut off"
+ },
+ "image": {
+ "notOffered": "{model} is not an image model of this turn.",
+ "unknownArguments": "image_generate takes only model, prompt, size, images and n; it was given {names}.",
+ "noPrompt": "prompt must be the text of what to draw.",
+ "sizeForm": "size must be {pixels}, or {ratio}.",
+ "sizeFormUnsupported": "{model} does not take size {size}: it takes {form}.",
+ "badImages": "images must be 1 to {max} paths of reference images.",
+ "badCount": "n must be a whole number from 1 to {max}.",
+ "form": {
+ "pixels": "WIDTHxHEIGHT, such as 1024x1024",
+ "ratio": "an aspect ratio, such as 16:9"
+ },
+ "reference": {
+ "unreadable": "Cannot read the reference image {path}: {reason}.",
+ "notImage": "The reference image {path} is not an image (jpg, png, gif, webp).",
+ "tooLarge": "The reference image {path} is {size}, over the {limit} limit.",
+ "unsupported": "The reference image {path} is {mime}, which cannot be sent."
+ }
}
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 34e656c17..a02acd565 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1165,7 +1165,11 @@
"upstream_error": "供应商返回错误。"
},
"hostedTools": {
- "noExecutor": "当前没有可运行 {tool} 的来源。添加以下任一供应商的来源即可使用:{vendors}。",
+ "noExecutor": {
+ "web_search": {"one": "当前没有能运行网页搜索的供应商。请添加 {vendors} 的 API Key。", "several": "当前没有能运行网页搜索的供应商。请添加 {vendors} 其中一家的 API Key。"},
+ "x_search": {"one": "当前没有能运行 X 搜索的供应商。请添加 {vendors} 的 API Key。", "several": "当前没有能运行 X 搜索的供应商。请添加 {vendors} 其中一家的 API Key。"}
+ },
+ "listSeparator": "、",
"providerRefused": "执行方的供应商拒绝了此次调用({detail})。",
"timedOut": "执行方调用超时。",
"unreachable": "无法连接执行方。",
@@ -1174,7 +1178,13 @@
"didNotRun": "执行方没有运行 {tool}。",
"responseEnded": "执行方的响应以 {status} 结束。",
"callFailed": "供应商的 {tool} 调用失败。",
- "triedSources": "已尝试:{sources}。"
+ "triedSources": "已尝试:{sources}。",
+ "imageMissing": "图像端点没有返回图像数据。",
+ "imageUnreadable": "图像端点返回的图像无法使用。",
+ "imageModelUnavailable": "本轮中 {model} 已不可用。",
+ "imageParamUnsupported": "{model} 不支持 {param}。",
+ "imageParamTakers": "支持它的模型:{models}。",
+ "imageAlternatives": "可用:{models}。"
},
"events": {
"sourceFallback": "供应商",
@@ -1807,7 +1817,18 @@
"gateway_refused": "模型网关拒绝了这次调用",
"gateway_no_result": "模型网关没有返回结果",
"image_param_unsupported": "所选图片模型不支持其中一个参数",
- "image_model_unavailable": "所选图片模型当前不可用"
+ "image_model_unavailable": "所选图片模型当前不可用",
+ "image_argument_invalid": "图片调用的参数无法发送",
+ "image_reference_unreadable": "无法读取参考图片",
+ "provider_refused": "供应商拒绝了这次调用",
+ "provider_timed_out": "调用超时",
+ "provider_unreachable": "无法连接供应商",
+ "provider_unreadable": "无法读取供应商的回复",
+ "provider_too_large": "供应商的回复超出了大小上限",
+ "provider_image_unusable": "供应商返回的图片无法使用",
+ "search_not_run": "模型没有搜索就直接作答了",
+ "search_failed": "供应商的搜索失败了",
+ "response_ended_early": "回复提前结束了"
},
"tool": {
"web_search": "网页搜索",
@@ -1840,6 +1861,25 @@
"failed": "失败:{error}",
"incomplete": "未完成:{error}",
"pending": "已中断"
+ },
+ "image": {
+ "notOffered": "{model} 不是本轮可用的图片模型。",
+ "unknownArguments": "image_generate 只接受 model、prompt、size、images 和 n,却收到了 {names}。",
+ "noPrompt": "prompt 必须写明要画的内容。",
+ "sizeForm": "size 必须是{pixels},或{ratio}。",
+ "sizeFormUnsupported": "{model} 不支持尺寸 {size}:它只接受{form}。",
+ "badImages": "images 必须是 1 到 {max} 个参考图片路径。",
+ "badCount": "n 必须是 1 到 {max} 之间的整数。",
+ "form": {
+ "pixels": "宽x高,例如 1024x1024",
+ "ratio": "宽高比,例如 16:9"
+ },
+ "reference": {
+ "unreadable": "无法读取参考图片 {path}:{reason}。",
+ "notImage": "参考图片 {path} 不是图片(jpg、png、gif、webp)。",
+ "tooLarge": "参考图片 {path} 有 {size},超过 {limit} 的上限。",
+ "unsupported": "参考图片 {path} 是 {mime},无法发送。"
+ }
}
}
}
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index c826e20ab..8859ed2f5 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -33,6 +33,7 @@ from core.handlers.model_hub.adapter import (
from core.handlers.model_hub.async_owner import run_owned_in_thread
from core.handlers.model_hub.classification import UPSTREAM_MACHINE_ERROR_CODES
from core.handlers.model_hub.events import bounded_diagnostic_detail
+from core.handlers.model_hub.hosted_images import IMAGE_RESPONSE_MAX_BYTES
from core.handlers.model_hub.json_wire import (
JSONEvent,
JSONPath,
@@ -70,6 +71,12 @@ _ENGINE_TRANSPORT_FAILURE = re.compile(
# This threshold only selects memory or a temporary file; it never rejects or
# truncates upstream response bytes.
_PRELUDE_MEMORY_BYTES = 256 * 1024
+# A buffered answer is spooled whole before it is read. An image answer, served or refused, is bounded while it
+# downloads, so a relay that never stops cannot fill the disk before the image call rejects it
+# (vibey-hosted-tools.md §7.4).
+_BUFFERED_RESPONSE_MAX_BYTES: Mapping[str, int] = {"openai_images": IMAGE_RESPONSE_MAX_BYTES}
+# The machine code of an answer cut at that bound; L1's own, never an upstream's.
+RESPONSE_TOO_LARGE = "response_too_large"
_ERROR_OBSERVATION_BYTES = 256 * 1024
# Projecting a response body that has already arrived is local work. It has
# its own budget so the client's connection budget never limits it.
@@ -466,6 +473,11 @@ class EngineClient:
endpoint += "?alt=sse"
body.pop("model", None)
body.pop("stream", None)
+ elif request_protocol == "openai_images":
+ # Reference images make an edit (vibey-hosted-tools.md §7.4). An images call is
+ # always buffered, and names no stream: not every images endpoint reads one.
+ endpoint = "/v1/images/edits" if "images" in body else "/v1/images/generations"
+ body["model"] = routed_model
else:
endpoint = _endpoint_for_protocol(request_protocol)
body["model"] = routed_model
@@ -500,6 +512,9 @@ class EngineClient:
# bound, and one that runs out closes the engine connection, which
# cancels the upstream request. A buffered response sends nothing until
# it is complete, so it has none.
+ bound = _BUFFERED_RESPONSE_MAX_BYTES.get(request_protocol)
+ # A body can carry megabytes of images: encoded off the controller loop.
+ encoded = await run_owned_in_thread(lambda: json.dumps(body).encode("utf-8"))
trace_configs: list[aiohttp.TraceConfig] = []
if on_request_sent is not None:
# CPA resolves the route as soon as it reads the body, while a
@@ -550,10 +565,21 @@ class EngineClient:
)
return completed_handle(outcome)
+ def cut(status: int) -> EngineInvokeHandle:
+ # A local cut, like a transport failure: nothing past the bound was read or observed.
+ return ended(_outcome(
+ kind=RawOutcomeKind.NETWORK_ERROR,
+ source=source,
+ model_id=model_id,
+ http_status=status,
+ error_code=RESPONSE_TOO_LARGE,
+ message="upstream response exceeded its bound",
+ ))
+
try:
response = await session.post(
self._url(endpoint),
- json=body,
+ data=encoded,
headers=headers,
allow_redirects=False,
)
@@ -565,7 +591,7 @@ class EngineClient:
error_body = _StreamPrelude()
try:
await asyncio.wait_for(
- _read_response_into(response.content, error_body),
+ _read_response_into(response.content, error_body, max_bytes=bound),
timeout=self.timeout,
)
observed_payload = await _observe_buffered_protocol_response_async(
@@ -579,6 +605,10 @@ class EngineClient:
except (asyncio.TimeoutError, aiohttp.ClientError):
payload = b""
observed_payload = ProtocolObservation()
+ except _ResponseTooLarge:
+ response.close()
+ await session.close()
+ return cut(response.status)
finally:
error_body.close()
if retry_after is None:
@@ -637,7 +667,15 @@ class EngineClient:
buffered_body = _StreamPrelude()
prelude = buffered_body
await buffered_body.write_async(first)
- await _read_response_into(response.content, buffered_body)
+ try:
+ await _read_response_into(
+ response.content, buffered_body, max_bytes=None if bound is None else bound - len(first),
+ )
+ except _ResponseTooLarge:
+ buffered_body.close()
+ response.close()
+ await session.close()
+ return cut(response.status)
observation = await _observe_buffered_protocol_response_async(
observe_buffered_protocol_response,
request_protocol,
@@ -1351,10 +1389,18 @@ def _is_local_model_registration_failure(
return False
error = decoded.get("error")
error_type, _, _ = _raw_error_fields(payload)
+ message = error.get("message") if isinstance(error, dict) else None
return (
- isinstance(error, dict)
- and error_type == "invalid_request_error"
- and error.get("message") == f"unknown provider for model {routed_model}"
+ error_type == "invalid_request_error"
+ and isinstance(message, str)
+ and (
+ message == f"unknown provider for model {routed_model}"
+ # Its images handler refuses, before any upstream, a model it does not route
+ # there (sdk/api/handlers/openai/openai_images_handlers.go at d318bcc3).
+ or message.startswith(
+ f"Model {routed_model} is not supported on /v1/images/generations or /v1/images/edits."
+ )
+ )
)
@@ -1505,11 +1551,22 @@ def _project_raw_error_fields(
return types[0] if types else None, codes[0] if codes else None, candidates
+class _ResponseTooLarge(Exception):
+ """A response grew past the bound its request protocol sets."""
+
+
async def _read_response_into(
content: aiohttp.StreamReader,
target: _StreamPrelude,
+ *,
+ max_bytes: int | None = None,
) -> None:
+ received = 0
while chunk := await content.read(_STREAM_CHUNK_BYTES):
+ received += len(chunk)
+ if max_bytes is not None and received > max_bytes:
+ # Stop reading: what is past the bound is never written anywhere.
+ raise _ResponseTooLarge
await target.write_async(chunk)
diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.py
index 482afd3d3..ca6329fb1 100644
--- a/vibe/model_hub_runtime/config.py
+++ b/vibe/model_hub_runtime/config.py
@@ -14,6 +14,7 @@ from vibe.model_hub_runtime.api_key_vendors import (
openai_compatible_endpoint,
validate_api_key_auth_scheme,
)
+from vibe.backend_model_catalog import IMAGE_PROTOCOLS, provider_image_models
from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, RuntimeSecrets, SourceRecord
# The engine rotates main.log at 10 MB and deletes the oldest rotated files beyond this total.
@@ -140,7 +141,8 @@ def _append_source(
# Its name match is looser than a routed ID (see _engine_model_name) and
# takes the first entry that matches, so models it cannot tell apart are
# declared text-only together or not at all.
- routed = tuple(dict.fromkeys((*source.model_ids, *source.route_model_ids)))
+ images = image_model_ids(source)
+ routed = tuple(dict.fromkeys((*source.model_ids, *source.route_model_ids, *images)))
marked = set(source.text_only_model_ids) if source.protocol == "openai_chat" else set()
unmarked_names = {_engine_model_name(model) for model in routed if model not in marked}
text_only = {model for model in marked if _engine_model_name(model) not in unmarked_names}
@@ -157,6 +159,10 @@ def _append_source(
entry["thinking"] = {"levels": list(reversed(reasoning_efforts))}
if model in text_only:
entry["input-modalities"] = ["text"]
+ if model in images and source.protocol == "openai_chat":
+ # An OpenAI-compatible entry serves the images endpoints only for a model it flags
+ # (CPA config_types.go OpenAICompatibilityModel.Image); gpt-image names pass unflagged.
+ entry["image"] = True
models.append(entry)
if source.protocol == "google":
if not source.base_url:
@@ -230,11 +236,23 @@ def expected_model_names(
metadata = store.credential_metadata_if_present(source.credential_ref)
if metadata is None or metadata.get("kind") != "api_key":
continue
- for model in (*source.model_ids, *source.route_model_ids):
+ for model in dict.fromkeys((*source.model_ids, *source.route_model_ids, *image_model_ids(source))):
expected[f"{source.prefix}/{model}"] = reload_display_name(model, generation)
return expected
+def image_model_ids(source: SourceRecord) -> tuple[str, ...]:
+ """The vendor's image models an API-key Source's engine entry registers, so ``image_generate`` can route them.
+
+ Only models whose route was verified on API keys, on a protocol whose engine
+ entry serves the images endpoints.
+ """
+
+ if source.protocol not in IMAGE_PROTOCOLS:
+ return ()
+ return tuple(spec.id for spec in provider_image_models(source.vendor) if "api_key" in spec.kinds)
+
+
def _engine_model_name(model: str) -> str:
"""The name CLIProxyAPI compares when it looks up a model's input modalities.