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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): hosted-tool contracts and capability foundation (#2549)
Call White7e357278ea9e
diff --git a/config/v2_config.py b/config/v2_config.pyindex e40a85569..9270e8ce4 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -35,6 +35,7 @@ from config.platform_registry import (supported_platform_ids,supported_platform_set,)+from core.agent_core.messages import HOSTED_TOOLSfrom modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, AgentBackend, DEFAULT_AGENT_BACKENDfrom modules.im.base import BaseIMConfigfrom vibe.i18n import normalize_language@@ -3011,6 +3012,70 @@ class ModelHubAgentSupplyConfig:return payload+# The hosted-tool catalog names are owned by the C-1 contract.+MODEL_HUB_HOSTED_TOOLS: tuple[str, ...] = HOSTED_TOOLS+++@dataclass(frozen=True)+class ModelHubHostedToolConfig:+ """One hosted tool's user toggle (``vibey-hosted-tools.md`` §3.3).++ ``executor`` is the proxy executor the user chose, or None to let hop+ resolution pick the first verified candidate.+ """++ enabled: bool = False+ executor: Optional[ModelHubRouteHopConfig] = None++ @classmethod+ def from_payload(cls, payload: object, *, tool: str) -> "ModelHubHostedToolConfig":+ if not isinstance(payload, dict) or set(payload) != {"enabled", "executor"}:+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must contain enabled and executor")+ if not isinstance(payload["enabled"], bool):+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")+ executor = payload["executor"]+ return cls(+ enabled=payload["enabled"],+ executor=None if executor is None else ModelHubRouteHopConfig.from_payload(executor),+ )++ def to_payload(self) -> dict:+ return {"enabled": self.enabled, "executor": None if self.executor is None else self.executor.to_payload()}+++def _hosted_tools_from_payload(+ payload: object,+ sources: list["ModelHubSourceConfig"],+) -> dict[str, ModelHubHostedToolConfig]:+ """Read ``model_hub.hosted_tools`` as an optional feature that degrades on its own.++ Absent means every tool is off. A malformed section or entry turns off only+ what it describes, with a warning; Sources and Agents still load. An+ executor whose Source or model no longer exists reads as None.+ """++ if payload is None:+ return {}+ if not isinstance(payload, dict):+ logger.warning("Config 'model_hub.hosted_tools' is not an object; hosted tools are off")+ return {}+ models = {source.id: {model.id for model in source.models} for source in sources}+ tools: dict[str, ModelHubHostedToolConfig] = {}+ for tool, raw in payload.items():+ if tool not in MODEL_HUB_HOSTED_TOOLS:+ logger.warning("Config 'model_hub.hosted_tools' has an unknown tool %r; it is off", tool)+ continue+ try:+ entry = ModelHubHostedToolConfig.from_payload(raw, tool=tool)+ except ValueError as exc:+ logger.warning("%s; hosted tool %r is off", exc, tool)+ continue+ if entry.executor is not None and entry.executor.model_id not in models.get(entry.executor.source_id, ()):+ entry = ModelHubHostedToolConfig(enabled=entry.enabled, executor=None)+ tools[tool] = entry+ return tools++@dataclassclass ModelHubConfig:# New installations enable the runtime. Disk loading promotes pre-marker@@ -3028,6 +3093,8 @@ class ModelHubConfig:# retain a pending false marker until lock-owning startup commits promotion;# an unrelated save must not acknowledge an upgrade it did not perform.runtime_default_applied: bool = True+ # Absent on every released config: absence means every hosted tool is off.+ hosted_tools: dict[str, ModelHubHostedToolConfig] = field(default_factory=dict)# Not persisted, like ``V2Config.load_warnings``. True while the Vibey# entry was never supplied: a fresh install, or a file written before# Vibey existed. The empty entry standing in waits for its starting@@ -3081,7 +3148,7 @@ class ModelHubConfig:def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub' must be an object")- if set(payload) - {"enabled", "sources", "agents", "runtime_default_applied"}:+ if set(payload) - {"enabled", "sources", "agents", "runtime_default_applied", "hosted_tools"}:raise ValueError("Config 'model_hub' contains unknown fields")enabled = payload.get("enabled", True)if not isinstance(enabled, bool):@@ -3148,6 +3215,7 @@ class ModelHubConfig:sources=sources,agents=agents,runtime_default_applied=runtime_default_applied,+ hosted_tools=_hosted_tools_from_payload(payload.get("hosted_tools"), sources),)agents = config.agentsfor backend in MODEL_HUB_BACKENDS:@@ -3186,7 +3254,7 @@ class ModelHubConfig:unseeded = self.vibey_supply_pending and self.agents["vibey"] == ModelHubAgentSupplyConfig.default("vibey", mode="hub")- return {+ payload = {"enabled": self.enabled,"runtime_default_applied": self.runtime_default_applied,"sources": [source.to_payload() for source in self.sources],@@ -3196,6 +3264,13 @@ class ModelHubConfig:if not (backend == "vibey" and unseeded)},}+ if self.hosted_tools:+ payload["hosted_tools"] = {+ tool: self.hosted_tools[tool].to_payload()+ for tool in MODEL_HUB_HOSTED_TOOLS+ if tool in self.hosted_tools+ }+ return payload@dataclassdiff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex fa397c9b8..924d77ccd 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -49,9 +49,31 @@ from core.agent_core.ai.provider import (ToolCallStart,)++@dataclass(frozen=True)+class ServedHop:+ """The C-6 served-hop report: the message origin and the serving Source."""++ origin: Origin+ source_id: str+++@dataclass(frozen=True)+class ServedResolution:+ """The response origin, whether its signature data is verified, and its Source.++ ``source_id`` is ``None`` in direct mode and for a missing or invalid report.+ """++ origin: Origin+ verified: bool+ source_id: str | None++ServedHopResolver = Callable[- [Mapping[str, str]], Origin | None | Awaitable[Origin | None]+ [Mapping[str, str]], ServedHop | None | Awaitable[ServedHop | None]]+_SOURCE_ID = re.compile(r"src_[a-z0-9]{8,}")_T = TypeVar("_T")WireTranslator = Callable[[AsyncIterator[SSEEvent]], AsyncIterator[Any]]@@ -1305,12 +1327,12 @@ async def resolve_served_origin(*,gateway: bool,cancel: CancelToken,-) -> tuple[Origin, bool] | None:- """Return the served origin and whether its signature data is verified."""+) -> ServedResolution | None:+ """Return the served origin, whether its signature data is verified, and its Source."""direct = endpoint_origin(endpoint)if not gateway:- return direct, True+ return ServedResolution(direct, True, None)candidate = resolver(headers) if resolver is not None else default_served_hop_resolver(headers)if inspect.isawaitable(candidate):try:@@ -1321,10 +1343,12 @@ async def resolve_served_origin(served = candidateif cancel.cancelled:return None- return served or direct, served is not None+ if served is None:+ return ServedResolution(direct, False, None)+ return ServedResolution(served.origin, True, served.source_id)-def default_served_hop_resolver(headers: Mapping[str, str]) -> Origin | None:+def default_served_hop_resolver(headers: Mapping[str, str]) -> ServedHop | None:"""Read the exact C-6 served-hop header."""normalized = {key.lower(): value for key, value in headers.items()}@@ -1337,12 +1361,15 @@ def default_served_hop_resolver(headers: Mapping[str, str]) -> Origin | None:return Noneif not isinstance(value, Mapping):return None- if set(value) != {"provider", "api", "model"} or any(not isinstance(value[key], str) for key in value):+ if set(value) != {"provider", "api", "model", "source"} or any(not isinstance(value[key], str) for key in value):+ return None+ if not _SOURCE_ID.fullmatch(value["source"]):return Nonetry:- return Origin(provider=value["provider"], api=value["api"], model=value["model"])+ origin = Origin(provider=value["provider"], api=value["api"], model=value["model"])except (KeyError, TypeError, ValueError):return None+ return ServedHop(origin=origin, source_id=value["source"])def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:@@ -1495,7 +1522,7 @@ async def drive_sse_stream(if resolved_origin is None:candidate = assembler.aborted(cancel.reason)else:- assembler.set_origin(*resolved_origin)+ assembler.set_origin(resolved_origin.origin, resolved_origin.verified)async for item in translate(iter_sse_events(response, cancel)):if isinstance(item, (Done, ProviderError)):candidate = itemdiff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex b82413448..e3ffaca5a 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -22,6 +22,16 @@ STOP_REASONS: tuple[str, ...] = ("stop", "length", "tool_use", "refusal", "safetIMAGE_MIME_TYPES: tuple[str, ...] = ("image/png", "image/jpeg", "image/gif", "image/webp")_LARGE_REF_RE = re.compile(r"^sha256:[0-9a-f]{64}$")+_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")+_COUNTER_NAME_RE = re.compile(r"^[a-z0-9_]{1,64}$")++HostedToolName = Literal["web_search", "x_search", "image_generation"]+HOSTED_TOOLS: tuple[str, ...] = ("web_search", "x_search", "image_generation")+HostedStatus = Literal["completed", "failed", "incomplete", "pending"]+HOSTED_STATUSES: tuple[str, ...] = ("completed", "failed", "incomplete", "pending")+HOSTED_ERROR_MAX_CHARS = 400+COST_BASES: tuple[str, ...] = ("reported", "list", "included")+SOURCE_BILLINGS: tuple[str, ...] = ("monthly", "metered")def _require(value: Any, kind: type, what: str, *, optional: bool = False) -> None:@@ -47,16 +57,59 @@ class LargeRef:raise ValueError(f"invalid large-content reference: {self.ref!r}")+def _require_text(value: Any, what: str, *, optional: bool = False) -> None:+ _require(value, str, what, optional=optional)+ if value is not None and not value:+ raise ValueError(f"{what} must not be empty")+++@dataclass(frozen=True)+class Citation:+ """A source the provider attached to assistant text; presentation only, never replayed.++ ``start`` and ``end`` come together, as a half-open code-point range into the block's text.+ """++ url: str+ title: Optional[str] = None+ cited_text: Optional[str] = None+ start: Optional[int] = None+ end: Optional[int] = None++ def __post_init__(self) -> None:+ _require_text(self.url, "citation url")+ _require(self.title, str, "citation title", optional=True)+ _require(self.cited_text, str, "cited_text", optional=True)+ _require(self.start, int, "citation start", optional=True)+ _require(self.end, int, "citation end", optional=True)+ if (self.start is None) != (self.end is None):+ raise ValueError("a citation range needs both start and end")+ if self.start is not None and not 0 <= self.start <= self.end:+ raise ValueError("a citation range must satisfy 0 <= start <= end")++@dataclass(frozen=True)class TextBlock:text: Optional[str] = Noneref: Optional[LargeRef] = None+ citations: Optional[tuple[Citation, ...]] = None+ """Assistant text only, and only with inline ``text``; absent when the provider attached none."""def __post_init__(self) -> None:_require(self.text, str, "text", optional=True)_require(self.ref, LargeRef, "ref", optional=True)if (self.text is None) == (self.ref is None):raise ValueError("a text block holds exactly one of text or ref")+ if self.citations is None:+ return+ if not isinstance(self.citations, tuple) or not self.citations:+ raise ValueError("citations, when present, are a non-empty tuple")+ if not all(isinstance(citation, Citation) for citation in self.citations):+ raise ValueError("citations must be Citation values")+ if self.text is None:+ raise ValueError("citations index into inline text")+ if any(c.end is not None and c.end > len(self.text) for c in self.citations):+ raise ValueError("a citation range must lie within the text")@dataclass(frozen=True)@@ -150,8 +203,283 @@ def _require_blocks(content: Any, allowed: tuple[type, ...], what: str) -> None:raise ValueError(f"{what} content must be a tuple of {', '.join(k.__name__ for k in allowed)}")+def _refuse_citations(content: tuple[Any, ...], what: str) -> None:+ if any(isinstance(block, TextBlock) and block.citations is not None for block in content):+ raise ValueError(f"{what} text carries no citations")+++# --- hosted tools (``vibey-hosted-tools.md`` §4.2) ----------------------------+#+# A native hosted call is one ``HostedToolBlock`` in assistant content. A proxied+# call is an ordinary ``ToolCallBlock`` whose ``ToolResultMessage`` carries+# ``hosted``. Neither ever holds image bytes: a generated image is a file, and+# the record holds its path.++# Per action type: (owning tool or None for any hosted tool, required fields, optional fields).+_HOSTED_ACTIONS: dict[str, tuple[Optional[str], dict[str, type], dict[str, type]]] = {+ "search": ("web_search", {"queries": list}, {}),+ "open_page": ("web_search", {"url": str}, {}),+ "find_in_page": ("web_search", {"url": str, "pattern": str}, {}),+ "x_search": ("x_search", {"variant": str, "query": str}, {"limit": int, "mode": str}),+ "x_user_search": ("x_search", {"query": str}, {}),+ "x_thread_fetch": ("x_search", {"ref": str}, {}),+ "generate": ("image_generation", {}, {"prompt": str, "size": str, "quality": str}),+ "other": (None, {"name": str}, {}),+}+_X_SEARCH_VARIANTS = ("keyword", "semantic")+_X_SEARCH_MODES = ("Latest", "Top")+++@dataclass(frozen=True)+class HostedAction:+ """What a hosted call did, provider-neutral. Only the fields of its ``type`` are set."""++ type: str+ queries: Optional[tuple[str, ...]] = None+ url: Optional[str] = None+ pattern: Optional[str] = None+ variant: Optional[str] = None+ query: Optional[str] = None+ limit: Optional[int] = None+ mode: Optional[str] = None+ ref: Optional[str] = None+ prompt: Optional[str] = None+ size: Optional[str] = None+ quality: Optional[str] = None+ name: Optional[str] = None++ def __post_init__(self) -> None:+ _require(self.type, str, "hosted action type")+ if self.type not in _HOSTED_ACTIONS:+ raise ValueError(f"unknown hosted action type: {self.type}")+ _, required, optional = _HOSTED_ACTIONS[self.type]+ for name in _HOSTED_ACTION_FIELDS:+ value = getattr(self, name)+ if name in required and value is None:+ raise ValueError(f"a {self.type} action needs {name}")+ if name not in required and name not in optional and value is not None:+ raise ValueError(f"a {self.type} action has no {name}")+ if self.queries is not None:+ if not isinstance(self.queries, tuple) or not self.queries:+ raise ValueError("search queries are a non-empty tuple")+ for query in self.queries:+ _require_text(query, "search query")+ for name in ("url", "pattern", "query", "ref", "prompt", "size", "quality", "name"):+ _require_text(getattr(self, name), f"action {name}", optional=True)+ _require(self.variant, str, "action variant", optional=True)+ if self.variant is not None and self.variant not in _X_SEARCH_VARIANTS:+ raise ValueError(f"unknown x_search variant: {self.variant}")+ _require(self.mode, str, "action mode", optional=True)+ if self.mode is not None and self.mode not in _X_SEARCH_MODES:+ raise ValueError(f"unknown x_search mode: {self.mode}")+ _require(self.limit, int, "action limit", optional=True)+ if self.limit is not None and self.limit < 1:+ raise ValueError("an x_search limit is at least 1")++ def fits(self, tool: str) -> bool:+ owner = _HOSTED_ACTIONS[self.type][0]+ return owner is None or owner == tool+++_HOSTED_ACTION_FIELDS: tuple[str, ...] = (+ "queries", "url", "pattern", "variant", "query", "limit", "mode", "ref", "prompt", "size", "quality", "name",+)+++@dataclass(frozen=True)+class HostedSource:+ url: str+ title: Optional[str] = None+ snippet: Optional[str] = None+ page_age: Optional[str] = None++ def __post_init__(self) -> None:+ _require_text(self.url, "source url")+ for name in ("title", "snippet", "page_age"):+ _require(getattr(self, name), str, f"source {name}", optional=True)+++@dataclass(frozen=True)+class HostedImage:+ """A generated image saved as a local file; the model sees only this record."""++ path: str+ mime: str+ width: Optional[int] = None+ height: Optional[int] = None++ def __post_init__(self) -> None:+ _require_text(self.path, "image path")+ _require(self.mime, str, "image mime")+ if self.mime not in IMAGE_MIME_TYPES:+ raise ValueError(f"unsupported image type: {self.mime}")+ for name in ("width", "height"):+ value = getattr(self, name)+ _require(value, int, f"image {name}", optional=True)+ if value is not None and value < 1:+ raise ValueError(f"image {name} is at least 1")+++@dataclass(frozen=True)+class HostedRecord:+ """Per-call facts. ``images`` is set exactly for ``image_generation`` (possibly empty)."""++ status: HostedStatus+ error: Optional[str] = None+ sources: tuple[HostedSource, ...] = ()+ images: Optional[tuple[HostedImage, ...]] = None++ def __post_init__(self) -> None:+ _require(self.status, str, "hosted status")+ if self.status not in HOSTED_STATUSES:+ raise ValueError(f"unknown hosted status: {self.status}")+ _require_text(self.error, "hosted error", optional=True)+ if (self.error is not None) != (self.status in ("failed", "incomplete")):+ raise ValueError("a hosted error is present exactly for failed and incomplete records")+ if self.error is not None and len(self.error) > HOSTED_ERROR_MAX_CHARS:+ raise ValueError(f"a hosted error is at most {HOSTED_ERROR_MAX_CHARS} characters")+ if not isinstance(self.sources, tuple) or not all(isinstance(s, HostedSource) for s in self.sources):+ raise ValueError("hosted sources must be a tuple of HostedSource")+ if self.images is not None and (+ not isinstance(self.images, tuple) or not all(isinstance(i, HostedImage) for i in self.images)+ ):+ raise ValueError("hosted images must be a tuple of HostedImage")++ def check_tool(self, tool: str) -> None:+ if (self.images is not None) != (tool == "image_generation"):+ raise ValueError("a hosted record lists images exactly for image_generation")+++@dataclass(frozen=True)+class HostedNative:+ """The provider's own items for one call, verbatim and in order; their origin is the message's."""++ source_id: str+ payload: tuple[dict[str, Any], ...]++ def __post_init__(self) -> None:+ _require(self.source_id, str, "native source_id")+ if not _SOURCE_ID_RE.fullmatch(self.source_id):+ raise ValueError(f"invalid source id: {self.source_id!r}")+ if not isinstance(self.payload, tuple) or not self.payload:+ raise ValueError("a native payload is a non-empty tuple of provider items")+ for index, item in enumerate(self.payload):+ _require(item, dict, f"native payload[{index}]")+ require_json_value(item, f"native payload[{index}]")+ object.__setattr__(self, "payload", copy.deepcopy(self.payload))+++@dataclass(frozen=True)+class HostedToolBlock:+ id: str+ tool: HostedToolName+ action: HostedAction+ record: HostedRecord+ native: HostedNative++ def __post_init__(self) -> None:+ _require_text(self.id, "hosted call id")+ _require(self.tool, str, "hosted tool")+ if self.tool not in HOSTED_TOOLS:+ raise ValueError(f"unknown hosted tool: {self.tool}")+ _require(self.action, HostedAction, "hosted action")+ _require(self.record, HostedRecord, "hosted record")+ _require(self.native, HostedNative, "native payload")+ if not self.action.fits(self.tool):+ raise ValueError(f"a {self.action.type} action does not belong to {self.tool}")+ self.record.check_tool(self.tool)+ if self.action.type == "generate" and self.record.status == "completed" and self.action.prompt is None:+ raise ValueError("a completed generate action needs its prompt")+++@dataclass(frozen=True)+class HostedCost:+ """Money for one response, from the pricing module or the provider; ``usd`` is absent exactly when included."""++ basis: str+ usd: Optional[float] = None++ def __post_init__(self) -> None:+ _require(self.basis, str, "cost basis")+ if self.basis not in COST_BASES:+ raise ValueError(f"unknown cost basis: {self.basis}")+ if self.usd is not None and (isinstance(self.usd, bool) or not isinstance(self.usd, (int, float))):+ raise ValueError("cost usd must be a number")+ if (self.usd is None) != (self.basis == "included"):+ raise ValueError("cost usd is present exactly when the basis is not included")+ if self.usd is not None:+ require_json_value(self.usd, "cost usd")+ if self.usd < 0:+ raise ValueError("cost usd must not be negative")+++@dataclass(frozen=True)+class HostedSummary:+ """Response-scoped hosted facts, present exactly when the message has a ``HostedToolBlock``.++ ``cost`` is absent when no price is known: unknown is never priced as zero.+ """++ counts: Mapping[str, int] = field(default_factory=dict)+ cited_sources: tuple[HostedSource, ...] = ()+ cost: Optional[HostedCost] = None++ def __post_init__(self) -> None:+ _require(self.counts, dict, "hosted counts")+ for name, value in self.counts.items():+ if not isinstance(name, str) or not _COUNTER_NAME_RE.fullmatch(name):+ raise ValueError(f"invalid hosted counter name: {name!r}")+ _require(value, int, f"hosted count {name}")+ if value < 0:+ raise ValueError("hosted counts must not be negative")+ object.__setattr__(self, "counts", dict(self.counts))+ if not isinstance(self.cited_sources, tuple) or not all(+ isinstance(s, HostedSource) for s in self.cited_sources+ ):+ raise ValueError("cited sources must be a tuple of HostedSource")+ _require(self.cost, HostedCost, "hosted cost", optional=True)+++@dataclass(frozen=True)+class ProxyExecution:+ """Which executor ran a proxied hosted call; absent when the call never reached one."""++ executor_origin: Origin+ executor_source_id: str+ executor_billing: str+ cost: Optional[HostedCost] = None++ @property+ def mode(self) -> Literal["proxy"]:+ return "proxy"++ def __post_init__(self) -> None:+ _require(self.executor_origin, Origin, "executor origin")+ _require(self.executor_source_id, str, "executor source id")+ if not _SOURCE_ID_RE.fullmatch(self.executor_source_id):+ raise ValueError(f"invalid source id: {self.executor_source_id!r}")+ _require(self.executor_billing, str, "executor billing")+ if self.executor_billing not in SOURCE_BILLINGS:+ raise ValueError(f"unknown billing: {self.executor_billing}")+ _require(self.cost, HostedCost, "executor cost", optional=True)+++@dataclass(frozen=True)+class HostedResult:+ """``ToolResultMessage.hosted``: the canonical record of a proxied hosted call."""++ record: HostedRecord+ execution: Optional[ProxyExecution] = None++ def __post_init__(self) -> None:+ _require(self.record, HostedRecord, "hosted record")+ _require(self.execution, ProxyExecution, "proxy execution", optional=True)+ if self.execution is None and self.record.status != "failed":+ raise ValueError("a hosted result without an execution is a failed record")++UserContent = Union[TextBlock, ImageBlock]-AssistantContent = Union[TextBlock, ThinkingBlock, ToolCallBlock]+AssistantContent = Union[TextBlock, ThinkingBlock, ToolCallBlock, HostedToolBlock]@dataclass(frozen=True)@@ -194,6 +522,7 @@ class UserMessage:def __post_init__(self) -> None:_require_blocks(self.content, (TextBlock, ImageBlock), "user message")+ _refuse_citations(self.content, "user message")if not self.content:raise ValueError("a user message needs content")@@ -209,13 +538,18 @@ class AssistantMessage:stop_reason: StopReasonusage: Optional[Usage] = Noneerror_message: Optional[str] = None+ hosted_summary: Optional[HostedSummary] = Nonedef __post_init__(self) -> None:- _require_blocks(self.content, (TextBlock, ThinkingBlock, ToolCallBlock), "assistant message")+ _require_blocks(self.content, (TextBlock, ThinkingBlock, ToolCallBlock, HostedToolBlock), "assistant message")_require(self.origin, Origin, "origin")_require(self.stop_reason, str, "stop_reason")_require(self.usage, Usage, "usage", optional=True)_require(self.error_message, str, "error_message", optional=True)+ _require(self.hosted_summary, HostedSummary, "hosted_summary", optional=True)+ hosted = any(isinstance(block, HostedToolBlock) for block in self.content)+ if hosted != (self.hosted_summary is not None):+ raise ValueError("a hosted summary is present exactly when the message has hosted tool blocks")if self.error_message is not None and not self.error_message:raise ValueError("an error message, when present, must not be empty")if self.stop_reason not in STOP_REASONS:@@ -236,14 +570,24 @@ class ToolResultMessage:tool_name: strcontent: tuple[UserContent, ...]is_error: bool = False+ hosted: Optional[HostedResult] = None+ """Set only on the result of a proxied hosted tool call."""def __post_init__(self) -> None:_require(self.tool_call_id, str, "tool_call_id")_require(self.tool_name, str, "tool_name")_require_blocks(self.content, (TextBlock, ImageBlock), "tool result")+ _refuse_citations(self.content, "tool result")_require(self.is_error, bool, "is_error")+ _require(self.hosted, HostedResult, "hosted", optional=True)if not self.tool_call_id or not self.tool_name:raise ValueError("a tool result needs its call id and tool name")+ if self.hosted is not None:+ if self.tool_name not in HOSTED_TOOLS:+ raise ValueError(f"{self.tool_name} is not a hosted tool")+ self.hosted.record.check_tool(self.tool_name)+ if self.is_error != (self.hosted.record.status in ("failed", "incomplete")):+ raise ValueError("a hosted result is an error exactly when its record failed or is incomplete")@propertydef role(self) -> Literal["tool_result"]:@@ -293,11 +637,94 @@ def _put(out: dict[str, Any], name: str, value: Any) -> None:out[name] = value+def _source_to_dict(source: HostedSource) -> dict[str, Any]:+ out: dict[str, Any] = {"url": source.url}+ for name in ("title", "snippet", "page_age"):+ _put(out, name, getattr(source, name))+ return out+++def _source_from_dict(data: Any) -> HostedSource:+ return HostedSource(**_read(data, "hosted source", {"url": str}, {"title": str, "snippet": str, "page_age": str}))+++def _record_to_dict(record: HostedRecord) -> dict[str, Any]:+ out: dict[str, Any] = {"status": record.status}+ _put(out, "error", record.error)+ out["sources"] = [_source_to_dict(source) for source in record.sources]+ if record.images is not None:+ images = []+ for image in record.images:+ item: dict[str, Any] = {"path": image.path, "mime": image.mime}+ _put(item, "width", image.width)+ _put(item, "height", image.height)+ images.append(item)+ out["images"] = images+ return out+++def _record_from_dict(data: Any) -> HostedRecord:+ f = _read(data, "hosted record", {"status": str, "sources": list}, {"error": str, "images": list})+ images = None+ if "images" in f:+ images = tuple(+ HostedImage(**_read(item, "hosted image", {"path": str, "mime": str}, {"width": int, "height": int}))+ for item in f["images"]+ )+ return HostedRecord(+ status=f["status"],+ error=f.get("error"),+ sources=tuple(_source_from_dict(source) for source in f["sources"]),+ images=images,+ )+++def _action_to_dict(action: HostedAction) -> dict[str, Any]:+ out: dict[str, Any] = {"type": action.type}+ for name in _HOSTED_ACTION_FIELDS:+ value = getattr(action, name)+ _put(out, name, list(value) if isinstance(value, tuple) else value)+ return out+++def _action_from_dict(data: Any) -> HostedAction:+ kind = data.get("type") if isinstance(data, Mapping) else None+ if kind not in _HOSTED_ACTIONS:+ raise ValueError(f"unknown hosted action type: {kind!r}")+ _, required, optional = _HOSTED_ACTIONS[kind]+ f = _read(data, f"{kind} action", {"type": str, **required}, optional)+ if "queries" in f:+ f["queries"] = tuple(f["queries"])+ return HostedAction(**f)+++def _cost_to_dict(cost: HostedCost) -> dict[str, Any]:+ out: dict[str, Any] = {"basis": cost.basis}+ _put(out, "usd", cost.usd)+ return out+++def _cost_from_dict(data: Any) -> HostedCost:+ if isinstance(data, Mapping) and isinstance(data.get("usd"), int) and not isinstance(data.get("usd"), bool):+ data = {**data, "usd": float(data["usd"])}+ return HostedCost(**_read(data, "hosted cost", {"basis": str}, {"usd": float}))+++def _citation_to_dict(citation: Citation) -> dict[str, Any]:+ out: dict[str, Any] = {"url": citation.url}+ for name in ("title", "cited_text", "start", "end"):+ _put(out, name, getattr(citation, name))+ return out++def _block_to_dict(block: Any) -> dict[str, Any]:if isinstance(block, TextBlock):if block.ref is not None:return {"type": "text", "ref": {"ref": block.ref.ref, "bytes": block.ref.bytes}}- return {"type": "text", "text": block.text}+ out: dict[str, Any] = {"type": "text", "text": block.text}+ if block.citations is not None:+ out["citations"] = [_citation_to_dict(citation) for citation in block.citations]+ return outif isinstance(block, ImageBlock):out: dict[str, Any] = {"type": "image", "mime_type": block.mime_type, "media_token": block.media_token}_put(out, "name", block.name)@@ -315,6 +742,15 @@ def _block_to_dict(block: Any) -> dict[str, Any]:_put(out, "native_id", block.native_id)_put(out, "signature", block.signature)return out+ if isinstance(block, HostedToolBlock):+ return {+ "type": "hosted_tool",+ "id": block.id,+ "tool": block.tool,+ "action": _action_to_dict(block.action),+ "record": _record_to_dict(block.record),+ "native": {"source_id": block.native.source_id, "payload": copy.deepcopy(list(block.native.payload))},+ }raise TypeError(f"not a content block: {type(block).__name__}")@@ -323,12 +759,34 @@ def _block_from_dict(data: Any, allowed_types: tuple[str, ...]) -> Any:if kind not in allowed_types:raise ValueError(f"block type {kind!r} is not allowed here")if kind == "text":- f = _read(data, "text block", {"type": str}, {"text": str, "ref": dict})+ f = _read(data, "text block", {"type": str}, {"text": str, "ref": dict, "citations": list})ref = Noneif "ref" in f:r = _read(f["ref"], "large-content reference", {"ref": str, "bytes": int})ref = LargeRef(ref=r["ref"], bytes=r["bytes"])- return TextBlock(text=f.get("text"), ref=ref)+ citations = None+ if "citations" in f:+ citations = tuple(+ Citation(+ **_read(item, "citation", {"url": str}, {"title": str, "cited_text": str, "start": int, "end": int})+ )+ for item in f["citations"]+ )+ return TextBlock(text=f.get("text"), ref=ref, citations=citations)+ if kind == "hosted_tool":+ f = _read(+ data,+ "hosted tool block",+ {"type": str, "id": str, "tool": str, "action": dict, "record": dict, "native": dict},+ )+ native = _read(f["native"], "native payload", {"source_id": str, "payload": list})+ return HostedToolBlock(+ id=f["id"],+ tool=f["tool"],+ action=_action_from_dict(f["action"]),+ record=_record_from_dict(f["record"]),+ native=HostedNative(source_id=native["source_id"], payload=tuple(native["payload"])),+ )if kind == "image":f = _read(data, "image block", {"type": str, "mime_type": str, "media_token": str}, {"name": str})return ImageBlock(mime_type=f["mime_type"], media_token=f["media_token"], name=f.get("name"))@@ -378,15 +836,42 @@ def message_to_dict(message: Message) -> dict[str, Any]:if message.usage is not None:out["usage"] = usage_to_dict(message.usage)_put(out, "error_message", message.error_message)+ if message.hosted_summary is not None:+ summary = message.hosted_summary+ hosted: dict[str, Any] = {+ "counts": dict(summary.counts),+ "cited_sources": [_source_to_dict(source) for source in summary.cited_sources],+ }+ if summary.cost is not None:+ hosted["cost"] = _cost_to_dict(summary.cost)+ out["hosted_summary"] = hostedreturn outif isinstance(message, ToolResultMessage):- return {+ result: dict[str, Any] = {"role": "tool_result","tool_call_id": message.tool_call_id,"tool_name": message.tool_name,"content": [_block_to_dict(b) for b in message.content],"is_error": message.is_error,}+ if message.hosted is not None:+ hosted_result: dict[str, Any] = {"record": _record_to_dict(message.hosted.record)}+ execution = message.hosted.execution+ if execution is not None:+ hosted_result["execution"] = {+ "mode": execution.mode,+ "executor_origin": {+ "provider": execution.executor_origin.provider,+ "api": execution.executor_origin.api,+ "model": execution.executor_origin.model,+ },+ "executor_source_id": execution.executor_source_id,+ "executor_billing": execution.executor_billing,+ }+ if execution.cost is not None:+ hosted_result["execution"]["cost"] = _cost_to_dict(execution.cost)+ result["hosted"] = hosted_result+ return resultraise TypeError(f"not a message: {type(message).__name__}")@@ -400,25 +885,61 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:data,"assistant message",{"role": str, "content": list, "origin": dict, "stop_reason": str},- {"usage": dict, "error_message": str},+ {"usage": dict, "error_message": str, "hosted_summary": dict},)+ summary = None+ if "hosted_summary" in f:+ h = _read(f["hosted_summary"], "hosted summary", {"counts": dict, "cited_sources": list}, {"cost": dict})+ summary = HostedSummary(+ counts=dict(h["counts"]),+ cited_sources=tuple(_source_from_dict(source) for source in h["cited_sources"]),+ cost=_cost_from_dict(h["cost"]) if "cost" in h else None,+ )return AssistantMessage(- content=tuple(_block_from_dict(b, ("text", "thinking", "tool_call")) for b in f["content"]),+ content=tuple(_block_from_dict(b, ("text", "thinking", "tool_call", "hosted_tool")) for b in f["content"]),origin=origin_from_dict(f["origin"]),stop_reason=f["stop_reason"],usage=usage_from_dict(f["usage"]) if "usage" in f else None,error_message=f.get("error_message"),+ hosted_summary=summary,)if role == "tool_result":f = _read(data,"tool result message",{"role": str, "tool_call_id": str, "tool_name": str, "content": list, "is_error": bool},+ {"hosted": dict},)+ hosted_result = None+ if "hosted" in f:+ h = _read(f["hosted"], "hosted result", {"record": dict}, {"execution": dict})+ execution = None+ if "execution" in h:+ e = _read(+ h["execution"],+ "proxy execution",+ {+ "mode": str,+ "executor_origin": dict,+ "executor_source_id": str,+ "executor_billing": str,+ },+ {"cost": dict},+ )+ if e["mode"] != "proxy":+ raise ValueError("proxy execution.mode must be proxy")+ execution = ProxyExecution(+ executor_origin=origin_from_dict(e["executor_origin"]),+ executor_source_id=e["executor_source_id"],+ executor_billing=e["executor_billing"],+ cost=_cost_from_dict(e["cost"]) if "cost" in e else None,+ )+ hosted_result = HostedResult(record=_record_from_dict(h["record"]), execution=execution)return ToolResultMessage(tool_call_id=f["tool_call_id"],tool_name=f["tool_name"],content=tuple(_block_from_dict(b, ("text", "image")) for b in f["content"]),is_error=f["is_error"],+ hosted=hosted_result,)raise ValueError(f"unknown message role: {role!r}")diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 35e57a833..7550be7e6 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -1,4 +1,4 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v11 (2026-10-02).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v12 (2026-10-13).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:diff --git a/core/handlers/model_hub/capability_evidence.py b/core/handlers/model_hub/capability_evidence.pynew file mode 100644index 000000000..284234527--- /dev/null+++ b/core/handlers/model_hub/capability_evidence.py@@ -0,0 +1,286 @@+"""Per-Source capability evidence (``model-hub-capability-model.md`` §3).++One record per (Source, model, feature). Absence of a record is ``unknown``,+and unknown is never negative (#2505): only explicit negative evidence excludes,+and only positive evidence enables a feature whose failure is terminal or+silent (a native hosted tool).++Two writers exist, and only they write here: a probe the user started, and the+gateway classifier's narrow rules on a real upstream error. This module owns+the persisted shape, its expiry and staleness, and how a record resolves for+routing. It decides nothing about requests itself.++Records follow Source identity: each one stores a digest of+``retry.source_identity`` at the time it was written, and a record whose+Source identity has since changed reads as absent and is pruned at the next+write.+"""++from __future__ import annotations++import hashlib+import json+import re+import threading+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Iterable, Literal, Mapping, Optional++from config.v2_config import ModelHubSourceConfig++from .retry import source_identity+from .state_file import write_state_document++EVIDENCE_VERSION = 1+MAX_RECORDS = 4000+OBSERVED_TTL_SECONDS = 7 * 24 * 3600+PROBE_REVERIFY_AFTER_SECONDS = 30 * 24 * 3600+DETAIL_MAX_CHARS = 64++FeatureKind = Literal["effort", "hosted_tool"]+EvidenceStatus = Literal["verified", "unsupported"]+EvidenceBasis = Literal["probe", "observed"]+RoutingStatus = Literal["verified", "unsupported", "unknown"]+Staleness = Literal["wire", "age"]++HOSTED_TOOL_ASPECTS: Mapping[str, tuple[str, ...]] = {+ "web_search": ("call", "replay"),+ "x_search": ("call", "replay"),+ # A generated image is never replayed verbatim, so only its call is evidence.+ "image_generation": ("call",),+}+_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")+++@dataclass(frozen=True)+class EvidenceFeature:+ kind: FeatureKind+ name: str+ aspect: Optional[Literal["call", "replay"]] = None++ def __post_init__(self) -> None:+ if self.kind == "effort":+ if not isinstance(self.name, str) or not _NAME_RE.fullmatch(self.name) or self.aspect is not None:+ raise ValueError("an effort feature is a name without an aspect")+ return+ if self.kind != "hosted_tool":+ raise ValueError(f"unknown evidence feature kind: {self.kind!r}")+ if self.name not in HOSTED_TOOL_ASPECTS or self.aspect not in HOSTED_TOOL_ASPECTS[self.name]:+ raise ValueError(f"unknown hosted-tool evidence: {self.name!r} {self.aspect!r}")++ @classmethod+ def effort(cls, name: str) -> "EvidenceFeature":+ return cls("effort", name)++ @classmethod+ def hosted(cls, tool: str, aspect: Literal["call", "replay"]) -> "EvidenceFeature":+ return cls("hosted_tool", tool, aspect)++ def payload(self) -> dict[str, str]:+ out = {"kind": self.kind, "name": self.name}+ if self.aspect is not None:+ out["aspect"] = self.aspect+ return out+++@dataclass(frozen=True)+class EvidenceRecord:+ source_id: str+ model_id: str+ feature: EvidenceFeature+ status: EvidenceStatus+ basis: EvidenceBasis+ observed_at: datetime+ engine: str+ shape: int+ source_identity: str+ detail: Optional[str] = None++ def __post_init__(self) -> None:+ for name in ("source_id", "model_id", "engine", "source_identity"):+ value = getattr(self, name)+ if not isinstance(value, str) or not value:+ raise ValueError(f"evidence {name} must be a non-empty string")+ if self.status not in ("verified", "unsupported") or self.basis not in ("probe", "observed"):+ raise ValueError("invalid evidence status or basis")+ if self.basis == "observed" and (self.status != "unsupported" or not self.detail):+ raise ValueError("observed evidence is always unsupported and carries its detail")+ if self.detail is not None and (not isinstance(self.detail, str) or not 0 < len(self.detail) <= DETAIL_MAX_CHARS):+ raise ValueError(f"evidence detail is at most {DETAIL_MAX_CHARS} characters")+ if isinstance(self.shape, bool) or not isinstance(self.shape, int) or self.shape < 0:+ raise ValueError("evidence shape is a non-negative integer")+ if self.observed_at.tzinfo is None:+ raise ValueError("evidence time must be timezone-aware")++ @property+ def key(self) -> tuple[str, str, str, str, str]:+ return (self.source_id, self.model_id, self.feature.kind, self.feature.name, self.feature.aspect or "")++ def payload(self) -> dict[str, Any]:+ out: dict[str, Any] = {+ "version": EVIDENCE_VERSION,+ "source_id": self.source_id,+ "model_id": self.model_id,+ "feature": self.feature.payload(),+ "status": self.status,+ "basis": self.basis,+ "observed_at": self.observed_at.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),+ "engine": self.engine,+ "shape": self.shape,+ "source_identity": self.source_identity,+ }+ if self.detail is not None:+ out["detail"] = self.detail+ return out++ @classmethod+ def from_payload(cls, payload: Any) -> "EvidenceRecord":+ if not isinstance(payload, Mapping) or payload.get("version") != EVIDENCE_VERSION:+ raise ValueError("unknown evidence record version")+ allowed = {+ "version", "source_id", "model_id", "feature", "status", "basis",+ "observed_at", "engine", "shape", "source_identity", "detail",+ }+ if set(payload) - allowed:+ raise ValueError("unknown evidence record field")+ feature = payload.get("feature")+ if not isinstance(feature, Mapping) or set(feature) - {"kind", "name", "aspect"}:+ raise ValueError("invalid evidence feature")+ observed_at = payload.get("observed_at")+ if not isinstance(observed_at, str) or not observed_at.endswith("Z"):+ raise ValueError("evidence time must be UTC")+ return cls(+ source_id=payload.get("source_id"),+ model_id=payload.get("model_id"),+ feature=EvidenceFeature(feature.get("kind"), feature.get("name"), feature.get("aspect")),+ status=payload.get("status"),+ basis=payload.get("basis"),+ observed_at=datetime.fromisoformat(observed_at[:-1] + "+00:00"),+ engine=payload.get("engine"),+ shape=payload.get("shape"),+ source_identity=payload.get("source_identity"),+ detail=payload.get("detail"),+ )+++@dataclass(frozen=True)+class EvidenceView:+ """How one record resolves now.++ ``status`` is what routing uses. ``stale`` asks for a re-verify: ``wire``+ when the record was taken on another engine or probe shape, ``age`` when it+ is merely old. ``record`` is kept for display even when it no longer routes.+ """++ status: RoutingStatus+ stale: Optional[Staleness] = None+ record: Optional[EvidenceRecord] = None+++UNKNOWN = EvidenceView("unknown")+++def identity_digest(source: ModelHubSourceConfig) -> str:+ """Stable, credential-free digest of the Source identity that evidence follows."""++ raw = json.dumps(list(source_identity(source)), ensure_ascii=False, separators=(",", ":"))+ return "sha256:" + hashlib.sha256(raw.encode("utf-8")).hexdigest()+++def resolve(+ record: Optional[EvidenceRecord],+ *,+ source: ModelHubSourceConfig,+ engine: str,+ shape: int,+ now: datetime,+) -> EvidenceView:+ """Resolve one record for routing (capability model §3.3, §3.4)."""++ if record is None or record.source_identity != identity_digest(source):+ return UNKNOWN+ age = (now - record.observed_at).total_seconds()+ if record.basis == "observed":+ # Relays change; an expired negative record falls back to the priors.+ return UNKNOWN if age > OBSERVED_TTL_SECONDS else EvidenceView("unsupported", None, record)+ wire_stale = record.engine != engine or record.shape != shape+ stale: Optional[Staleness] = "wire" if wire_stale else "age" if age > PROBE_REVERIFY_AFTER_SECONDS else None+ if record.feature.kind == "hosted_tool" and wire_stale:+ # Evidence taken on another wire cannot vouch for this one, and a silent+ # native drop would never trip a narrow rule: route as unknown (proxy).+ return EvidenceView("unknown", stale, record)+ return EvidenceView(record.status, stale, record)+++class CapabilityEvidenceStore:+ """The evidence records, held in memory and persisted on every write.++ Small: bounded by Sources x models x features. The controller is the only+ writer (probes and the classifier both run there; other processes reach it+ over RPC), so the file is read once and memory is authoritative afterwards.+ Lookups on the request path therefore never touch the disk.+ """++ def __init__(self, path: Path, *, max_records: int = MAX_RECORDS):+ self.path = path+ self.max_records = max_records+ self._lock = threading.RLock()+ self._records: dict[tuple, EvidenceRecord] | None = None++ def _loaded(self) -> dict[tuple, EvidenceRecord]:+ if self._records is None:+ try:+ payload = json.loads(self.path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ payload = []+ records: dict[tuple, EvidenceRecord] = {}+ for item in payload if isinstance(payload, list) else []:+ try:+ record = EvidenceRecord.from_payload(item)+ except (TypeError, ValueError):+ # An unreadable record is unknown, never negative.+ continue+ records[record.key] = record+ self._records = records+ return self._records++ def get(self, source_id: str, model_id: str, feature: EvidenceFeature) -> Optional[EvidenceRecord]:+ with self._lock:+ return self._loaded().get((source_id, model_id, feature.kind, feature.name, feature.aspect or ""))++ def view(+ self,+ source: ModelHubSourceConfig,+ model_id: str,+ feature: EvidenceFeature,+ *,+ engine: str,+ shape: int,+ now: datetime,+ ) -> EvidenceView:+ return resolve(self.get(source.id, model_id, feature), source=source, engine=engine, shape=shape, now=now)++ def records(self) -> list[EvidenceRecord]:+ with self._lock:+ return list(self._loaded().values())++ def write(self, record: EvidenceRecord, *, live: Iterable[ModelHubSourceConfig]) -> None:+ """Replace the record for its key; prune records of removed or re-identified Sources.++ Memory changes only once the file holds the new records.+ """++ identities = {source.id: identity_digest(source) for source in live}+ if identities.get(record.source_id) != record.source_identity:+ raise ValueError("evidence must be written for a live Source's current identity")+ with self._lock:+ records = {+ key: existing+ for key, existing in self._loaded().items()+ if identities.get(existing.source_id) == existing.source_identity+ }+ records[record.key] = record+ kept = sorted(records.values(), key=lambda item: item.observed_at)[-self.max_records :]+ write_state_document(self.path, [item.payload() for item in kept])+ self._records = {item.key: item for item in kept}diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.pynew file mode 100644index 000000000..9346b1a8c--- /dev/null+++ b/core/handlers/model_hub/hosted_tools.py@@ -0,0 +1,283 @@+"""Hosted-tool resolution for a Vibey hop (``vibey-hosted-tools.md`` §3.4, §3.5).++Model Hub resolves the capability layers once per launch, and Vibey only reads+the result in ``HopResolution.hosted_tools``. For every tool the user enabled+it states the primary hop's mode, the wire declaration when that mode is+native, the proxy executor bound for the turn, and whether a native payload+from this Source may be replayed to it.++Native needs all of: the toggle on, an eligible credential, an untranslated+path, the overlay's declaration for the hop's (vendor, protocol, model), and+positive ``call`` evidence taken on the current engine and probe shape. Anything+less is the lossless proxy.+"""++from __future__ import annotations++import json+import os+from dataclasses import dataclass+from datetime import datetime+from functools import lru_cache+from importlib import resources+from pathlib import Path+from typing import Any, Callable, Mapping, Optional++from config.v2_config import MODEL_HUB_HOSTED_TOOLS, ModelHubConfig, ModelHubHostedToolConfig, ModelHubSourceConfig+from vibe.backend_model_catalog import HostedToolSpec++from .capability_evidence import HOSTED_TOOL_ASPECTS, CapabilityEvidenceStore, EvidenceFeature++# The request shape a hosted-tool probe sends. Changing the probe or the native+# request it mirrors bumps this, which makes earlier probe evidence wire-stale.+HOSTED_PROBE_SHAPE = 1+++SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]+++def credential_eligible(source: ModelHubSourceConfig) -> bool:+ """Whether a Source may run hosted tools at all: natively, as executor, or for a probe.++ Anthropic restricts OAuth credentials to Claude Code and its own apps+ (``model-hub-tos-review.md``), so a Claude subscription never is.+ """++ return not (source.vendor == "anthropic" and source.kind == "subscription")+++def untranslated(source: ModelHubSourceConfig) -> bool:+ """Vibey speaks the Source's own protocol, except Chat Completions to a ``google`` Source."""++ return source.protocol != "google"+++@lru_cache(maxsize=1)+def _manifest_engine_stamp(path: Optional[str]) -> str:+ if path:+ payload = json.loads(Path(path).read_text(encoding="utf-8"))+ else:+ resource = resources.files("vibe").joinpath("model_hub_runtime/cliproxyapi_manifest.json")+ payload = json.loads(resource.read_text(encoding="utf-8"))+ stamp = payload.get("asset_release_tag") or payload.get("release_tag") or payload.get("version")+ if not isinstance(stamp, str) or not stamp:+ raise ValueError("the engine manifest names no release")+ return stamp+++def engine_stamp() -> str:+ """The engine release evidence is stamped with: the shipped manifest's asset release.++ Engine upgrades ship as manifest changes, and a patched rebuild of the same+ upstream version gets a new asset release, so this is what a wire change+ looks like from here.+ """++ return _manifest_engine_stamp(os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH") or None)+++@dataclass(frozen=True)+class _Context:+ evidence: CapabilityEvidenceStore+ spec_for: SpecLookup+ engine: str+ shape: int+ now: datetime+++def _verified(context: _Context, source: ModelHubSourceConfig, model_id: str, feature: EvidenceFeature) -> bool:+ view = context.evidence.view(source, model_id, feature, engine=context.engine, shape=context.shape, now=context.now)+ return view.status == "verified"+++def _runnable_spec(+ context: _Context, source: ModelHubSourceConfig, model_id: str, tool: str+) -> Optional[HostedToolSpec]:+ if not credential_eligible(source) or not untranslated(source):+ return None+ spec = context.spec_for(source.vendor, source.protocol, model_id, tool)+ if spec is None or not _verified(context, source, model_id, EvidenceFeature.hosted(tool, "call")):+ return None+ return spec+++def _executor(+ context: _Context, config: ModelHubConfig, tool: str, chosen: Optional[tuple[str, str]]+) -> Optional[dict[str, str]]:+ sources = {source.id: source for source in config.sources}+ candidates: list[tuple[str, str]] = []+ if chosen is not None:+ candidates.append(chosen)+ for source_id in config.agents["vibey"].sources.order:+ source = sources.get(source_id)+ if source is not None:+ candidates.extend((source_id, model.id) for model in source.models)+ for source_id, model_id in candidates:+ source = sources.get(source_id)+ if source is not None and _runnable_spec(context, source, model_id, tool) is not None:+ return {"source_id": source_id, "model_id": model_id}+ return None+++def resolve_hosted_tools(+ config: ModelHubConfig,+ *,+ source: ModelHubSourceConfig,+ model_id: str,+ evidence: CapabilityEvidenceStore,+ spec_for: SpecLookup,+ engine: str,+ now: datetime,+ shape: int = HOSTED_PROBE_SHAPE,+) -> dict[str, dict[str, Any]]:+ """``HopResolution.hosted_tools`` for a Vibey hop served by ``source``/``model_id``."""++ context = _Context(evidence, spec_for, engine, shape, now)+ resolved: dict[str, dict[str, Any]] = {}+ for tool in MODEL_HUB_HOSTED_TOOLS:+ toggle = config.hosted_tools.get(tool)+ if toggle is None or not toggle.enabled:+ continue+ spec = _runnable_spec(context, source, model_id, tool)+ entry: dict[str, Any] = {"mode": "native" if spec is not None else "proxy"}+ if spec is not None:+ entry["declaration"] = spec.declaration+ entry["include"] = list(spec.include)+ chosen = (toggle.executor.source_id, toggle.executor.model_id) if toggle.executor is not None else None+ entry["executor"] = _executor(context, config, tool, chosen)+ entry["replay"] = (+ "replay" in HOSTED_TOOL_ASPECTS[tool]+ and credential_eligible(source)+ and untranslated(source)+ and _verified(context, source, model_id, EvidenceFeature.hosted(tool, "replay"))+ )+ resolved[tool] = entry+ return resolved+++def _evidence_payload(view) -> dict[str, Any]:+ record = view.record+ return {+ "status": view.status,+ "stale": view.stale,+ "basis": record.basis if record is not None else None,+ "observed_at": record.payload()["observed_at"] if record is not None else None,+ "detail": record.detail if record is not None else None,+ }+++def _candidate_sources(config: ModelHubConfig) -> list[ModelHubSourceConfig]:+ """Hub Sources that may run hosted tools, Vibey's Source order first."""++ by_id = {source.id: source for source in config.sources}+ ordered = [by_id[source_id] for source_id in config.agents["vibey"].sources.order if source_id in by_id]+ ordered += [source for source in config.sources if source not in ordered]+ return [+ source+ for source in ordered+ if source.supply_channel == "hub" and credential_eligible(source) and untranslated(source)+ ]+++def hosted_tools_status(+ config: ModelHubConfig,+ *,+ evidence: CapabilityEvidenceStore,+ spec_for: SpecLookup,+ engine: str,+ now: datetime,+ shape: int = HOSTED_PROBE_SHAPE,+) -> dict[str, Any]:+ """What the Tools tab reads: each tool's toggle and where it can run, with its evidence.++ ``candidates`` lists every (Source, model) the overlay offers the tool on,+ on an eligible credential and an untranslated path. ``reverify`` counts+ hosted-tool probe evidence that needs a user re-verify: ``engine_upgraded``+ for evidence taken on another engine or probe shape (it routes as unknown),+ ``aged`` for evidence that is only old (it still routes).+ """++ tools = []+ for tool in MODEL_HUB_HOSTED_TOOLS:+ toggle = config.hosted_tools.get(tool)+ candidates = []+ for source in _candidate_sources(config):+ for model in source.models:+ if spec_for(source.vendor, source.protocol, model.id, tool) is None:+ continue+ views = {+ aspect: evidence.view(+ source, model.id, EvidenceFeature.hosted(tool, aspect), engine=engine, shape=shape, now=now+ )+ for aspect in HOSTED_TOOL_ASPECTS[tool]+ }+ candidates.append(+ {+ "source_id": source.id,+ "model_id": model.id,+ "call": _evidence_payload(views["call"]),+ "replay": _evidence_payload(views["replay"]) if "replay" in views else None,+ }+ )+ tools.append(+ {+ "name": tool,+ "enabled": bool(toggle and toggle.enabled),+ "executor": toggle.executor.to_payload() if toggle and toggle.executor else None,+ "candidates": candidates,+ }+ )+ live = {source.id: source for source in config.sources}+ reverify = {"engine_upgraded": 0, "aged": 0}+ for record in evidence.records():+ source = live.get(record.source_id)+ if record.feature.kind != "hosted_tool" or record.basis != "probe" or source is None:+ continue+ stale = evidence.view(+ source, record.model_id, record.feature, engine=engine, shape=shape, now=now+ ).stale+ if stale == "wire":+ reverify["engine_upgraded"] += 1+ elif stale == "age":+ reverify["aged"] += 1+ return {"tools": tools, "reverify": reverify}+++class HostedToolSettingRefused(ValueError):+ """A Tools-tab write the API refuses, with its machine error and HTTP status."""++ def __init__(self, code: str, status: int):+ super().__init__(code)+ self.code = code+ self.status = status+++def parse_hosted_tool_setting(+ config: ModelHubConfig, tool: str, payload: object, *, spec_for: SpecLookup+) -> ModelHubHostedToolConfig:+ """Validate one ``PUT /api/models/hosted-tools/<tool>`` body against the current config.++ The executor must be a hub Source with that model, an eligible credential,+ an untranslated path, and the overlay's declaration for the tool. Whether+ it is verified is evidence, decided at every resolution, never here.+ """++ if tool not in MODEL_HUB_HOSTED_TOOLS:+ raise HostedToolSettingRefused("invalid_parameter", 400)+ try:+ setting = ModelHubHostedToolConfig.from_payload(payload, tool=tool)+ except ValueError:+ raise HostedToolSettingRefused("invalid_parameter", 400) from None+ executor = setting.executor+ if executor is None:+ return setting+ source = next((item for item in config.sources if item.id == executor.source_id), None)+ if source is None:+ raise HostedToolSettingRefused("source_not_found", 404)+ if (+ source not in _candidate_sources(config)+ or executor.model_id not in {model.id for model in source.models}+ or spec_for(source.vendor, source.protocol, executor.model_id, tool) is None+ ):+ raise HostedToolSettingRefused("invalid_parameter", 400)+ return settingdiff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 95021a117..f3e8dc882 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -72,13 +72,20 @@ class HopOrigin:provider: strapi: strmodel: str+ # The serving Source: two Sources can share an origin. Equality stays the+ # origin's, since opaque payloads are origin-bound, not Source-bound.+ source: str = field(compare=False)def payload(self) -> dict[str, str]:return {"provider": self.provider, "api": self.api, "model": self.model}def response_headers(self) -> dict[str, str]:# JSON escapes keep arbitrary Unicode model ids safe in HTTP headers.- value = json.dumps(self.payload(), ensure_ascii=True, separators=(",", ":"))+ value = json.dumps(+ {**self.payload(), "source": self.source},+ ensure_ascii=True,+ separators=(",", ":"),+ )# ensure_ascii makes character count equal to wire byte count.if len(value) > SERVED_HOP_HEADER_MAX_BYTES:raise ServedHopHeaderTooLarge("Served-hop header exceeds its transport bound")@@ -2535,7 +2542,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 11,+ "contract_version": 12,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 7becb3b24..def435213 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -215,6 +215,10 @@ async def dispatch_model_hub_rpc()if operation == "quota_summary":return await service.quota_summary(force=payload.get("force") is True)+ if operation == "hosted_tools_status":+ return await asyncio.to_thread(service.hosted_tools_status)+ if operation == "set_hosted_tool":+ return await service.set_hosted_tool(payload.get("tool"), payload.get("setting"))if operation == "get_agent_chain":return service.agent_chain(payload.get("backend"), payload.get("model_id"))if operation == "get_agent_chains":diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex adefc4bdb..309dd2330 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -51,6 +51,7 @@ from vibe.backend_model_catalog import (PROTOCOL_REASONING_EFFORT_DEFAULTS,builtin_display_name,bundled_catalog_reasoning_efforts_by_model,+ hosted_tool_spec,)from vibe.model_hub_runtime.api_key_vendors import (catalog_api_key_vendor_label,@@ -103,7 +104,15 @@ from .events import (build_resolution_event,contains_credential_material,)+from .capability_evidence import CapabilityEvidenceStorefrom .errors import ModelDiscoveryError+from .hosted_tools import (+ HostedToolSettingRefused,+ engine_stamp,+ hosted_tools_status,+ parse_hosted_tool_setting,+ resolve_hosted_tools,+)from .identifiers import (OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,canonical_model_id,@@ -175,7 +184,7 @@ from .usage import (local_usage_day,)-CONTRACT_VERSION = 11+CONTRACT_VERSION = 12def seeded_source_name(vendor: str) -> str:@@ -298,8 +307,8 @@ def _described_as_unfit_for_agent_turns(match: Mapping[str, Any]) -> bool:)-AGENT_CHAIN_CONTRACT_VERSION = 11-PROBE_RESULT_CONTRACT_VERSION = 11+AGENT_CHAIN_CONTRACT_VERSION = 12+PROBE_RESULT_CONTRACT_VERSION = 12_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60# Background inventory refresh. The first tick doubles as the startup delay, so@@ -1024,7 +1033,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 11,+ "contract_version": 12,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),@@ -1136,6 +1145,7 @@ class ModelHubService:recovery: RecoveryPolicy | None = None,price_table: Callable[[], PriceTable] | None = None,models_dev_catalog: Callable[[], Mapping[str, Any]] | None = None,+ capability_evidence: CapabilityEvidenceStore | None = None,):self.store = storeself.adapter = adapter@@ -1163,6 +1173,10 @@ class ModelHubService:self.migration_journal = migration_journal or NativeTakeoverJournal(events.path.parent / "native-takeover" / "current.json")+ # Beside the other state documents, so it follows wherever they live.+ self.capability_evidence = capability_evidence or CapabilityEvidenceStore(+ events.path.parent / "model_hub_capability_evidence.json"+ )self.migration_blocked_backends: set[str] = set()self.migration_guard = migration_guard or self._unavailable_migration_guardself.migration_reconcile_auth = migration_reconcile_auth@@ -5753,6 +5767,47 @@ class ModelHubService:await self._refresh_backend_catalog(backend)return changed+ def hosted_tools_status(self) -> dict:+ """The Tools tab read: toggles, where each tool can run, and pending re-verifications."""++ return {+ "hosted_tools": hosted_tools_status(+ self.store.load(),+ evidence=self.capability_evidence,+ spec_for=hosted_tool_spec,+ engine=engine_stamp(),+ now=self.now(),+ )+ }++ async def set_hosted_tool(self, tool: str, payload: object) -> dict:+ """Replace one hosted tool's toggle and chosen executor; it applies from the next turn."""++ async with self._mutation_lock:+ previous = self.store.load()+ try:+ setting = parse_hosted_tool_setting(previous, tool, payload, spec_for=hosted_tool_spec)+ except HostedToolSettingRefused as refused:+ raise ModelHubError(refused.code, status=refused.status) from None+ if previous.hosted_tools.get(tool) != setting:+ config = self._clone_config(previous)+ config.hosted_tools[tool] = setting+ await self._commit_synced(previous, config)+ return await asyncio.to_thread(self.hosted_tools_status)++ def hosted_tools_for_hop(self, config: ModelHubConfig, source: ModelHubSourceConfig, model_id: str) -> dict:+ """``HopResolution.hosted_tools`` for a Vibey launch served by this Source and model."""++ return resolve_hosted_tools(+ config,+ source=source,+ model_id=model_id,+ evidence=self.capability_evidence,+ spec_for=hosted_tool_spec,+ engine=engine_stamp(),+ now=self.now(),+ )+async def set_agent_mode(self, backend: str, mode: object) -> dict:if mode not in {"hub", "direct"} or (backend == "vibey" and mode != "hub"):raise ModelHubError("mode_switch_blocked")@@ -8609,7 +8664,7 @@ class ModelHubService:# hop, including fallback/refresh. Persisted ids stay intact;# refusal must precede a transport, attempt, or recovery slot.try:- origin = HopOrigin(source.vendor, source.protocol, model_id)+ origin = HopOrigin(source.vendor, source.protocol, model_id, source.id)origin.response_headers()except ServedHopHeaderTooLarge:raise ModelHubError("served_hop_too_large", status=422) from None@@ -8771,7 +8826,7 @@ class ModelHubService:decision,(),(),- HopOrigin(source.vendor, source.protocol, source_model_id) if backend == "vibey" else None,+ HopOrigin(source.vendor, source.protocol, source_model_id, source.id) if backend == "vibey" else None,)if decision.action == "fallback" or (decision.action == "surface"@@ -8991,7 +9046,7 @@ class ModelHubService:if source is None or target_model is None:raise AssertionError("runnable hop must have an exact identity")verification_pending = source.verification_pending- origin = HopOrigin(source.vendor, source.protocol, target_model) if backend == "vibey" else None+ origin = HopOrigin(source.vendor, source.protocol, target_model, source.id) if backend == "vibey" else Noneif source.supply_channel == "native_cli":self._emit_switch(agent=event_agent,diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 6f9784bec..40a650a26 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -17,7 +17,7 @@ rules on top of those mappings.| Images | `ImageBlock.media_token` is resolved by `MediaLoader` immediately before the request. Unknown `supports_images` is false, so the cross-provider transform replaces each image with `[image: <name or mime>]`. || Tool ids | A safe stored id is preserved when accepted by the target. Otherwise the per-request map uses `call_` plus the first 24 hex characters of SHA-256. The same map rewrites tool results. || Missing tool results | The transform inserts `[tool call interrupted; no result recorded]` with `is_error=true`. |-| Origin | Direct requests use the endpoint origin. Gateway requests parse only `x-avibe-served-hop`, whose JSON object must contain exactly `provider`, `api`, and `model`. A missing or invalid report makes the response unverified: thinking and tool-call signatures are nulled, and redacted thinking is dropped before allocating a canonical slot, so later event indexes still identify their final message blocks. |+| Origin | Direct requests use the endpoint origin. Gateway requests parse only `x-avibe-served-hop`, whose JSON object must contain exactly `provider`, `api`, `model`, and `source` (Model Hub contract v12); `origin` takes `provider`, `api`, `model`, and `source` is the serving Source id matching `^src_[a-z0-9]{8,}$`. A missing or invalid report makes the response unverified: thinking and tool-call signatures are nulled, and redacted thinking is dropped before allocating a canonical slot, so later event indexes still identify their final message blocks. || Cancellation | `CancelToken` ends the HTTP stream and yields one non-retryable `ProviderError(kind="aborted")`. Opening, stream reads, error-body reads, media loads, and served-hop resolution all use the shared cancellation-aware await owner. || Network timeouts | The shared lifecycle driver bounds connecting at 10 seconds; a connect failure or timeout is `ProviderError(kind="network")`. Every wait on a connected provider (response headers, the first chunk, and each next chunk) is bounded by the same 600-second silence bound: reasoning models and relays that buffer tool-call arguments stay silent far longer than a connect window. Codex (`stream_idle_timeout_ms`), Claude Code, Pi, and OpenCode use 300 seconds; Avibe doubles it (owner decision, 2026-10-10) because through Model Hub the response headers wait for the first model output, so a high-effort reasoning model's thinking time is all silence and can exceed five minutes. Running out of the silence bound is `ProviderError(kind="stalled")`, never a connection failure. Both kinds are retryable only when no model output was emitted; a provider that never sends response headers cannot hang a turn. A bounded 10-second cancellation join detaches a non-cooperative transport task instead of extending the timeout indefinitely. || HTTP response status | Only 2xx responses enter an SSE translator. Redirects (3xx) are terminal `invalid_request` errors and are never followed implicitly; 4xx/5xx bodies use the shared status-aware classifier. |diff --git a/docs/plans/agent-core-contracts/hop-resolution.schema.json b/docs/plans/agent-core-contracts/hop-resolution.schema.jsonindex 3a12923e7..e840d73a1 100644--- a/docs/plans/agent-core-contracts/hop-resolution.schema.json+++ b/docs/plans/agent-core-contracts/hop-resolution.schema.json@@ -14,7 +14,8 @@"source_id","provider","capabilities",- "request_headers"+ "request_headers",+ "hosted_tools"],"additionalProperties": false,"properties": {@@ -116,6 +117,216 @@}},"description": "Null means Model Hub does not know the value; it never guesses. supports_images is null when the model declares no input modalities."+ },+ "hosted_tools": {+ "type": "object",+ "description": "One entry per hosted tool the user enabled (vibey-hosted-tools.md §3.5). `mode` is the primary hop's; `declaration` and `include` are the overlay's wire declaration, present exactly for native; `executor` is the proxy executor bound for this turn, present for every entry because a native request answered pin_unavailable is re-rendered with the proxy in the same turn; `replay` is true only for the primary hop Source's positive replay evidence taken on the current engine and probe shape. A request carrying native content is pinned with x-avibe-pin-source: source_id.",+ "propertyNames": {+ "enum": [+ "web_search",+ "x_search",+ "image_generation"+ ]+ },+ "additionalProperties": {+ "type": "object",+ "required": [+ "mode",+ "executor",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "mode": {+ "enum": [+ "native",+ "proxy"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "executor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ ]+ },+ "replay": {+ "type": "boolean"+ }+ },+ "if": {+ "properties": {+ "mode": {+ "const": "native"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "properties": {+ "image_generation": {+ "allOf": [+ {+ "type": "object",+ "required": [+ "mode",+ "executor",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "mode": {+ "enum": [+ "native",+ "proxy"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "executor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ ]+ },+ "replay": {+ "type": "boolean"+ }+ },+ "if": {+ "properties": {+ "mode": {+ "const": "native"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ {+ "properties": {+ "replay": {+ "const": false+ }+ }+ }+ ]+ }+ }}},"examples": [@@ -142,6 +353,16 @@"high","xhigh"]+ },+ "hosted_tools": {+ "web_search": {+ "mode": "proxy",+ "executor": {+ "source_id": "src_xai00001",+ "model_id": "grok-4.6"+ },+ "replay": false+ }}}]diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.jsonindex 804f2de63..780c8a852 100644--- a/docs/plans/agent-core-contracts/message.schema.json+++ b/docs/plans/agent-core-contracts/message.schema.json@@ -83,6 +83,14 @@},"ref": {"$ref": "#/definitions/LargeRef"+ },+ "citations": {+ "type": "array",+ "minItems": 1,+ "items": {+ "$ref": "#/definitions/Citation"+ },+ "description": "Assistant text only, and only with inline `text`. Presentation only; never replayed."}},"oneOf": [@@ -96,7 +104,12 @@"ref"]}- ]+ ],+ "dependencies": {+ "citations": [+ "text"+ ]+ }},"ImageBlock": {"type": "object",@@ -318,6 +331,9 @@},{"$ref": "#/definitions/ToolCallBlock"+ },+ {+ "$ref": "#/definitions/HostedToolBlock"}]}@@ -334,6 +350,38 @@"error_message": {"type": "string","description": "Present when `stop_reason` is `error` or `aborted`."+ },+ "hosted_summary": {+ "$ref": "#/definitions/HostedSummary"+ }+ },+ "if": {+ "properties": {+ "content": {+ "contains": {+ "type": "object",+ "properties": {+ "type": {+ "const": "hosted_tool"+ }+ },+ "required": [+ "type"+ ]+ }+ }+ }+ },+ "then": {+ "required": [+ "hosted_summary"+ ]+ },+ "else": {+ "not": {+ "required": [+ "hosted_summary"+ ]}}},@@ -375,6 +423,790 @@},"is_error": {"type": "boolean"+ },+ "hosted": {+ "type": "object",+ "required": [+ "record"+ ],+ "additionalProperties": false,+ "description": "Set only on the result of a proxied hosted call. `execution` is present exactly when an executor ran; without it the record failed.",+ "properties": {+ "record": {+ "$ref": "#/definitions/HostedRecord"+ },+ "execution": {+ "$ref": "#/definitions/ProxyExecution"+ }+ },+ "if": {+ "not": {+ "required": [+ "execution"+ ]+ }+ },+ "then": {+ "properties": {+ "record": {+ "properties": {+ "status": {+ "const": "failed"+ }+ }+ }+ }+ }+ }+ },+ "allOf": [+ {+ "if": {+ "required": [+ "hosted"+ ]+ },+ "then": {+ "properties": {+ "tool_name": {+ "$ref": "#/definitions/HostedToolName"+ }+ }+ }+ },+ {+ "if": {+ "required": [+ "hosted"+ ],+ "properties": {+ "hosted": {+ "properties": {+ "record": {+ "properties": {+ "status": {+ "enum": [+ "failed",+ "incomplete"+ ]+ }+ }+ }+ }+ }+ }+ },+ "then": {+ "properties": {+ "is_error": {+ "const": true+ }+ }+ }+ },+ {+ "if": {+ "required": [+ "hosted"+ ],+ "properties": {+ "hosted": {+ "properties": {+ "record": {+ "properties": {+ "status": {+ "enum": [+ "completed",+ "pending"+ ]+ }+ }+ }+ }+ }+ }+ },+ "then": {+ "properties": {+ "is_error": {+ "const": false+ }+ }+ }+ },+ {+ "if": {+ "required": [+ "hosted"+ ],+ "properties": {+ "tool_name": {+ "const": "image_generation"+ }+ }+ },+ "then": {+ "properties": {+ "hosted": {+ "properties": {+ "record": {+ "required": [+ "images"+ ]+ }+ }+ }+ }+ }+ },+ {+ "if": {+ "required": [+ "hosted"+ ],+ "properties": {+ "tool_name": {+ "enum": [+ "web_search",+ "x_search"+ ]+ }+ }+ },+ "then": {+ "properties": {+ "hosted": {+ "properties": {+ "record": {+ "not": {+ "required": [+ "images"+ ]+ }+ }+ }+ }+ }+ }+ }+ ]+ },+ "Citation": {+ "type": "object",+ "required": [+ "url"+ ],+ "additionalProperties": false,+ "description": "A source the provider attached to assistant text. `start` and `end` come together, as a half-open code-point range into the block's `text` (0 <= start <= end <= its length).",+ "properties": {+ "url": {+ "type": "string",+ "minLength": 1+ },+ "title": {+ "type": "string"+ },+ "cited_text": {+ "type": "string"+ },+ "start": {+ "type": "integer",+ "minimum": 0+ },+ "end": {+ "type": "integer",+ "minimum": 0+ }+ },+ "dependencies": {+ "start": [+ "end"+ ],+ "end": [+ "start"+ ]+ }+ },+ "HostedToolName": {+ "enum": [+ "web_search",+ "x_search",+ "image_generation"+ ],+ "description": "Catalog name of a hosted tool (`vibey-hosted-tools.md` §2)."+ },+ "HostedAction": {+ "description": "What a hosted call did, provider-neutral (`vibey-hosted-tools.md` §4.2 mapping rule). An item the mapping does not know is `other`, never dropped.",+ "oneOf": [+ {+ "type": "object",+ "required": [+ "type",+ "queries"+ ],+ "additionalProperties": false,+ "description": "A web search; `queries` from `action.queries`, else the deprecated singular `action.query`.",+ "properties": {+ "type": {+ "const": "search"+ },+ "queries": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "url"+ ],+ "additionalProperties": false,+ "description": "A web search opened a page.",+ "properties": {+ "type": {+ "const": "open_page"+ },+ "url": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "url",+ "pattern"+ ],+ "additionalProperties": false,+ "description": "A web search searched within a page.",+ "properties": {+ "type": {+ "const": "find_in_page"+ },+ "url": {+ "type": "string",+ "minLength": 1+ },+ "pattern": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "variant",+ "query"+ ],+ "additionalProperties": false,+ "description": "An X post search; `limit` and `mode` are kept when the call carries them.",+ "properties": {+ "type": {+ "const": "x_search"+ },+ "variant": {+ "enum": [+ "keyword",+ "semantic"+ ]+ },+ "query": {+ "type": "string",+ "minLength": 1+ },+ "limit": {+ "type": "integer",+ "minimum": 1+ },+ "mode": {+ "enum": [+ "Latest",+ "Top"+ ]+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "query"+ ],+ "additionalProperties": false,+ "description": "An X user search.",+ "properties": {+ "type": {+ "const": "x_user_search"+ },+ "query": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "ref"+ ],+ "additionalProperties": false,+ "description": "An X thread fetch.",+ "properties": {+ "type": {+ "const": "x_thread_fetch"+ },+ "ref": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type"+ ],+ "additionalProperties": false,+ "description": "An image generation. `prompt` is the provider's revised prompt, required for a completed record; `size` and `quality` are the resolved output settings.",+ "properties": {+ "type": {+ "const": "generate"+ },+ "prompt": {+ "type": "string",+ "minLength": 1+ },+ "size": {+ "type": "string",+ "minLength": 1+ },+ "quality": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "name"+ ],+ "additionalProperties": false,+ "description": "Any other item under a declared hosted tool, with the provider's item name.",+ "properties": {+ "type": {+ "const": "other"+ },+ "name": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ ]+ },+ "HostedSource": {+ "type": "object",+ "required": [+ "url"+ ],+ "additionalProperties": false,+ "properties": {+ "url": {+ "type": "string",+ "minLength": 1+ },+ "title": {+ "type": "string"+ },+ "snippet": {+ "type": "string"+ },+ "page_age": {+ "type": "string"+ }+ }+ },+ "HostedImage": {+ "type": "object",+ "required": [+ "path",+ "mime"+ ],+ "additionalProperties": false,+ "description": "A generated image saved as a local file. Image bytes are never stored in a message.",+ "properties": {+ "path": {+ "type": "string",+ "minLength": 1+ },+ "mime": {+ "enum": [+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp"+ ]+ },+ "width": {+ "type": "integer",+ "minimum": 1+ },+ "height": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "HostedRecord": {+ "type": "object",+ "required": [+ "status",+ "sources"+ ],+ "additionalProperties": false,+ "description": "Per-call facts of one hosted call. `images` is present exactly for `image_generation`.",+ "properties": {+ "status": {+ "enum": [+ "completed",+ "failed",+ "incomplete",+ "pending"+ ]+ },+ "error": {+ "type": "string",+ "minLength": 1,+ "maxLength": 400,+ "description": "Bounded and redacted."+ },+ "sources": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/HostedSource"+ },+ "description": "This call's own results. Empty when the provider returns none per call (xAI X search), except in a proxied call's record."+ },+ "images": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/HostedImage"+ }+ }+ },+ "if": {+ "properties": {+ "status": {+ "enum": [+ "failed",+ "incomplete"+ ]+ }+ }+ },+ "then": {+ "required": [+ "error"+ ]+ },+ "else": {+ "not": {+ "required": [+ "error"+ ]+ }+ }+ },+ "HostedToolBlock": {+ "type": "object",+ "required": [+ "type",+ "id",+ "tool",+ "action",+ "record",+ "native"+ ],+ "additionalProperties": false,+ "description": "One native hosted call. A proxied call is a `ToolCallBlock` plus `ToolResultMessage.hosted`, never this block.",+ "properties": {+ "type": {+ "const": "hosted_tool"+ },+ "id": {+ "type": "string",+ "minLength": 1+ },+ "tool": {+ "$ref": "#/definitions/HostedToolName"+ },+ "action": {+ "$ref": "#/definitions/HostedAction"+ },+ "record": {+ "$ref": "#/definitions/HostedRecord"+ },+ "native": {+ "type": "object",+ "required": [+ "source_id",+ "payload"+ ],+ "additionalProperties": false,+ "description": "The provider's own items, verbatim and in order. Their origin is the message's `origin`; replay is decided at every request from current evidence and never stored.",+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "payload": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object"+ }+ }+ }+ }+ },+ "allOf": [+ {+ "if": {+ "properties": {+ "tool": {+ "const": "web_search"+ }+ }+ },+ "then": {+ "properties": {+ "action": {+ "properties": {+ "type": {+ "enum": [+ "search",+ "open_page",+ "find_in_page",+ "other"+ ]+ }+ }+ },+ "record": {+ "not": {+ "required": [+ "images"+ ]+ }+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "tool": {+ "const": "x_search"+ }+ }+ },+ "then": {+ "properties": {+ "action": {+ "properties": {+ "type": {+ "enum": [+ "x_search",+ "x_user_search",+ "x_thread_fetch",+ "other"+ ]+ }+ }+ },+ "record": {+ "not": {+ "required": [+ "images"+ ]+ }+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "tool": {+ "const": "image_generation"+ }+ }+ },+ "then": {+ "properties": {+ "action": {+ "properties": {+ "type": {+ "enum": [+ "generate",+ "other"+ ]+ }+ }+ },+ "record": {+ "required": [+ "images"+ ]+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "action": {+ "properties": {+ "type": {+ "const": "generate"+ }+ }+ },+ "record": {+ "properties": {+ "status": {+ "const": "completed"+ }+ }+ }+ }+ },+ "then": {+ "properties": {+ "action": {+ "required": [+ "prompt"+ ]+ }+ }+ }+ }+ ]+ },+ "HostedCost": {+ "type": "object",+ "required": [+ "basis"+ ],+ "additionalProperties": false,+ "description": "`reported`: the provider's figure; `list`: computed by Model Hub's pricing module; `included`: a subscription Source, no per-call charge.",+ "properties": {+ "basis": {+ "enum": [+ "reported",+ "list",+ "included"+ ]+ },+ "usd": {+ "type": "number",+ "minimum": 0+ }+ },+ "if": {+ "properties": {+ "basis": {+ "const": "included"+ }+ }+ },+ "then": {+ "not": {+ "required": [+ "usd"+ ]+ }+ },+ "else": {+ "required": [+ "usd"+ ]+ }+ },+ "HostedSummary": {+ "type": "object",+ "required": [+ "counts",+ "cited_sources"+ ],+ "additionalProperties": false,+ "description": "Response-scoped hosted facts, never copied into calls. `cost` is absent when no price is known: unknown is never priced as zero.",+ "properties": {+ "cost": {+ "$ref": "#/definitions/HostedCost"+ },+ "counts": {+ "type": "object",+ "propertyNames": {+ "pattern": "^[a-z0-9_]{1,64}$"+ },+ "additionalProperties": {+ "type": "integer",+ "minimum": 0+ },+ "description": "Provider-reported counters by name, e.g. `web_search_calls`, `x_posts_fetched`, `web_search_requests`."+ },+ "cited_sources": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/HostedSource"+ },+ "description": "Sources the response cites when the provider gives none per call (xAI X-search `url_citation`s)."+ }+ }+ },+ "ProxyExecution": {+ "type": "object",+ "required": [+ "mode",+ "executor_origin",+ "executor_source_id",+ "executor_billing"+ ],+ "additionalProperties": false,+ "description": "Which executor ran a proxied hosted call. `cost` is absent when no price is known.",+ "properties": {+ "mode": {+ "const": "proxy"+ },+ "executor_origin": {+ "$ref": "#/definitions/Origin"+ },+ "executor_source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "executor_billing": {+ "enum": [+ "monthly",+ "metered"+ ]+ },+ "cost": {+ "$ref": "#/definitions/HostedCost"}}}diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.mdindex 82e01135c..681bf0c3e 100644--- a/docs/plans/agent-core-contracts/model-hub-consumer.md+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md@@ -24,10 +24,11 @@ consumer's requirements, and the Model Hub lane lands the change in both places.Hub stores one. The agent treats unknown values conservatively (C-2). It resolves once per run and again after aretryable error.4. **Served-hop report.** Every gateway response for `vibey` carries `x-avibe-served-hop`: compact, ASCII-escaped JSON- with exactly `provider`, `api`, `model`, taken from the winning attempt (Source vendor, Source protocol, upstream- target) and sent before the first model byte. The gateway does not commit early keepalive headers for `vibey`;- other backends are unchanged. The same origin is recorded on `TurnProvenance.served`. An `api` different from the- frontend protocol means the gateway converted. The agent records it as the message `origin` (C-1). The header value is at most 4096 bytes; a hop whose origin cannot be represented within that limit is+ with exactly `provider`, `api`, `model`, `source` (since Model Hub contract v12), taken from the winning attempt+ (Source vendor, Source protocol, upstream target, Source id) and sent before the first model byte. The gateway does+ not commit early keepalive headers for `vibey`; other backends are unchanged. The same origin is recorded on+ `TurnProvenance.served`, beside its `source_id`. An `api` different from the frontend protocol means the gateway+ converted. The agent records `provider`, `api`, `model` as the message `origin` (C-1); `source` is not part of it. The header value is at most 4096 bytes; a hop whose origin cannot be represented within that limit isrefused before invocation with a controlled local error (no model call, no header). Identifiers are never truncated.5. **Conversion stays a fallback.** The agent speaks the primary hop's protocol. When failover reaches a hop withanother protocol, the gateway converts (degraded, not broken) and the served-hop report says so.@@ -61,11 +62,9 @@ consumer's requirements, and the Model Hub lane lands the change in both places.- its attempt ends before model output with an error that a narrow hosted-content evidence rule names.- Vibey then renders the same request in portable form and sends it unpinned; it fails over as today.- Item 6 (the opaque thinking strip) is unchanged and applies only to unpinned requests.- - The served-hop report gains `source`, the serving Source id, so that a hosted block's payload is tagged with- the exact Source; two Sources can share an origin. The parser in `conversion-tables.md` (exactly `provider`,- `api`, `model` today) changes in the same release, in a coordinated Model Hub contract bump (v12). Native- hosted mode lands with or after v12. `../vibey-hosted-tools.md` §5 lists the frozen exact-shape contracts that- the bump edits together.+ - The served-hop report carries `source`, the serving Source id (item 4, Model Hub contract v12), so that a+ hosted block's payload is tagged with the exact Source; two Sources can share an origin. The gateway and the+ parser in `conversion-tables.md` changed together in that bump. Native hosted mode lands with or after v12.## 3. Not requireddiff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex e6b8ba2dd..31e7d8073 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -65,7 +65,9 @@ token names an immutable snapshot (`message.schema.json`), so the bytes never ch`stream` yields `ProviderEvent`s (`provider-event.schema.json`) and always ends with exactly one `done` or one`error`. `done.message` is the complete canonical `AssistantMessage`; its `origin` comes from the served-hop report(C-6), which the gateway sends as the `x-avibe-served-hop` response header: compact JSON with exactly `provider`,-`api`, `model`, before the first model byte. On the direct channel (no gateway) the endpoint is the served hop. When a gateway response carries no+`api`, `model`, `source` (Model Hub contract v12), before the first model byte. The `origin` is `provider`, `api`,+`model`; `source` is the serving Source id, which is not part of a message's origin. A report of any other shape+counts as no report. On the direct channel (no gateway) the endpoint is the served hop. When a gateway response carries noserved-hop report, the origin is unverified: the adapter commits the message with every opaque provider payloadremoved (the `signature` of every block of any kind, and redacted thinking), keeping the endpoint as `origin`, so noopaque payload of an unknown vendor can ever be replayed. A block without a signature is always sent without onediff --git a/docs/plans/model-hub-capability-model.md b/docs/plans/model-hub-capability-model.mdindex ed5c4b676..48d2f43ad 100644--- a/docs/plans/model-hub-capability-model.md+++ b/docs/plans/model-hub-capability-model.md@@ -57,8 +57,8 @@ Rules:### 3.1 RecordOne record per (`source_id`, `model_id`, `feature`). Absence of a record is `unknown`. The persisted shape is-below. Its JSON Schema (`model-hub-contracts/capability-evidence.schema.json`) lands with Phase 0, where the store-validates it.+below, and [`model-hub-contracts/capability-evidence.schema.json`](model-hub-contracts/capability-evidence.schema.json)+is its JSON Schema. The store is `core/handlers/model_hub/capability_evidence.py`.| Field | Rule || --- | --- |@@ -67,16 +67,18 @@ validates it.| `feature` | `{kind: "effort", name}` or `{kind: "hosted_tool", name: "web_search" \| "x_search" \| "image_generation", aspect: "call" \| "replay"}`; `image_generation` has `call` only || `status` | `verified` or `unsupported` || `basis` | `probe` (a live probe the user started) or `observed` (learned from a real request's error) |-| `observed_at` | timestamp |-| `engine` | engine release at that time; a change makes `probe` evidence stale (§3.3) |+| `observed_at` | UTC timestamp |+| `engine` | engine release at that time (the shipped engine manifest's asset release); a change makes `probe` evidence stale (§3.3) || `shape` | version of the request shape that produced the record; a change makes `probe` evidence stale || `detail` | required when `basis` is `observed`: the HTTP status and upstream machine code, e.g. `400 invalid_value`, at most 64 characters, never upstream text |+| `source_identity` | digest of `retry.source_identity` when the record was written |`observed` evidence is always `unsupported`.-Records live with the Source's runtime state (`model_hub` state dir). They follow Source identity:+Records live in the Model Hub state directory (`model_hub_capability_evidence.json`). They follow Source identity:`retry.source_identity` covers kind, vendor, protocol, channel, base URL, credential and verification marker.-Changing any of those drops the Source's evidence.+Changing any of those drops the Source's evidence: a record whose stored digest no longer matches reads as unknown+and is pruned at the next write.### 3.2 Learning from real errors (negative evidence)@@ -139,9 +141,11 @@ Even without the overlay fix, the next request would skip that hop or fail clear## 4. The overlay's `providers` section-The section is keyed by Source vendor (`openai`, `anthropic`, `xai`, …). Each vendor holds a list of model-families, matched by the existing model-id normalization, the first matching prefix winning. A new model of a-family inherits its row. Shape (`vibe/data/backend_models.json`, `providers`; the loader validates it):+The section is keyed by canonical Source vendor id (`openai`, `anthropic`, `xai`, …). Each vendor holds an ordered+list of model families. A family matches by `prefix` or exact `id` against the model id as Model Hub normalizes it+for Source models and route hops (`normalized_model_id`), and the first match wins. A new model of a family inherits+its row. Shape (`vibe/data/backend_models.json`, `providers`; the loader in `vibe/backend_model_catalog.py`+validates it):```json"providers": {@@ -163,18 +167,23 @@ family inherits its row. Shape (`vibe/data/backend_models.json`, `providers`; th}```-Fields of one vendor entry. The loader validates them; their JSON Schema lands with Phase 0.+Fields of one vendor entry, mirrored by+[`model-hub-contracts/provider-overlay.schema.json`](model-hub-contracts/provider-overlay.schema.json):| Field | Rule || --- | --- || `models[]` | required; ordered, first match wins || `match` | exactly one of `prefix` or `id`, non-empty |-| `wire_efforts` | a list of effort names, or `null` to defer to models.dev |-| `hosted_tools` | protocol (`anthropic`, `openai_responses`, `openai_chat`, `google`) → tool (`web_search`, `x_search`, `image_generation`) → `{declaration, price, include?}`. `declaration` and `price` are required, and `declaration` has a `type`. `include` lists Responses `include` values the tool needs (OpenAI web search: `web_search_call.action.sources`). |-| `price` | `unit` (`call`, `search`, `post`, `profile`, `image`), `usd_per_1k` ≥ 0, `as_of` (date) and `url`, all required; optional `extra[]` of `{unit, usd_per_1k}`. Image prices vary by quality and size, so each `image` entry in `extra[]` also carries `quality` and `size`, and pricing selects the entry that matches the declaration that ran. |+| `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`) → tool (`web_search`, `x_search`, `image_generation`) → `{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. OpenAI prices image generation per image token, not per image, so its `image_generation` entry has none. `include` lists Responses `include` values the tool needs (OpenAI web search: `web_search_call.action.sources`). |+| `price` | `unit` (`call`, `search`, `post`, `profile`), `usd_per_1k` ≥ 0, `as_of` (date) and `url` (https), all required; optional `extra[]` of `{unit, usd_per_1k}`. A per-image unit, whose entries would also carry `quality` and `size`, waits for a vendor that lists a per-image price. |- The overlay records what the **provider** offers. Whether a Source (a relay, a subscription) carries it isevidence.-- An invalid vendor entry disables that entry with a warning; startup never fails.+- An invalid vendor entry disables that entry with a warning; startup never fails. A `providers` value that is not+ an object disables the whole overlay. Backend rows never depend on the section.+- The section is read from the bundled file only, never from the remote catalog copy that refreshes backend rows:+ its declarations go on the wire and must match the code that shipped with them. Released loaders ignore both the+ section and the rows' `client_presets`.## 5. What Models shows per Source@@ -215,7 +224,7 @@ and the existing tone vocabulary (`TimeHint` for dates):| --- | --- | --- || Token prices: input, output, cache read, cache write | models.dev base `cost.*`; the user's override file | used || One-hour cache write | override file, or 2× input by default (`pricing.py`) | used; models.dev has no field |-| **Context-tier prices** (a higher rate past a context size) | models.dev `cost.tiers[]` with `{"tier": {"type": "context", "size": N}}`, plus the legacy `cost.context_over_200k`. On 2026-10-13: 630 and 517 models (e.g. `gpt-6-astra` above 272K: $20/$75; `grok-4.6` above 200K: $4/$12) | **not used.** `model_price` reads only the flat fields, so valuation understates long-context use. Fix: when a call's input tokens exceed `size`, the tier's rates apply to the whole call, as the vendors bill. The ledger already has per-call input tokens. |+| **Context-tier prices** (a higher rate past a context size) | models.dev `cost.tiers[]` with `{"tier": {"type": "context", "size": N}}`, plus the legacy `cost.context_over_200k`. On 2026-10-13: 630 and 517 models (e.g. `gpt-6-astra` above 272K: $20/$75; `grok-4.6` above 200K: $4/$12) | **not used.** `model_price` reads only the flat fields, so valuation understates long-context use. Fix: when a call's total context input (input plus cache-read and cache-write tokens) exceeds `size`, the tier's rates apply to the whole call, as the vendors bill. The usage ledger aggregates per (day, Source, model) and keeps no per-call rows, so the tier must be applied when a call is recorded (Phase 1 pricing PR). || **Hosted-tool call prices** | overlay `providers.<vendor>.models[].hosted_tools.<protocol>.<tool>.price` (§4): unit, USD per 1,000 units, date and source URL | new. models.dev has none; the open proposal anomalyco/models.dev#8707 adds `cost.web_search = {search, prompt}` (no maintainer response yet) || Search-result tokens | the provider's usage (input tokens), priced by the token rows | already counted as input || Provider-reported cost | per-call usage, when present: xAI `cost_in_usd_ticks` (USD × 10¹⁰), `server_side_tool_usage_details`; Anthropic `server_tool_use.web_search_requests` | not read today; hosted tools read it (§6.4) |diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 065245280..1c8aff9dc 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,6 +1,8 @@# Model Hub contracts-Status: **contract_version 11**, 2026-10-02: the Vibey Hub-only consumer, primary-hop+Status: **contract_version 12**, 2026-10-13: the served-hop response header also names+the serving Source id (`served-hop.schema.json`), because two Sources can share an origin.+It builds on v11 (2026-10-02): the Vibey Hub-only consumer, primary-hopresolution and response origin linked to the served attempt, plus the Google protocolvocabulary and Gemini gateway frontend, with API/config-only Source admission. See[`vibey-consumer.md`](vibey-consumer.md) and [`google-protocol.md`](google-protocol.md).@@ -182,7 +184,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 11 must coexist in all registered version locations on the same tested head:+`contract_version` 12 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`@@ -240,6 +242,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. The one versioned object persisted to disk, so it accepts every released version. || `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns, with its list-API-price valuation. A report only: no consumer may feed it back into resolution, admission, or cooldown. || `quota-summary.schema.json` | Rate-limit windows of hub-held subscriptions, parsed from each vendor's own usage report, and the API-price value of each subscription's metered usage against its monthly fee. A report only; carries no grant or raw body. |+| `hosted-tools-status.schema.json` | The Tools tab read: each hosted tool's toggle and chosen executor, every eligible (Source, model) the overlay offers it on with its `call` and `replay` evidence, and re-verify counts. A report only; hop resolution reads config and evidence itself. || `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. || `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. || `migration-scan.schema.json` | Server-owned custody-takeover scan of existing native CLI/provider configuration; not an internal contract migration. |@@ -253,6 +256,9 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| `vibey-consumer.md` | C-6 launch projection, capability authority, served-hop response headers, and delivery boundaries. || `google-protocol.md` | Google API/config admission, native gateway paths, discovery, stream facts, and pinned-engine translation boundary. || `vibey-boundary-matrix.json` | Executable Vibey backend/channel audit: all declared schema shapes, runtime admission owners, and Hub-only refusal cases. |-| `hop-resolution.schema.json` | Ephemeral in-process Vibey consumer result, including gateway-only credentials and nullable capabilities. |-| `hop-origin.schema.json` | Non-secret response origin shared by the HTTP response header and provenance attempt. |+| `hop-resolution.schema.json` | Ephemeral in-process Vibey consumer result, including gateway-only credentials, nullable capabilities, and each enabled hosted tool's mode, declaration, bound executor, and replay authorization. |+| `hop-origin.schema.json` | Non-secret upstream origin persisted on the provenance attempt, beside its `source_id`. |+| `served-hop.schema.json` | Exact `x-avibe-served-hop` response header value: the admitted origin plus the serving Source id. |+| `capability-evidence.schema.json` | One persisted (Source, model, feature) evidence record: probe or observed, with its engine and probe-shape stamps and the Source identity it follows. |+| `provider-overlay.schema.json` | The `providers` section of `vibe/data/backend_models.json`: per-vendor model families with wire efforts and hosted-tool declarations, includes, and list prices. || `README.md` | This ownership, version-closure, and contract-index document. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 35e57a833..7550be7e6 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -1,4 +1,4 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v11 (2026-10-02).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v12 (2026-10-13).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex afc9b48e7..9aa131a61 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"model_id": { "type": "string" },"manual_override": {@@ -237,7 +237,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "unlisted-model","manual_override": null,@@ -247,7 +247,7 @@"supply_state": "ok"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -257,7 +257,7 @@"supply_state": "ok"},{- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-opus-4-6","manual_override": null,@@ -267,7 +267,7 @@"supply_state": "waiting"},{- "contract_version": 11,+ "contract_version": 12,"backend": "opencode","model_id": "glm-5.2","manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },@@ -277,7 +277,7 @@"supply_state": "waiting"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -287,7 +287,7 @@"supply_state": "interrupted"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -297,7 +297,7 @@"supply_state": "interrupted"},{- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-haiku-4-5","manual_override": null,diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 678574266..867148b6d 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -37,6 +37,8 @@{"method": "GET", "path": "/api/models/usage?days=<n>", "response_schema": "UsageResponse", "exercises": [{"path": "/api/models/usage?days=30", "status": 200}, {"path": "/api/models/usage?window=24h", "status": 200}]},{"method": "GET", "path": "/api/models/quota", "response_schema": "QuotaResponse", "exercise": {"path": "/api/models/quota", "status": 200}},{"method": "POST", "path": "/api/models/quota/refresh", "response_schema": "QuotaResponse", "exercise": {"path": "/api/models/quota/refresh", "status": 200}},+ {"method": "GET", "path": "/api/models/hosted-tools", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools", "status": 200}},+ {"method": "PUT", "path": "/api/models/hosted-tools/<tool>", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools/web_search", "status": 200, "json": {"enabled": true, "executor": null}}},{"method": "POST", "path": "/api/models/oauth/start", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/oauth/start", "status": 200, "json": {"vendor": "anthropic", "channel": "hub"}}},{"method": "GET", "path": "/api/models/oauth/status/<flow_id>", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/status/oaf_00000001", "status": 200}},{"method": "POST", "path": "/api/models/oauth/submit", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/submit", "status": 200, "json": {"flow_id": "oaf_00000001", "value": "contract-code"}}},@@ -56,7 +58,7 @@"required": ["ok", "contract_version", "probe"],"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"probe": {"$ref": "model-hub/source-probe-result.schema.json"}}},@@ -155,7 +157,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 11}+ "contract_version": {"const": 12}}},"SourceListResponse": {@@ -164,7 +166,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -174,7 +176,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -184,7 +186,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"source": {"$ref": "#/definitions/SourceApi"},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}@@ -196,7 +198,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -206,7 +208,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"source": {"$ref": "#/definitions/SourceApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -218,7 +220,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}@@ -229,7 +231,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -239,7 +241,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -256,7 +258,7 @@],"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agent": {"$ref": "#/definitions/AgentSupplyApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}@@ -281,7 +283,7 @@"additionalProperties": false,"properties": {"ok": {"const": false},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -301,7 +303,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],@@ -402,7 +404,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -421,7 +423,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"matches": {"type": "array","maxItems": 8,@@ -455,7 +457,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -465,7 +467,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -475,7 +477,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -487,7 +489,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -497,7 +499,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -507,7 +509,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -517,17 +519,27 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"quota": {"$ref": "model-hub/quota-summary.schema.json"}}},+ "HostedToolsResponse": {+ "type": "object",+ "required": ["ok", "contract_version", "hosted_tools"],+ "additionalProperties": false,+ "properties": {+ "ok": {"const": true},+ "contract_version": {"const": 12},+ "hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}+ }+ },"OAuthFlowResponse": {"type": "object","required": ["ok", "contract_version", "flow"],"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -549,7 +561,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -572,7 +584,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -597,7 +609,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11}+ "contract_version": {"const": 12}}},"RuntimeApi": {@@ -619,7 +631,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -629,7 +641,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -641,7 +653,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -652,7 +664,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"provenance": {"anyOf": [{"$ref": "model-hub/turn-provenance.schema.json"},@@ -667,7 +679,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex d4f409f8a..bf7a9791f 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -8,11 +8,11 @@ credential redaction and supply-impact confirmation rules still apply; unknownAPI siblings retain the Owner default.-Status: **Normative, `contract_version` 11** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.+Status: **Normative, `contract_version` 12** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.-Success envelope: `{ok: true, contract_version: 11, ...}`.+Success envelope: `{ok: true, contract_version: 12, ...}`.Failure envelope:-`{ok: false, contract_version: 11, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 12, error: <machine_code>, detail?: <i18n_key>}`.`detail` is always a string. Structured error data lives in a named sibling.Guarded mutation refusals specialize that envelope through`guard-refusal.schema.json`; both report arrays are required and together form the plan@@ -24,7 +24,7 @@ table. The contract guard requires the two endpoint sets to be identical, requirexercised HTTP response for every registry entry, and validates that response againstthe route's named schema.-The shared envelope and every versioned nested contract carry `contract_version` 11, the+The shared envelope and every versioned nested contract carry `contract_version` 12, theterminal value. Supported persisted config shapes and historical TurnProvenanceremain readable; ephemeral envelopes use only the terminal version.@@ -71,6 +71,8 @@ runtime open. Once models are configured it participates in the runtime Stop gua| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary \| UsageReport}` | The released `days` selector remains supported and is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. The exclusive modern `window=24h\|7d\|30d\|60d` selector returns the dense temporal report; sending both selectors or an invalid `window` returns `400 invalid_parameter`. || GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report, plus each Source's API-price `value` (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline, and a Source still being read is listed in `pending`. Never starts the engine. || POST `/api/models/quota/refresh` | → `{quota: QuotaSummary}` | Forced re-read. Rate-limited per Source to one vendor call every 30 seconds and suppressed while a Source cools down after a vendor 429; a suppressed Source returns its cached snapshot. |+| GET `/api/models/hosted-tools` | → `{hosted_tools: HostedToolsStatus}` | The Tools tab read (`hosted-tools-status.schema.json`): every catalog tool with its toggle and chosen executor, every (Source, model) the overlay offers it on with an eligible credential and an untranslated path, each with its `call` and `replay` evidence as routing reads it, and `reverify` counts: `engine_upgraded` for probe evidence taken on another engine or probe shape (now routed as unknown) and `aged`. Never probes and never starts the engine. |+| PUT `/api/models/hosted-tools/<tool>` | `{enabled: boolean, executor: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Replaces one tool's toggle and chosen executor; it applies from the next turn and interrupts nothing. An unknown tool or a malformed body returns `400 invalid_parameter`; an executor naming a missing Source returns `404 source_not_found`; an executor that is not a hub Source with that model, an eligible credential, an untranslated path and the overlay's declaration returns `400 invalid_parameter`. Whether the executor is verified is evidence, read at each hop resolution. || POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. || GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. A `failed` flow names its cause with the closed `error_key` and, when the provider, engine, or native CLI said more, carries that reason verbatim on one bounded line in `error_detail` for the dialog's copyable details. || POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A callback address is recognized with or without its `http(s)://` scheme, which browsers drop when copying a page that failed to load; any other value is a bare code. An address the flow refuses before anything reaches the provider is the non-terminal `422 submission_rejected`: one with no `code` or `error`, or one whose `state` answers a different sign-in link than this flow's (`detail: modelHub.errors.submission_rejected_other_attempt`). The flow stays `awaiting_action` and accepts another submission until its `expires_at`. |@@ -78,7 +80,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. || GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 11 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 12 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. || POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. || POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent; runtime availability has no separate enable-confirmation step. Uses the existing mutation authentication and CSRF guards; status reads never start it. || POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any native backend is configured for Hub mode or Avibe has catalog models, so disabling the shared runtime cannot strand a configured route. An empty Avibe catalog does not keep the runtime open. |@@ -619,7 +621,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"source": {"id": "src_anthkey01","kind": "api_key",@@ -729,7 +731,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -865,7 +867,7 @@ API-key success:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -956,7 +958,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -1029,9 +1031,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"chain": {- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -1058,7 +1060,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -1072,9 +1074,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"probe": {- "contract_version": 11,+ "contract_version": 12,"backend": "claude","channel": "hub","reachable": false,@@ -1097,7 +1099,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": true,@@ -1110,7 +1112,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": false,@@ -1126,7 +1128,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1317,7 +1319,7 @@ The store retains at most 500 exactly attributed settled turns with its existingwrites. Ambiguous attribution remains excluded; this is not a log of every upstreamrequest. Null means no matching retained record, including eviction. A newer served,canceled or other record without a terminal error supersedes older error display.-Success uses exactly `{ok: true, contract_version: 11, provenance: TurnProvenance | null}`;+Success uses exactly `{ok: true, contract_version: 12, provenance: TurnProvenance | null}`;there is no `success` field or envelope exception.Local `engine_down` records may also contain `local_error_detail`, an OS-generated@@ -1411,7 +1413,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1420,7 +1422,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}diff --git a/docs/plans/model-hub-contracts/capability-evidence.schema.json b/docs/plans/model-hub-contracts/capability-evidence.schema.jsonnew file mode 100644index 000000000..f6a246aef--- /dev/null+++ b/docs/plans/model-hub-contracts/capability-evidence.schema.json@@ -0,0 +1,48 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/capability-evidence.schema.json",+ "title": "CapabilityEvidence",+ "description": "One persisted evidence record per (Source, model, feature) in the Model Hub state directory (model-hub-capability-model.md §3.1). Absence is unknown. Written only by a user-started probe or by a narrow classifier rule on a real upstream error.",+ "type": "object",+ "required": ["version", "source_id", "model_id", "feature", "status", "basis", "observed_at", "engine", "shape", "source_identity"],+ "additionalProperties": false,+ "properties": {+ "version": { "const": 1 },+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1 },+ "feature": {+ "oneOf": [+ {+ "type": "object",+ "required": ["kind", "name"],+ "additionalProperties": false,+ "properties": {+ "kind": { "const": "effort" },+ "name": { "type": "string", "pattern": "^[A-Za-z0-9_.-]{1,64}$" }+ }+ },+ {+ "type": "object",+ "required": ["kind", "name", "aspect"],+ "additionalProperties": false,+ "properties": {+ "kind": { "const": "hosted_tool" },+ "name": { "enum": ["web_search", "x_search", "image_generation"] },+ "aspect": { "enum": ["call", "replay"] }+ },+ "if": { "properties": { "name": { "const": "image_generation" } } },+ "then": { "properties": { "aspect": { "const": "call" } } }+ }+ ]+ },+ "status": { "enum": ["verified", "unsupported"] },+ "basis": { "enum": ["probe", "observed"] },+ "observed_at": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$" },+ "engine": { "type": "string", "minLength": 1, "description": "Engine release at that time; a different current engine makes probe evidence wire-stale." },+ "shape": { "type": "integer", "minimum": 0, "description": "Version of the request shape that produced the record; a different current shape makes probe evidence wire-stale." },+ "source_identity": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$", "description": "Digest of the Source identity at write time; a changed identity drops the record." },+ "detail": { "type": "string", "minLength": 1, "maxLength": 64, "description": "HTTP status and upstream machine code, never upstream text." }+ },+ "if": { "properties": { "basis": { "const": "observed" } } },+ "then": { "required": ["detail"], "properties": { "status": { "const": "unsupported" } } }+}diff --git a/docs/plans/model-hub-contracts/google-protocol.md b/docs/plans/model-hub-contracts/google-protocol.mdindex b33ef935f..89fc9f123 100644--- a/docs/plans/model-hub-contracts/google-protocol.md+++ b/docs/plans/model-hub-contracts/google-protocol.md@@ -1,6 +1,6 @@# Google protocol consumer extension-Normative for the v11 Model Hub contract. This extends the existing gateway,+Normative since the v11 Model Hub contract. This extends the existing gateway,EngineAdapter and pinned CPA transport; it does not add a provider implementationto agent-core, change backend registration, or upgrade the engine.diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex d691c8d6f..668fdd760 100644--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json@@ -61,7 +61,7 @@],"properties": {"ok": { "const": false },- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"error": {"enum": ["source_last_supplier",@@ -116,7 +116,7 @@"examples": [{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "source_model_in_route_chain","detail": "modelHub.errors.source_model_in_route_chain","would_remove_hops": [diff --git a/docs/plans/model-hub-contracts/hop-origin.schema.json b/docs/plans/model-hub-contracts/hop-origin.schema.jsonindex 8689986c3..2ccacbe27 100644--- a/docs/plans/model-hub-contracts/hop-origin.schema.json+++ b/docs/plans/model-hub-contracts/hop-origin.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/hop-origin.schema.json","title": "HopOrigin",- "description": "Upstream identity captured at admission. Serialized in x-avibe-served-hop and the same provenance attempt's origin.",+ "description": "Upstream identity captured at admission and persisted as the provenance attempt's origin, beside that attempt's source_id. The x-avibe-served-hop header carries these fields plus the Source id; see served-hop.schema.json.","type": "object","required": ["provider", "api", "model"],"additionalProperties": false,diff --git a/docs/plans/model-hub-contracts/hop-resolution.schema.json b/docs/plans/model-hub-contracts/hop-resolution.schema.jsonindex ae73b8a1c..0550b301e 100644--- a/docs/plans/model-hub-contracts/hop-resolution.schema.json+++ b/docs/plans/model-hub-contracts/hop-resolution.schema.json@@ -4,7 +4,7 @@"title": "HopResolution","description": "C-6 runtime consumer projection of ModelHubLaunch. Unknown planning metadata remains null; credentials are in-memory only.","type": "object",- "required": ["backend", "requested_model", "protocol", "base_url", "token", "runtime_model", "source_id", "provider", "request_headers", "capabilities"],+ "required": ["backend", "requested_model", "protocol", "base_url", "token", "runtime_model", "source_id", "provider", "request_headers", "capabilities", "hosted_tools"],"additionalProperties": false,"properties": {"backend": { "const": "vibey" },@@ -29,6 +29,216 @@"supports_reasoning": { "type": ["boolean", "null"] },"reasoning_efforts": { "type": "array", "items": { "type": "string" } }}+ },+ "hosted_tools": {+ "type": "object",+ "description": "One entry per hosted tool the user enabled (vibey-hosted-tools.md §3.5). `mode` is the primary hop's; `declaration` and `include` are the overlay's wire declaration, present exactly for native; `executor` is the proxy executor bound for this turn, present for every entry because a native request answered pin_unavailable is re-rendered with the proxy in the same turn; `replay` is true only for the primary hop Source's positive replay evidence taken on the current engine and probe shape. A request carrying native content is pinned with x-avibe-pin-source: source_id.",+ "propertyNames": {+ "enum": [+ "web_search",+ "x_search",+ "image_generation"+ ]+ },+ "additionalProperties": {+ "type": "object",+ "required": [+ "mode",+ "executor",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "mode": {+ "enum": [+ "native",+ "proxy"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "executor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ ]+ },+ "replay": {+ "type": "boolean"+ }+ },+ "if": {+ "properties": {+ "mode": {+ "const": "native"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "properties": {+ "image_generation": {+ "allOf": [+ {+ "type": "object",+ "required": [+ "mode",+ "executor",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "mode": {+ "enum": [+ "native",+ "proxy"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "executor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ ]+ },+ "replay": {+ "type": "boolean"+ }+ },+ "if": {+ "properties": {+ "mode": {+ "const": "native"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ {+ "properties": {+ "replay": {+ "const": false+ }+ }+ }+ ]+ }+ }}}}diff --git a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.jsonnew file mode 100644index 000000000..6384b87df--- /dev/null+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json@@ -0,0 +1,80 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/hosted-tools-status.schema.json",+ "title": "HostedToolsStatus",+ "description": "The Tools tab read (vibey-hosted-tools.md §6.1): each catalog tool's toggle and chosen executor, where it can run with that evidence, and how many hosted-tool probe records need a re-verify. A report only: hop resolution reads config and evidence itself.",+ "type": "object",+ "required": ["tools", "reverify"],+ "additionalProperties": false,+ "properties": {+ "tools": {+ "type": "array",+ "description": "Every catalog tool, in catalog order.",+ "items": {+ "type": "object",+ "required": ["name", "enabled", "executor", "candidates"],+ "additionalProperties": false,+ "properties": {+ "name": { "enum": ["web_search", "x_search", "image_generation"] },+ "enabled": { "type": "boolean" },+ "executor": {+ "description": "The executor the user chose, or null for the first verified candidate.",+ "oneOf": [+ { "type": "null" },+ {+ "type": "object",+ "required": ["source_id", "model_id"],+ "additionalProperties": false,+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1 }+ }+ }+ ]+ },+ "candidates": {+ "type": "array",+ "description": "Every (Source, model) the overlay offers the tool on, with an eligible credential and an untranslated path; Vibey's Source order first.",+ "items": {+ "type": "object",+ "required": ["source_id", "model_id", "call", "replay"],+ "additionalProperties": false,+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1 },+ "call": { "$ref": "#/definitions/Evidence" },+ "replay": {+ "description": "Null for image_generation, which is never replayed.",+ "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/Evidence" }]+ }+ }+ }+ }+ }+ }+ },+ "reverify": {+ "type": "object",+ "required": ["engine_upgraded", "aged"],+ "additionalProperties": false,+ "properties": {+ "engine_upgraded": { "type": "integer", "minimum": 0, "description": "Probe records taken on another engine or probe shape; they route as unknown." },+ "aged": { "type": "integer", "minimum": 0, "description": "Probe records older than 30 days; they still route." }+ }+ }+ },+ "definitions": {+ "Evidence": {+ "type": "object",+ "required": ["status", "stale", "basis", "observed_at", "detail"],+ "additionalProperties": false,+ "properties": {+ "status": { "enum": ["verified", "unsupported", "unknown"], "description": "As routing reads it." },+ "stale": { "enum": [null, "wire", "age"] },+ "basis": { "enum": [null, "probe", "observed"] },+ "observed_at": { "type": ["string", "null"] },+ "detail": { "type": ["string", "null"], "maxLength": 64 }+ }+ }+ }+}diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex 7007285ed..6e897811e 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -1,5 +1,5 @@{- "contract_version": 11,+ "contract_version": 12,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex 8ed7775a3..21efd8fb9 100644--- a/docs/plans/model-hub-contracts/observation-result.schema.json+++ b/docs/plans/model-hub-contracts/observation-result.schema.json@@ -16,7 +16,7 @@],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"outcome": {"enum": ["observed",@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 11,+ "contract_version": 12,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "timeout","reachable": null,"authenticated": "unknown",diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex 2baecdf0f..371ea43c6 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -66,10 +66,10 @@}],"examples": [- { "contract_version": 11, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },- { "contract_version": 11, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },- { "contract_version": 11, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },- { "contract_version": 11, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },- { "contract_version": 11, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }+ { "contract_version": 12, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 12, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },+ { "contract_version": 12, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },+ { "contract_version": 12, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 12, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }]}diff --git a/docs/plans/model-hub-contracts/provider-overlay.schema.json b/docs/plans/model-hub-contracts/provider-overlay.schema.jsonnew file mode 100644index 000000000..133b42bb4--- /dev/null+++ b/docs/plans/model-hub-contracts/provider-overlay.schema.json@@ -0,0 +1,112 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/provider-overlay.schema.json",+ "title": "ProviderOverlay",+ "description": "The providers section of vibe/data/backend_models.json (model-hub-capability-model.md §4): what each provider offers per model family and protocol. Priors only, read from the bundled file and never the remote catalog. Keys are canonical Source vendor ids. An invalid vendor entry is disabled with a warning.",+ "definitions": {+ "Token": {+ "type": "string",+ "pattern": "^\\S(?:.*\\S)?$",+ "description": "Nonblank, without surrounding whitespace."+ },+ "PriceComponent": {+ "type": "object",+ "required": ["unit", "usd_per_1k"],+ "additionalProperties": false,+ "properties": {+ "unit": { "enum": ["call", "search", "post", "profile"] },+ "usd_per_1k": { "type": "number", "minimum": 0 }+ }+ },+ "Price": {+ "type": "object",+ "description": "The provider's list price per 1,000 units, with the date and page it was read from.",+ "required": ["unit", "usd_per_1k", "as_of", "url"],+ "additionalProperties": false,+ "properties": {+ "unit": { "$ref": "#/definitions/PriceComponent/properties/unit" },+ "usd_per_1k": { "$ref": "#/definitions/PriceComponent/properties/usd_per_1k" },+ "as_of": { "type": "string", "format": "date", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" },+ "url": { "type": "string", "format": "uri", "pattern": "^https://[^\\s/?#]+(?:[/?#]\\S*)?$" },+ "extra": {+ "type": "array",+ "description": "Further units the same call is billed by, e.g. xAI x_search profiles beside posts.",+ "items": { "$ref": "#/definitions/PriceComponent" }+ }+ }+ },+ "HostedTool": {+ "type": "object",+ "required": ["declaration"],+ "additionalProperties": false,+ "properties": {+ "declaration": {+ "type": "object",+ "description": "Sent verbatim as the native tool declaration.",+ "required": ["type"],+ "properties": {+ "type": { "$ref": "#/definitions/Token" }+ }+ },+ "price": {+ "$ref": "#/definitions/Price",+ "description": "Absent when no list price is known, which is never a price of zero. OpenAI bills image generation per image token, so it has none."+ },+ "include": {+ "type": "array",+ "description": "Responses include values the tool needs, e.g. web_search_call.action.sources.",+ "items": { "$ref": "#/definitions/Token" },+ "uniqueItems": true+ }+ }+ },+ "ModelFamily": {+ "type": "object",+ "required": ["match"],+ "additionalProperties": false,+ "properties": {+ "match": {+ "type": "object",+ "description": "Compared with the normalized model id: prefix by startswith, id by equality.",+ "minProperties": 1,+ "maxProperties": 1,+ "additionalProperties": false,+ "properties": {+ "prefix": { "$ref": "#/definitions/Token" },+ "id": { "$ref": "#/definitions/Token" }+ }+ },+ "wire_efforts": {+ "type": ["array", "null"],+ "description": "Effort values the provider accepts on the wire. Null or absent defers to models.dev.",+ "items": { "$ref": "#/definitions/Token" },+ "uniqueItems": true+ },+ "hosted_tools": {+ "type": "object",+ "propertyNames": { "$ref": "source.schema.json#/properties/protocol" },+ "additionalProperties": {+ "type": "object",+ "propertyNames": { "enum": ["web_search", "x_search", "image_generation"] },+ "additionalProperties": { "$ref": "#/definitions/HostedTool" }+ }+ }+ }+ },+ "Vendor": {+ "type": "object",+ "required": ["models"],+ "additionalProperties": false,+ "properties": {+ "models": {+ "type": "array",+ "description": "Ordered; the first family that matches a model wins.",+ "items": { "$ref": "#/definitions/ModelFamily" }+ }+ }+ }+ },+ "type": "object",+ "propertyNames": { "pattern": "^[a-z0-9]+(?:[._-][a-z0-9]+)*$" },+ "additionalProperties": { "$ref": "#/definitions/Vendor" }+}diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 6b5e1c43d..6d03f3a6f 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "manifest", "status"],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"enabled": {"type": "boolean","description": "Persisted user intent for the managed gateway. Fresh/default configuration is true; explicit stop persists false."@@ -131,7 +131,7 @@},"examples": [{- "contract_version": 11,+ "contract_version": 12,"host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi",diff --git a/docs/plans/model-hub-contracts/served-hop.schema.json b/docs/plans/model-hub-contracts/served-hop.schema.jsonnew file mode 100644index 000000000..0514861b4--- /dev/null+++ b/docs/plans/model-hub-contracts/served-hop.schema.json@@ -0,0 +1,15 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/served-hop.schema.json",+ "title": "ServedHop",+ "description": "The exact x-avibe-served-hop response header value: the admitted attempt's origin plus the serving Source id, because two Sources can share an origin.",+ "type": "object",+ "required": ["provider", "api", "model", "source"],+ "additionalProperties": false,+ "properties": {+ "provider": { "type": "string", "minLength": 1 },+ "api": { "$ref": "source.schema.json#/properties/protocol" },+ "model": { "type": "string", "minLength": 1 },+ "source": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" }+ }+}diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 4730301fb..ff2d7a995 100644--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -36,7 +36,7 @@"additionalProperties": false,"properties": {"contract_version": {- "enum": [5, 6, 7, 8, 9, 10, 11],+ "enum": [5, 6, 7, 8, 9, 10, 11, 12],"$comment": "The only versioned object written to disk, so released versions form a set rather than a constant. Historical records validate after the existing persistence-read normalization of retired reasons; tests/fixtures/model_hub/released_v5_permission_denied.json exercises that boundary, not raw-file validation. Reading preserves the writer generation and requires no new route fields. New records carry the terminal member. Other versioned objects are ephemeral envelopes pinned to that value alone.","description": "Generation that wrote this record. Readers retain every supported released value, apply existing retired-reason normalization independently of version, and do not require route_origin or manual_override."},@@ -478,7 +478,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -503,7 +503,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -524,7 +524,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -544,7 +544,7 @@]},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -564,7 +564,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_modelmissing01","ts": "2026-09-05T17:31:10Z","agent": "claude",@@ -586,7 +586,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",diff --git a/docs/plans/model-hub-contracts/vibey-consumer.md b/docs/plans/model-hub-contracts/vibey-consumer.mdindex bd883d7a6..46907ecfa 100644--- a/docs/plans/model-hub-contracts/vibey-consumer.md+++ b/docs/plans/model-hub-contracts/vibey-consumer.md@@ -152,14 +152,17 @@ Every Vibey model response that the gateway serves carries the response header`x-avibe-served-hop`. Its value is compact ASCII-escaped JSON:```json-{"provider":"openai","api":"openai_responses","model":"upstream-model"}+{"provider":"openai","api":"openai_responses","model":"upstream-model","source":"src_relay9c1x"}```-The exact object is `hop-origin.schema.json`. The provider and protocol are-captured from the Source snapshot used at attempt admission, and the model is the-configured upstream target of that attempt. The same immutable `HopOrigin` travels-with `ResolvedInvocation` and the request's `AttemptIdentity`; successful settlement-stores it as the required `TurnProvenance.served.origin` for Vibey. Historical and+The exact object is `served-hop.schema.json`: exactly `provider`, `api`, `model`+and `source`, since contract v12. The provider and protocol are captured from the+Source snapshot used at attempt admission, the model is the configured upstream+target of that attempt, and `source` is that Source's id, because two Sources can+share an origin. The same immutable `HopOrigin` travels with `ResolvedInvocation`+and the request's `AttemptIdentity`; successful settlement stores its `provider`,+`api` and `model` (`hop-origin.schema.json`) as the required+`TurnProvenance.served.origin` for Vibey, beside the attempt's `source_id`. Historical andnative records may omit origin; Vibey has no pre-v11 historical record.Failed/canceled attempts can also retain that snapshot, without implying success.For a turn making several model requests, each response header names its owndiff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex f81170a98..85624c6ae 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -36,7 +36,7 @@ verified for X search.## 2. Concepts-- **One user-facing tool per capability.** Phase 1 has `web_search` and `x_search`.+- **One user-facing tool per capability.** Phase 1 has `web_search`, `x_search` and `image_generation`.- **Two execution modes behind one name and schema.**- **Native:** the provider's hosted declaration on the wire. The provider runs the search.- **Proxy:** a function with the canonical schema. Vibey's tool runtime asks the gateway's executor to run it.@@ -442,14 +442,16 @@ These rules become C-1 rows in `cross-provider.md` and per-protocol rows in `concontract change pending at that time joins it.- The gateway and the served-hop parser change in that same release.- **Phase 1's native mode therefore lands with or after v12.** Proxy mode does not depend on it.- - **The v12 bump edits these exact-shape contracts together:**- - `model-hub-contracts/hop-origin.schema.json`: add `source` (required);+ - **The v12 bump edited these exact-shape contracts together** (Phase 1 foundation PR):+ - `model-hub-contracts/served-hop.schema.json` (new): the header is exactly `provider`, `api`, `model`,+ `source`. `hop-origin.schema.json` stays the persisted provenance origin (`provider`, `api`, `model`), because+ provenance attempts already carry `source_id` beside it and records written at v5–11 must keep validating;- `model-hub-contracts/vibey-consumer.md`, Response origin;- `agent-core-contracts/provider.md`, the served-hop sentence;- - `agent-core-contracts/conversion-tables.md`, the Origin row ("exactly `provider`, `api`, `model`");+ - `agent-core-contracts/conversion-tables.md`, the Origin row;- `agent-core-contracts/model-hub-consumer.md`, item 4.- These files are frozen at v11, so this PR states the change and leaves their text alone.+ A message's C-1 `origin` stays exactly `provider`, `api`, `model`; the served `source` tags `native.source_id`.## 6. User interface@@ -610,8 +612,9 @@ Each has a **Re-verify** action with its cost. Unknown shows nothing.- OpenAI web search: $10 / 1k calls plus content tokens;- Anthropic: $10 / 1k searches plus result tokens, re-billed while they stay in context;- xAI: web search $5 / 1k calls, X search $5 / 1k posts and $10 / 1k profiles;- - OpenAI image generation: per image, by quality and size. The overlay records the vendor's table with its date- and URL, and the card shows the reported or list cost.+ - OpenAI image generation: OpenAI lists no per-image price; image generation is billed per image token at the+ image model's rate (2026-10-13 pricing page). The overlay's `image_generation` entry therefore has no list+ price, and the cost comes from the call's image-token usage at that rate (Phase 1 pricing PR).- **Relays** show list price, labelled as such, and may bill differently.- **Anthropic OAuth policy:** a Claude subscription Source is never probed and never runs a hosted tool, whethernatively or as proxy executor. Credential eligibility is checked before the probe, the native mode and the executor@@ -710,17 +713,22 @@ encoded either as a schema clause or as a producer test. The PR names which for`sources[]` entry requires `url`.4. `AssistantMessage.hosted_summary`:- it is present exactly when the message has a `HostedToolBlock`;+ - `counts` and `cited_sources` are required (possibly empty); `cost` is optional, absent when no price is known,+ because unknown is never priced as zero;- `cost.usd` is present exactly when `basis` is not `included`.5. `TextBlock.citations`: `start` and `end` come together.6. `ToolResultMessage.hosted` requires `record`. `execution` is present exactly when an executor ran; without it,`record.status` is `failed`.- - `execution` requires `mode: "proxy"`, `executor_origin`, `executor_source_id`, `executor_billing` and `cost`.+ - `execution` requires `mode: "proxy"`, `executor_origin`, `executor_source_id` and `executor_billing`; its+ `cost` is optional on the same rule as item 4.- `is_error` is `true` exactly when `record.status` is `failed` or `incomplete`.**C-6 `HopResolution.hosted_tools` (both copies):**7. Each entry requires `mode`, `replay` and `executor`.- `executor` is `{source_id, model_id}` or `null`, and is present for every entry whatever the mode.- - `declaration` is present exactly for `native`, and includes the overlay entry's `include` values.+ - `declaration` and `include` (the overlay entry's Responses `include` values, possibly empty) are present exactly+ for `native`.+ - `hosted_tools` itself is required, and empty when no tool is enabled.**Model Hub:**8. V2 `model_hub.hosted_tools`: keys are catalog tool names, and each entry requires `enabled` and `executor`.@@ -744,8 +752,9 @@ encoded either as a schema clause or as a producer test. The PR names which for16. Across `pause_turn` continuations, a result for a `pending` block finalizes that block by tool-call id. Themerged message has one `hosted_summary`, with summed `counts` and `cost.usd` and URL-deduplicated`cited_sources` (§4.3).-17. Image prices in the overlay are keyed variants: each `extra[]` entry for unit `image` carries `quality` and- `size`, and pricing selects the entry that matches the declaration that ran (capability model §4).+17. Image cost is valued from the call's image-token usage at the image model's per-token rate, because OpenAI+ lists no per-image price (capability model §4). If a vendor later lists per-image prices, those entries are+ keyed by the resolved `quality` and `size` (item 22).18. The image file a path record names fits `read`'s `MAX_INLINE_IMAGE_BYTES`, tested with a 6 MB generated image(§7.3).19. The executor binding is held for the turn. Only removal or disablement of the bound Source makes a call fail,@@ -753,3 +762,28 @@ encoded either as a schema clause or as a producer test. The PR names which for20. Hosted-tool `call` and `replay` evidence whose `engine` or `shape` differs from the current one resolves asunknown: proxy mode and synthetic replay. Age-only staleness keeps routing. Effort evidence is unchanged(capability model §3.3, §3.4).++**Added after review of the merged design (implementation-level, binding on the Phase 1 PRs):**++21. Continuations merge into one `AssistantMessage` only when the served-hop report shows the same origin. A+ `pin_unavailable` continuation served by another origin makes the merged message take the serving origin, and+ the paused part is kept in the portable form that was actually sent (§4.4 fallback, C-1 cross-origin rules), so+ no payload or signature from the first origin remains.+22. The `generate` action records the output's resolved `quality` and `size`; pricing uses those output values, not+ the declaration's.+23. The replay probe asks for a URL the call probe actually returned (such as the first). An answer with no earlier+ URL, or a refusal, is inconclusive; `unsupported` comes only from a 400 naming the replayed content or a new call+ to the tool.+24. For OpenAI and xAI executors, each source's `snippet` is the answer text its `url_citation` span covers, extended+ to the enclosing sentence; the executor instruction asks for one or two cited sentences per result so the spans+ align. A source without a span has no snippet; Anthropic keeps `cited_text`. Tested against a recorded executor+ response.+25. Each response has a maximum number of image events (final plus requested partials, plus a small margin) and a+ cumulative decoded-byte budget; exceeding either ends the stream as a provider error. The terminal duplicate is+ still discarded undecoded.+26. Context-tier thresholds use total context input: input plus cache-read and cache-write tokens.+27. The proxy endpoint returns a generated image's bytes to Vibey's tool runtime over the local hop. Vibey saves them+ through the same session media sink the native path uses, then builds the `HostedRecord` with the path record.+ The bytes are never persisted in a transcript, and Vibey stays the only writer of session media.+28. `generate.prompt` is required only for a `completed` record; a `failed` or `incomplete` record may omit it when+ the provider's `revised_prompt` is absent or null.diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex f111502ee..d8db96d6d 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -9,6 +9,7 @@ import jsonimport loggingimport osimport queue+import copyimport reimport shutilimport threading@@ -187,6 +188,8 @@ class ModelHubLaunch:provider: Optional[str] = Noneinput_limit: Optional[int] = Nonesupports_images: Optional[bool] = None+ # Vibey only: each enabled hosted tool's mode, declaration, executor and replay.+ hosted_tools: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)def to_hop_resolution(self) -> dict[str, Any]:"""Project C-6 from the same launch that owns routing and credentials."""@@ -216,6 +219,7 @@ class ModelHubLaunch:"supports_reasoning": self.supports_reasoning,"reasoning_efforts": list(self.reasoning_efforts),},+ "hosted_tools": copy.deepcopy({tool: dict(entry) for tool, entry in self.hosted_tools.items()}),}@property@@ -1322,7 +1326,7 @@ class ModelHubRuntimeRouter:via_mapping=False,gateway_request_model_id=runtime_model,primary_origin=(- HopOrigin(source.vendor, source.protocol, target_model)+ HopOrigin(source.vendor, source.protocol, target_model, source.id)if backend == "vibey" else None),)@@ -1363,6 +1367,12 @@ class ModelHubRuntimeRouter:if backend_model is not None and backend_model.input_modalitieselse None),+ hosted_tools=(+ # Off the controller loop: the first resolution loads the evidence file.+ await asyncio.to_thread(self.service.hosted_tools_for_hop, config, source, target_model)+ if backend == "vibey"+ else {}+ ),)self._emit_transition(launch, config)return launchdiff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.pyindex 9ed410f11..e47d5c290 100644--- a/tests/agent_core/ai/test_provider_adapters.py+++ b/tests/agent_core/ai/test_provider_adapters.py@@ -15,7 +15,7 @@ import core.agent_core.ai.anthropic as anthropic_moduleimport core.agent_core.ai.sse as sse_moduleimport core.agent_core.ai.openai_responses as responses_modulefrom core.agent_core.ai.anthropic import AnthropicAdapter, build_messages_payload-from core.agent_core.ai._common import OutputBudgetExceeded, StreamAssembler, read_response_body+from core.agent_core.ai._common import OutputBudgetExceeded, ServedHop, StreamAssembler, read_response_bodyfrom core.agent_core.ai.openai_chat import OpenAIChatAdapter, build_chat_payloadfrom core.agent_core.ai.openai_responses import OpenAIResponsesAdapter, build_responses_payloadfrom core.agent_core.ai.provider import (@@ -2814,8 +2814,32 @@ async def test_malformed_tool_arguments_are_terminal_invalid_requests() -> None:assert "malformed tool arguments" in error.message+_ORIGIN_KEYS = '"provider":"anthropic","api":"anthropic","model":"model-x"'++[email protected]("report,expected", [+ pytest.param(+ "{" + _ORIGIN_KEYS + ',"source":"src_fixture01"}',+ ServedHop(Origin("anthropic", "anthropic", "model-x"), "src_fixture01"),+ id="exact",+ ),+ pytest.param("{" + _ORIGIN_KEYS + "}", None, id="v11-without-source"),+ pytest.param("{" + _ORIGIN_KEYS + ',"source":"src_fixture01","extra":"x"}', None, id="extra-key"),+ pytest.param("{" + _ORIGIN_KEYS + ',"source":12345678}', None, id="non-string"),+ pytest.param("{" + _ORIGIN_KEYS + ',"source":"src_short"}', None, id="bad-source-id"),+ pytest.param(+ "{" + _ORIGIN_KEYS + ',"source":"src_fixture01","source":"src_fixture02"}', None, id="duplicate-key",+ ),+])+def test_served_hop_report_is_exactly_origin_and_source(report: str, expected: ServedHop | None) -> None:+ """MH-VIBEY-002: only the exact v12 report verifies an origin; any other shape leaves it unverified."""+ assert common_module.default_served_hop_resolver({"x-avibe-served-hop": report}) == expected++@pytest.mark.asyncio[email protected]("served_hop", [None, "invalid", '{"provider":"anthropic","api":"anthropic","model":"model-x"}'])[email protected]("served_hop", [+ None, "invalid", '{"provider":"anthropic","api":"anthropic","model":"model-x","source":"src_fixture01"}',+])async def test_gateway_origin_sanitization_preserves_streamed_block_indexes(served_hop: str | None) -> None:body = ('data: {"type":"message_start","message":{"usage":{}}}\n\n'@@ -3489,11 +3513,11 @@ class _StalledResolver:self.started = asyncio.Event()self.release = asyncio.Event()- async def __call__(self, headers: Mapping[str, str]) -> Origin | None:+ async def __call__(self, headers: Mapping[str, str]) -> ServedHop | None:del headersself.started.set()await self.release.wait()- return Origin("served", "openai_chat", "served-model")+ return ServedHop(Origin("served", "openai_chat", "served-model"), "src_served01")class _CloseFailStream(httpx.AsyncByteStream):@@ -3734,7 +3758,7 @@ async def test_http_error_classification_precedes_served_hop_resolution(resolver_calls = []closed = []- async def resolver(headers: Mapping[str, str]) -> Origin | None:+ async def resolver(headers: Mapping[str, str]) -> ServedHop | None:resolver_calls.append(headers)raise RuntimeError("served-hop resolution failed")diff --git a/tests/agent_core/test_hosted_messages.py b/tests/agent_core/test_hosted_messages.pynew file mode 100644index 000000000..7c119bc31--- /dev/null+++ b/tests/agent_core/test_hosted_messages.py@@ -0,0 +1,302 @@+"""C-1 hosted-tool shapes (``vibey-hosted-tools.md`` §4.2 and §12 items 1-6, 22, 28).++The dataclasses in ``core.agent_core.messages`` are the producer; ``message.schema.json``+is the contract other components read. Every invariant is checked twice: the schema and+the reader must refuse the same shapes, and what the producer writes must validate.+"""++from __future__ import annotations++import copy+import json+from pathlib import Path++import pytest+from jsonschema import Draft7Validator+from referencing import Registry, Resource++from core.agent_core.messages import (+ AssistantMessage,+ Citation,+ HostedAction,+ HostedCost,+ HostedImage,+ HostedNative,+ HostedRecord,+ HostedResult,+ HostedSource,+ HostedSummary,+ HostedToolBlock,+ Origin,+ ProxyExecution,+ TextBlock,+ ToolCallBlock,+ ToolResultMessage,+ message_from_dict,+ message_to_dict,+)++CONTRACTS = Path(__file__).resolve().parents[2] / "docs" / "plans" / "agent-core-contracts"+++def _validator() -> Draft7Validator:+ resources = {}+ for path in CONTRACTS.glob("*.schema.json"):+ value = json.loads(path.read_text())+ resources[value["$id"]] = Resource.from_contents(value)+ return Draft7Validator({"$ref": "agent-core/message.schema.json"}, registry=Registry().with_resources(resources.items()))+++VALIDATOR = _validator()+XAI = Origin(provider="xai", api="openai_responses", model="grok-4.6")+SOURCE = "src_x1a2b3c4d5"+POST = HostedSource(url="https://x.com/avibe/status/1", title="Avibe 本地优先", snippet="Agent OS 🚀 ships.")+++def _native(*items: dict) -> HostedNative:+ return HostedNative(source_id=SOURCE, payload=tuple(items))+++def _produced() -> list:+ """Messages as the adapters and the tool runtime will build them."""+ answer = "Avibe 是本地优先的 Agent OS。"+ native_turn = AssistantMessage(+ content=(+ HostedToolBlock(+ id="ws_1",+ tool="web_search",+ action=HostedAction(type="search", queries=("Avibe 本地优先", "avibe agent os")),+ record=HostedRecord(status="completed", sources=(HostedSource(url="https://avibe.bot", page_age="2 days"),)),+ native=_native({"type": "web_search_call", "id": "ws_1", "status": "completed"}),+ ),+ HostedToolBlock(+ id="op_1",+ tool="web_search",+ action=HostedAction(type="find_in_page", url="https://avibe.bot", pattern="local-first"),+ record=HostedRecord(status="incomplete", error="the page timed out"),+ native=_native({"type": "web_search_call", "id": "op_1"}),+ ),+ HostedToolBlock(+ id="xs_1",+ tool="x_search",+ action=HostedAction(type="x_search", variant="keyword", query="from:avibe", limit=10, mode="Latest"),+ record=HostedRecord(status="completed"),+ native=_native({"type": "custom_tool_call", "name": "x_keyword_search"}, {"type": "reasoning", "id": "tco_1"}),+ ),+ HostedToolBlock(+ id="xs_2",+ tool="x_search",+ action=HostedAction(type="other", name="x_bookmark_lookup"),+ record=HostedRecord(status="pending"),+ native=_native({"type": "custom_tool_call", "name": "x_bookmark_lookup"}),+ ),+ HostedToolBlock(+ id="ig_1",+ tool="image_generation",+ action=HostedAction(type="generate", prompt="一只猫, watercolor", size="1536x1024", quality="low"),+ record=HostedRecord(+ status="completed",+ images=(HostedImage(path="/tmp/media/image-3f2a.png", mime="image/png", width=1536, height=1024),),+ ),+ native=_native({"type": "image_generation_call", "result": "[image saved: /tmp/media/image-3f2a.png]"}),+ ),+ HostedToolBlock(+ id="ig_2",+ tool="image_generation",+ action=HostedAction(type="generate"),+ record=HostedRecord(status="failed", error="moderation_blocked", images=()),+ native=_native({"type": "image_generation_call", "status": "failed"}),+ ),+ TextBlock(+ text=answer,+ citations=(+ Citation(url="https://avibe.bot", title="Avibe", cited_text="本地优先", start=8, end=12),+ Citation(url="https://x.com/avibe/status/1"),+ ),+ ),+ ),+ origin=XAI,+ stop_reason="stop",+ hosted_summary=HostedSummary(+ counts={"web_search_calls": 2, "x_search_calls": 1, "x_posts_fetched": 10},+ cited_sources=(POST,),+ cost=HostedCost(basis="reported", usd=0.0412),+ ),+ )+ proxy_call = AssistantMessage(+ content=(ToolCallBlock(id="call_7", name="x_search", arguments={"query": "from:avibe", "limit": 5}),),+ origin=Origin(provider="anthropic", api="anthropic", model="claude-opus-5-5"),+ stop_reason="tool_use",+ )+ proxied = ToolResultMessage(+ tool_call_id="call_7",+ tool_name="x_search",+ content=(TextBlock(text="1. Avibe 本地优先 — https://x.com/avibe/status/1"),),+ hosted=HostedResult(+ record=HostedRecord(status="completed", sources=(POST,)),+ execution=ProxyExecution(+ executor_origin=XAI, executor_source_id=SOURCE, executor_billing="metered", cost=HostedCost(basis="list", usd=0.03)+ ),+ ),+ )+ included = ToolResultMessage(+ tool_call_id="call_8",+ tool_name="image_generation",+ content=(TextBlock(text="[image saved: /tmp/media/image-77.png · 1024x1024]"),),+ hosted=HostedResult(+ record=HostedRecord(status="completed", images=(HostedImage(path="/tmp/media/image-77.png", mime="image/webp"),)),+ execution=ProxyExecution(+ executor_origin=Origin(provider="openai", api="openai_responses", model="gpt-6-astra"),+ executor_source_id="src_o9p8q7r6s5",+ executor_billing="monthly",+ cost=HostedCost(basis="included"),+ ),+ ),+ )+ unexecuted = ToolResultMessage(+ tool_call_id="call_9",+ tool_name="web_search",+ content=(TextBlock(text="[web_search failed: verify web search on a Source in Models]"),),+ is_error=True,+ hosted=HostedResult(record=HostedRecord(status="failed", error="no verified executor")),+ )+ return [native_turn, proxy_call, proxied, included, unexecuted]++[email protected]("message", _produced(), ids=["native", "proxy-call", "proxied", "included", "unexecuted"])+def test_hosted_messages_the_producer_writes_match_the_schema_and_round_trip(message):+ payload = message_to_dict(message)+ VALIDATOR.validate(payload)+ assert message_from_dict(payload) == message+ assert message_to_dict(message_from_dict(payload)) == payload+++NATIVE = message_to_dict(_produced()[0])+PROXIED = message_to_dict(_produced()[2])+++def _without(payload: dict, path: tuple, field: str) -> dict:+ out = copy.deepcopy(payload)+ target = out+ for step in path:+ target = target[step]+ del target[field]+ return out+++MANDATORY = [+ (NATIVE, ("content", 0), "id"),+ (NATIVE, ("content", 0), "tool"),+ (NATIVE, ("content", 0), "action"),+ (NATIVE, ("content", 0), "record"),+ (NATIVE, ("content", 0), "native"),+ (NATIVE, ("content", 0, "native"), "source_id"),+ (NATIVE, ("content", 0, "native"), "payload"),+ (NATIVE, ("content", 0, "action"), "queries"),+ (NATIVE, ("content", 1, "action"), "pattern"),+ (NATIVE, ("content", 2, "action"), "variant"),+ (NATIVE, ("content", 2, "action"), "query"),+ (NATIVE, ("content", 3, "action"), "name"),+ (NATIVE, ("content", 0, "record"), "status"),+ (NATIVE, ("content", 0, "record"), "sources"),+ (NATIVE, ("content", 0, "record", "sources", 0), "url"),+ (NATIVE, ("content", 4, "record", "images", 0), "path"),+ (NATIVE, ("content", 4, "record", "images", 0), "mime"),+ (NATIVE, ("content", 6, "citations", 0), "url"),+ (NATIVE, ("hosted_summary",), "counts"),+ (NATIVE, ("hosted_summary",), "cited_sources"),+ (NATIVE, ("hosted_summary", "cost"), "basis"),+ (PROXIED, ("hosted",), "record"),+ (PROXIED, ("hosted", "execution"), "mode"),+ (PROXIED, ("hosted", "execution"), "executor_origin"),+ (PROXIED, ("hosted", "execution"), "executor_source_id"),+ (PROXIED, ("hosted", "execution"), "executor_billing"),+]++[email protected]("payload,path,field", MANDATORY, ids=[f"{'.'.join(map(str, p))}.{f}" for _, p, f in MANDATORY])+def test_every_mandatory_hosted_field_is_required_by_schema_and_reader(payload, path, field):+ broken = _without(payload, path, field)+ assert any(error.validator == "required" for error in VALIDATOR.iter_errors(broken) for error in [error, *(error.context or ())])+ with pytest.raises(ValueError):+ message_from_dict(broken)+++def _set(payload: dict, path: tuple, value) -> dict:+ out = copy.deepcopy(payload)+ target = out+ for step in path[:-1]:+ target = target[step]+ target[path[-1]] = value+ return out+++VIOLATIONS = {+ "error-on-completed": _set(NATIVE, ("content", 0, "record", "error"), "boom"),+ "failed-without-error": _without(NATIVE, ("content", 5, "record"), "error"),+ "error-too-long": _set(NATIVE, ("content", 1, "record", "error"), "x" * 401),+ "unknown-status": _set(NATIVE, ("content", 0, "record", "status"), "done"),+ "images-on-web-search": _set(NATIVE, ("content", 0, "record", "images"), []),+ "no-images-on-image-generation": _without(NATIVE, ("content", 4, "record"), "images"),+ "image-base64": _set(NATIVE, ("content", 4, "record", "images", 0, "b64_json"), "iVBORw0KGgo="),+ "generate-on-web-search": _set(NATIVE, ("content", 0, "action"), {"type": "generate", "prompt": "p"}),+ "search-on-x-search": _set(NATIVE, ("content", 2, "action"), {"type": "search", "queries": ["q"]}),+ "completed-generate-without-prompt": _without(NATIVE, ("content", 4, "action"), "prompt"),+ "unknown-action": _set(NATIVE, ("content", 0, "action"), {"type": "browse", "url": "https://a"}),+ "field-of-another-action": _set(NATIVE, ("content", 0, "action", "url"), "https://a"),+ "empty-queries": _set(NATIVE, ("content", 0, "action", "queries"), []),+ "x-search-limit-zero": _set(NATIVE, ("content", 2, "action", "limit"), 0),+ "x-search-mode": _set(NATIVE, ("content", 2, "action", "mode"), "latest"),+ "unknown-tool": _set(NATIVE, ("content", 0, "tool"), "code_interpreter"),+ "empty-payload": _set(NATIVE, ("content", 0, "native", "payload"), []),+ "payload-not-objects": _set(NATIVE, ("content", 0, "native", "payload"), ["web_search_call"]),+ "native-replay-flag": _set(NATIVE, ("content", 0, "native", "replay"), True),+ "bad-source-id": _set(NATIVE, ("content", 0, "native", "source_id"), "xai-key"),+ "summary-without-hosted-block": _set(message_to_dict(_produced()[1]), ("hosted_summary",), {"counts": {}, "cited_sources": []}),+ "hosted-block-without-summary": _without(NATIVE, (), "hosted_summary"),+ "included-with-usd": _set(NATIVE, ("hosted_summary", "cost"), {"basis": "included", "usd": 0.1}),+ "list-without-usd": _set(NATIVE, ("hosted_summary", "cost"), {"basis": "list"}),+ "negative-usd": _set(NATIVE, ("hosted_summary", "cost", "usd"), -0.01),+ "negative-count": _set(NATIVE, ("hosted_summary", "counts", "x_posts_fetched"), -1),+ "counter-name": _set(NATIVE, ("hosted_summary", "counts"), {"Web Search": 1}),+ "citation-start-only": _without(NATIVE, ("content", 6, "citations", 0), "end"),+ "citations-on-reference-text": _set(+ NATIVE, ("content", 6), {"type": "text", "ref": {"ref": "sha256:" + "a" * 64, "bytes": 9}, "citations": [{"url": "https://a"}]}+ ),+ "empty-citations": _set(NATIVE, ("content", 6, "citations"), []),+ "unexecuted-not-failed": _set(+ _set(_without(PROXIED, ("hosted",), "execution"), ("hosted", "record"), {"status": "incomplete", "error": "cut", "sources": []}),+ ("is_error",),+ True,+ ),+ "error-result-not-flagged": _set(+ _set(PROXIED, ("hosted", "record"), {"status": "failed", "error": "upstream 500", "sources": []}), ("is_error",), False+ ),+ "completed-result-flagged": _set(PROXIED, ("is_error",), True),+ "hosted-on-local-tool": _set(PROXIED, ("tool_name",), "bash"),+ "proxy-mode": _set(PROXIED, ("hosted", "execution", "mode"), "native"),+ "proxy-billing": _set(PROXIED, ("hosted", "execution", "executor_billing"), "free"),+ "proxy-images-on-x-search": _set(PROXIED, ("hosted", "record", "images"), []),+}++[email protected]("payload", list(VIOLATIONS.values()), ids=list(VIOLATIONS))+def test_schema_and_reader_refuse_the_same_hosted_violations(payload):+ assert not VALIDATOR.is_valid(payload)+ with pytest.raises(ValueError):+ message_from_dict(payload)+++def test_a_failed_generate_may_lack_the_revised_prompt():+ # Item 28: OpenAI may return a failed image_generation_call with no revised_prompt.+ failed = NATIVE["content"][5]+ assert "prompt" not in failed["action"] and failed["record"]["status"] == "failed"+ VALIDATOR.validate(NATIVE)+++def test_a_citation_range_must_lie_within_its_text():+ # The schema cannot compare a range with the text length; the producer and reader own it.+ with pytest.raises(ValueError):+ TextBlock(text="短", citations=(Citation(url="https://a", start=0, end=2),))+ with pytest.raises(ValueError):+ message_from_dict(_set(NATIVE, ("content", 6, "citations", 0, "end"), 99))diff --git a/tests/e2e/test_model_hub_google.py b/tests/e2e/test_model_hub_google.pyindex ca0877c48..c72830e76 100644--- a/tests/e2e/test_model_hub_google.py+++ b/tests/e2e/test_model_hub_google.py@@ -116,7 +116,7 @@ async def test_real_google_frontend_uses_pinned_engine_and_reports_serving_origiassert b"candidates" in rawassert b"mock response" in raw or b"Answer" in raworigin = json.loads(response.headers[SERVED_HOP_HEADER])- assert origin == {"provider": "custom", "api": protocol, "model": model_id}+ assert origin == {"provider": "custom", "api": protocol, "model": model_id, "source": source.id}completion = router.settle_turn("real-google", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-10-02T09:00:00Z",)@@ -124,7 +124,7 @@ async def test_real_google_frontend_uses_pinned_engine_and_reports_serving_origiawait completionrecord = service.provenance.get("real-google")assert record["outcome"] == "served", (record, raw)- assert record["served"]["origin"] == origin+ assert {**record["served"]["origin"], "source": record["served"]["source_id"]} == originassert len(requests) == 1path, body, headers = requests[0]assert "真实 fixture: 上海" in json.dumps(body, ensure_ascii=False)diff --git a/tests/e2e/test_model_hub_google_chat.py b/tests/e2e/test_model_hub_google_chat.pyindex 22b981995..4a490e63b 100644--- a/tests/e2e/test_model_hub_google_chat.py+++ b/tests/e2e/test_model_hub_google_chat.py@@ -117,7 +117,7 @@ async def _chat_gateway(tmp_path, monkeypatch, upstream, *, model="gemini-3-pro-}) as response:assert response.status == 200, await response.text()# Observed before the consumer reads any model body.- assert json.loads(response.headers[SERVED_HOP_HEADER]) == origin+ assert json.loads(response.headers[SERVED_HOP_HEADER]) == {**origin, "source": source.id}raw = await response.read()if not stream:return [json.loads(raw)]diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex 171306de1..f1fed0516 100644--- a/tests/e2e/test_model_hub_runtime.py+++ b/tests/e2e/test_model_hub_runtime.py@@ -684,7 +684,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(assert response.status == 404, (method, path, body)assert body == {"ok": False,- "contract_version": 11,+ "contract_version": 12,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex e39cba107..05b947220 100644--- a/tests/e2e/test_model_hub_sources.py+++ b/tests/e2e/test_model_hub_sources.py@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstreampytestmark = pytest.mark.e2e_model_hub-CONTRACT_VERSION = 11+CONTRACT_VERSION = 12MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex a053cf113..1064e356e 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -49,6 +49,10 @@ capabilities:- tests/scenario_harness/model_hub.pyunit_or_contract_tests:- tests/test_model_hub_api.py+ - tests/test_model_hub_hosted_tools_resolution.py+ - tests/test_model_hub_hosted_tools_config.py+ - tests/test_model_hub_capability_evidence.py+ - tests/test_provider_overlay.py- tests/test_model_hub_admission.py- tests/test_model_hub_vibey_consumer.py- tests/test_model_hub_config.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 9a79fcfcb..34406495e 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -5,6 +5,10 @@ capability:canonical_tests:- tests/test_model_hub_api.py- tests/test_model_hub_vibey_consumer.py+ - tests/test_model_hub_hosted_tools_resolution.py+ - tests/test_model_hub_hosted_tools_config.py+ - tests/test_model_hub_capability_evidence.py+ - tests/test_provider_overlay.py- tests/test_model_hub_config.py- tests/test_model_hub_legacy_opencode_migration.py- tests/test_member_management_parity.py@@ -132,12 +136,59 @@ scenarios:- tests/test_model_hub_vibey_consumer.py::test_served_hop_transport_bound_does_not_restrict_native_clients- tests/test_model_hub_vibey_consumer.py::test_slow_anthropic_resolution_waits_to_publish_origin_and_keeps_source_snapshot- tests/test_model_hub_vibey_consumer.py::test_concurrent_responses_keep_their_own_origin+ - tests/agent_core/ai/test_provider_adapters.py::test_served_hop_report_is_exactly_origin_and_source- id: MH-VIBEY-003name: Released three-backend configs gain only an empty Vibey Hub row without changing existing routesstatus: coveredkind: compatibilitylayer: contracttest: tests/test_model_hub_vibey_consumer.py::test_released_config_adds_only_empty_vibey_supply+ - id: MH-HOSTED-001+ name: Vibey hop resolution states each enabled hosted tool; native only on current-wire call evidence, an executor bound for every entry+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_vibey_consumer.py::test_hop_resolution_states_each_enabled_hosted_tool+ related_tests:+ - tests/test_model_hub_vibey_consumer.py::test_both_hop_resolution_copies_state_the_same_contract+ - tests/test_model_hub_hosted_tools_resolution.py::test_verified_call_makes_the_hop_native_and_binds_the_first_verified_executor+ - tests/test_model_hub_hosted_tools_resolution.py::test_evidence_from_another_engine_routes_as_proxy+ - tests/test_model_hub_hosted_tools_resolution.py::test_ineligible_or_translated_hops_never_go_native_or_execute+ - id: MH-HOSTED-002+ name: A broken hosted-tools config entry turns off only its tool, without the whole-section Model Hub reset+ status: covered+ kind: compatibility+ layer: contract+ test: tests/test_model_hub_hosted_tools_config.py::test_a_broken_hosted_tool_entry_turns_off_only_itself+ related_tests:+ - tests/test_model_hub_hosted_tools_config.py::test_disk_load_with_a_broken_hosted_tools_section_keeps_model_hub+ - tests/test_model_hub_hosted_tools_config.py::test_released_configs_load_with_every_tool_off_and_stay_without_the_section+ - id: MH-HOSTED-003+ name: Capability evidence resolves for routing; hosted-tool evidence from another engine or probe shape is unknown+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_capability_evidence.py::test_evidence_resolves_for_routing+ related_tests:+ - tests/test_model_hub_capability_evidence.py::test_a_changed_source_identity_reads_as_unknown_and_is_pruned+ - tests/test_model_hub_capability_evidence.py::test_persisted_records_match_the_schema_and_unreadable_ones_are_unknown+ - id: MH-HOSTED-004+ name: The Tools API reads every tool's candidates and evidence and writes one toggle without touching other Model Hub state+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_hosted_tools_config.py::test_the_tools_api_reads_and_writes_one_tool_at_a_time+ related_tests:+ - tests/test_model_hub_hosted_tools_resolution.py::test_status_lists_where_each_tool_can_run_and_counts_re_verifications+ - id: MH-HOSTED-005+ name: The bundled provider overlay resolves hosted-tool declarations, includes and prices; a broken vendor entry disables only that vendor+ status: covered+ kind: compatibility+ layer: contract+ test: tests/test_provider_overlay.py::test_bundled_overlay_resolves_hosted_tools+ related_tests:+ - tests/test_provider_overlay.py::test_bundled_providers_section_satisfies_its_schema+ - tests/test_provider_overlay.py::test_an_invalid_vendor_entry_disables_only_that_vendor- id: MH-VIBEY-007name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source existsstatus: covereddiff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.pyindex 40f65bdf4..47b18bc4b 100644--- a/tests/test_backend_model_catalog.py+++ b/tests/test_backend_model_catalog.py@@ -143,6 +143,11 @@ def test_backend_model_entries_normalize_runtime_catalog_shape():{"effort": "ultra"},],},+ {+ "id": "gpt-6-astra",+ "reasoning_efforts": ["high", "ultra"],+ "client_presets": ["ultra", "turbo", "ultra"],+ },]}},@@ -156,9 +161,64 @@ def test_backend_model_entries_normalize_runtime_catalog_shape():"visibility": "list","reasoning_efforts": ["low", "ultra"],},+ {+ "id": "gpt-6-astra",+ "reasoning_efforts": ["high", "ultra"],+ "client_presets": ["ultra"],+ },]+def test_bundled_client_presets_name_codex_ultra_without_leaving_its_menu():+ presets = backend_model_catalog.bundled_catalog_client_presets_by_model()+ efforts = backend_model_catalog.bundled_catalog_reasoning_efforts_by_model()++ assert dict(presets) == {+ "gpt-6-astra": ("ultra",),+ "gpt-5.6-sol": ("ultra",),+ "gpt-5.6-terra": ("ultra",),+ }+ assert all("ultra" in efforts[model] for model in presets)+ assert backend_model_catalog._read_complete_catalog(+ backend_model_catalog.get_bundled_catalog_path()+ )+ with pytest.raises(TypeError):+ presets["gpt-6-astra"] = ()+++ "providers",+ [+ pytest.param("bundled", id="bundled"),+ pytest.param([], id="not-an-object"),+ pytest.param({"xai": {"models": [{"match": {}}]}}, id="invalid-vendor"),+ pytest.param({"openai": {"models": [], "future_field": 1}}, id="unknown-shape"),+ ],+)+def test_providers_section_never_changes_backend_rows(monkeypatch, tmp_path, providers):+ bundled = json.loads(+ backend_model_catalog.get_bundled_catalog_path().read_text(encoding="utf-8")+ )+ without = {key: value for key, value in bundled.items() if key != "providers"}+ with_providers = {+ **without,+ "providers": bundled["providers"] if providers == "bundled" else providers,+ }+ path = tmp_path / "backend_models.json"+ path.write_text(json.dumps(with_providers), encoding="utf-8")+ payloads = iter([without, with_providers])+ monkeypatch.setattr(+ backend_model_catalog.urllib.request,+ "urlopen",+ lambda request, timeout: _FakeResponse(next(payloads)),+ )++ rows = backend_model_catalog.fetch_remote_catalog("https://example.test/catalog.json")++ assert backend_model_catalog.fetch_remote_catalog("https://example.test/catalog.json") == rows+ assert backend_model_catalog.load_bundled_catalog(path) == rows++def test_codex_hub_catalog_projects_complete_catalog(monkeypatch, tmp_path):runtime_dir = tmp_path / "runtime"monkeypatch.setattr(backend_model_catalog.paths, "get_runtime_dir", lambda: runtime_dir)@@ -1343,6 +1403,9 @@ def test_fetch_remote_catalog_rejects_invalid_model_entries(monkeypatch):({"id": "gpt-invalid", "visibility": "sometimes"}, "invalid visibility"),({"id": "gpt-invalid", "priority": "first"}, "invalid priority"),({"id": "gpt-invalid", "reasoning_efforts": "ultra"}, "invalid reasoning efforts"),+ ({"id": "gpt-invalid", "reasoning_efforts": ["high"], "client_presets": ["ultra"]}, "invalid client presets"),+ ({"id": "gpt-invalid", "client_presets": ["ultra"]}, "invalid client presets"),+ ({"id": "gpt-invalid", "reasoning_efforts": ["ultra"], "client_presets": "ultra"}, "invalid client presets"),],)def test_fetch_remote_catalog_rejects_malformed_model_metadata(monkeypatch, model_entry, error):diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex 2b45c8bc2..e94652d3c 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 281+ assert len(endpoints) == 283assert http_authorization_policy("POST", "/api/desktop-mini/session").minimum_role == "editor"assert http_authorization_policy("GET", "/api/desktop/capabilities").minimum_role == "member"assert http_authorization_policy("GET", "/api/desktop/computer-use/status").minimum_role == "member"diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 1c0650d18..cb33f765a 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1031,7 +1031,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):assert adapter.start_calls == 1assert store.config.enabled is Trueassert runtime["enabled"] is True- assert runtime["contract_version"] == 11+ assert runtime["contract_version"] == 12assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1338,7 +1338,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 11, "status": {"health": "ok"}}+ return {"contract_version": 12, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1355,7 +1355,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 11, "status": {"health": "not_started"}}+ return {"contract_version": 12, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1372,7 +1372,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 11, "status": {"health": "installing"}}+ return {"contract_version": 12, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1390,7 +1390,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypatdef rpc(operation, payload=None):calls.append((operation, payload))return {- "contract_version": 11,+ "contract_version": 12,"changed": True,"status": {"health": "not_started", "verified": True},}@@ -4807,7 +4807,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):assert response.status_code == 200assert response.get_json() == {"ok": True,- "contract_version": 11,+ "contract_version": 12,"agent": {"backend": "codex","mode": "hub",@@ -9686,7 +9686,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tassert accepted.status_code == 200runtime = accepted.get_json()["runtime"]assert adapter.start_calls == 1- assert runtime["contract_version"] == 11+ assert runtime["contract_version"] == 12_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_capability_evidence.py b/tests/test_model_hub_capability_evidence.pynew file mode 100644index 000000000..98d462dd8--- /dev/null+++ b/tests/test_model_hub_capability_evidence.py@@ -0,0 +1,186 @@+"""Capability evidence store (``model-hub-capability-model.md`` §3, jsH stale rule).++The store is the only routing truth for hosted tools and the only negative+truth for efforts, so its resolution table is pinned here at its owning boundary.+"""++from __future__ import annotations++import json+from dataclasses import replace+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest+from jsonschema import Draft7Validator+from referencing import Registry, Resource++from config.v2_config import ModelHubModelConfig, ModelHubSourceConfig, ModelHubSourceStateConfig+from core.handlers.model_hub.capability_evidence import (+ CapabilityEvidenceStore,+ EvidenceFeature,+ EvidenceRecord,+ identity_digest,+ resolve,+)++CONTRACTS = Path(__file__).parents[1] / "docs/plans/model-hub-contracts"+NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)+ENGINE = "model-hub-engine-v8.0.23-3"+++def _source(source_id: str = "src_xai00001", **changes) -> ModelHubSourceConfig:+ source = ModelHubSourceConfig(+ id=source_id,+ kind="api_key",+ vendor="xai",+ display_name="xAI 密钥",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="grok-4.6", provenance="discovered")],+ credential_ref=f"cred_{source_id}",+ )+ return replace(source, **changes)+++def _record(source: ModelHubSourceConfig, feature: EvidenceFeature, **changes) -> EvidenceRecord:+ fields = dict(+ source_id=source.id,+ model_id="grok-4.6",+ feature=feature,+ status="verified",+ basis="probe",+ observed_at=NOW,+ engine=ENGINE,+ shape=1,+ source_identity=identity_digest(source),+ )+ fields.update(changes)+ return EvidenceRecord(**fields)+++CALL = EvidenceFeature.hosted("x_search", "call")+REPLAY = EvidenceFeature.hosted("web_search", "replay")+ULTRA = EvidenceFeature.effort("ultra")+DAYS = timedelta(days=1)++# (case, feature, record changes, current engine, current shape, age) -> (routing status, stale)+RESOLUTION = [+ ("fresh-verified-call", CALL, {}, ENGINE, 1, 0 * DAYS, "verified", None),+ ("probe-unsupported-call", CALL, {"status": "unsupported"}, ENGINE, 1, 0 * DAYS, "unsupported", None),+ ("engine-upgrade-call-is-unknown", CALL, {}, "model-hub-engine-v8.0.24-1", 1, 0 * DAYS, "unknown", "wire"),+ ("shape-change-replay-is-unknown", REPLAY, {}, ENGINE, 2, 0 * DAYS, "unknown", "wire"),+ ("old-call-still-routes", CALL, {}, ENGINE, 1, 31 * DAYS, "verified", "age"),+ ("engine-upgrade-effort-negative-still-applies", ULTRA, {"status": "unsupported"}, "model-hub-engine-v9", 1, 0 * DAYS, "unsupported", "wire"),+ ("observed-negative-within-ttl", ULTRA, {"status": "unsupported", "basis": "observed", "detail": "400 invalid_value"}, "model-hub-engine-v9", 1, 6 * DAYS, "unsupported", None),+ ("observed-negative-expires", CALL, {"status": "unsupported", "basis": "observed", "detail": "400 invalid_request_error"}, ENGINE, 1, 8 * DAYS, "unknown", None),+]+++ "feature,changes,engine,shape,age,status,stale",+ [case[1:] for case in RESOLUTION],+ ids=[case[0] for case in RESOLUTION],+)+def test_evidence_resolves_for_routing(feature, changes, engine, shape, age, status, stale):+ """MH-HOSTED-003: probe and observed evidence resolve for routing, with the jsH stale rule."""+ source = _source()+ record = _record(source, feature, **changes)+ view = resolve(record, source=source, engine=engine, shape=shape, now=NOW + age)+ assert (view.status, view.stale) == (status, stale)+++def test_a_changed_source_identity_reads_as_unknown_and_is_pruned(tmp_path):+ store = CapabilityEvidenceStore(tmp_path / "model_hub_capability_evidence.json")+ keep, rekeyed = _source("src_keep0001"), _source("src_swap0001")+ store.write(_record(keep, CALL), live=[keep, rekeyed])+ store.write(_record(rekeyed, CALL), live=[keep, rekeyed])++ replaced = replace(rekeyed, credential_ref="cred_rotated")+ assert store.view(replaced, "grok-4.6", CALL, engine=ENGINE, shape=1, now=NOW).status == "unknown"+ assert store.view(keep, "grok-4.6", CALL, engine=ENGINE, shape=1, now=NOW).status == "verified"++ store.write(_record(keep, REPLAY), live=[keep, replaced])+ assert {record.source_id for record in store.records()} == {"src_keep0001"}+ with pytest.raises(ValueError):+ store.write(_record(rekeyed, CALL), live=[keep, replaced])+++def test_persisted_records_match_the_schema_and_unreadable_ones_are_unknown(tmp_path):+ path = tmp_path / "model_hub_capability_evidence.json"+ store = CapabilityEvidenceStore(path)+ source = _source()+ store.write(_record(source, CALL), live=[source])+ store.write(+ _record(source, ULTRA, status="unsupported", basis="observed", detail="400 invalid_value"), live=[source]+ )+ schema = json.loads((CONTRACTS / "capability-evidence.schema.json").read_text())+ validator = Draft7Validator(+ schema,+ registry=Registry().with_resources(+ [(schema["$id"], Resource.from_contents(schema))]+ ),+ )+ written = json.loads(path.read_text())+ for payload in written:+ validator.validate(payload)++ written.append({**written[0], "status": "maybe"})+ written.append({**written[0], "feature": {"kind": "hosted_tool", "name": "image_generation", "aspect": "replay"}})+ path.write_text(json.dumps(written))+ assert len(CapabilityEvidenceStore(path).records()) == 2+ assert not validator.is_valid(written[2]) and not validator.is_valid(written[3])+++ "changes",+ [+ {"basis": "observed"},+ {"basis": "observed", "status": "verified", "detail": "400 x"},+ {"detail": "x" * 65},+ {"observed_at": datetime(2026, 10, 13)},+ {"shape": -1},+ {"source_identity": ""},+ ],+ ids=["observed-without-detail", "observed-positive", "long-detail", "naive-time", "negative-shape", "no-identity"],+)+def test_a_record_refuses_what_the_contract_forbids(changes):+ with pytest.raises(ValueError):+ _record(_source(), CALL, **changes)+++def test_image_generation_has_no_replay_evidence():+ with pytest.raises(ValueError):+ EvidenceFeature.hosted("image_generation", "replay")+++def test_lookups_after_the_first_read_never_touch_the_disk(tmp_path, monkeypatch):+ """MH-HOSTED-003: the request path reads evidence from memory, never from the file."""+ path = tmp_path / "model_hub_capability_evidence.json"+ source = _source()+ CapabilityEvidenceStore(path).write(_record(source, CALL), live=[source])+ store = CapabilityEvidenceStore(path)+ assert len(store.records()) == 1++ touched = []+ original_stat, original_read = Path.stat, Path.read_text++ def stat(self, *args, **kwargs):+ if self == path:+ touched.append("stat")+ return original_stat(self, *args, **kwargs)++ def read_text(self, *args, **kwargs):+ if self == path:+ touched.append("read")+ return original_read(self, *args, **kwargs)++ monkeypatch.setattr(Path, "stat", stat)+ monkeypatch.setattr(Path, "read_text", read_text)+ for _ in range(50):+ assert store.view(source, "grok-4.6", CALL, engine=ENGINE, shape=1, now=NOW).status == "verified"+ store.write(_record(source, REPLAY), live=[source])+ assert store.view(source, "grok-4.6", REPLAY, engine=ENGINE, shape=1, now=NOW).status == "verified"+ assert touched == []diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 99aa4defe..5b146f809 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -96,7 +96,7 @@ def test_auto_detect_asks_for_responses_before_chat():def test_unsaved_observation_schema_closes_all_terminal_shapes():schema = _schema("observation-result.schema.json")- assert schema["properties"]["contract_version"]["const"] == 11+ assert schema["properties"]["contract_version"]["const"] == 12assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -120,7 +120,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():def payload(observation: SourceObservation) -> dict:return {- "contract_version": 11,+ "contract_version": 12,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -700,7 +700,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 11,+ "contract_version": 12,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -716,7 +716,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 11,+ "contract_version": 12,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -800,7 +800,7 @@ def test_v8_mirror_registry_is_executable_and_complete():registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))schemas = _mirror_schemas(registry)- assert registry["contract_version"] == 11+ assert registry["contract_version"] == 12ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -937,8 +937,8 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp"kind": "contract_version_schema_drift","domain": "V1","file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",- "values": [6, 7, 8, 9, 10, 11],- "expected": [5, 6, 7, 8, 9, 10, 11],+ "values": [6, 7, 8, 9, 10, 11, 12],+ "expected": [5, 6, 7, 8, 9, 10, 11, 12],} in result["findings"]@@ -1249,7 +1249,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(interrupted)exact_hop = {- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-opus-4-6","manual_override": None,@@ -1410,6 +1410,8 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmbackend: ModelHubAgentSupplyConfig.default(backend, mode="hub").to_payload()for backend in AGENT_BACKENDS},+ # Omitted while empty, so populate it to exercise its serializer.+ "hosted_tools": {"web_search": {"enabled": True, "executor": None}},}config = default_config()config.model_hub = ModelHubConfig.from_payload(hub_payload)diff --git a/tests/test_model_hub_google.py b/tests/test_model_hub_google.pyindex dd35b65ee..316cad99b 100644--- a/tests/test_model_hub_google.py+++ b/tests/test_model_hub_google.py@@ -339,6 +339,7 @@ async def test_google_router_gateway_failover_preserves_visible_history_and_origorigin = json.loads(response.headers[SERVED_HOP_HEADER])assert origin == {"provider": "custom", "api": fallback.protocol, "model": fallback.models[0].id,+ "source": fallback.id,}assert service.adapter.requests[0] == signedassert service.adapter.requests[1] == (signed if same_origin else plain)@@ -350,7 +351,7 @@ async def test_google_router_gateway_failover_preserves_visible_history_and_origawait completionrecord = service.provenance.get("turn-google")_validate("turn-provenance.schema.json", record)- assert record["served"]["origin"] == origin+ assert {**record["served"]["origin"], "source": record["served"]["source_id"]} == originfinally:await gateway.close()diff --git a/tests/test_model_hub_hosted_tools_config.py b/tests/test_model_hub_hosted_tools_config.pynew file mode 100644index 000000000..31feb7fe7--- /dev/null+++ b/tests/test_model_hub_hosted_tools_config.py@@ -0,0 +1,176 @@+"""V2 ``model_hub.hosted_tools`` (``vibey-hosted-tools.md`` §3.3, §12 item 8).++Hosted tools are an optional feature inside the Model Hub section. Released+configs never carry them, and a broken entry must turn off only that tool:+the rest of ``model_hub`` (Sources, Agents) has to load untouched, never through+the whole-section recovery reset.+"""++from __future__ import annotations++import copy+import json+import logging+from pathlib import Path++import pytest++from config.v2_config import ModelHubConfig, ModelHubHostedToolConfig, ModelHubRouteHopConfig, V2Config+from core.services.settings import default_config+from vibe import api++FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"+SOURCE = {+ "id": "src_xai00001",+ "kind": "api_key",+ "vendor": "xai",+ "display_name": "xAI 密钥",+ "protocol": "openai_responses",+ "supply_channel": "hub",+ "billing": "metered",+ "state": {"status": "standby", "retry_at": None, "detail_key": None},+ "models": [{"id": "grok-4.6", "display_name": "Grok 4.6", "origin": "discovered", "reasoning_efforts": [], "reasoning_efforts_source": None}],+ "created_at": "2026-10-13T00:00:00Z",+ "credential_ref": "cred_src_xai00001",+}+++def _section(hosted_tools) -> dict:+ section = ModelHubConfig.from_payload({"sources": [SOURCE]}).to_payload()+ if hosted_tools is not ...:+ section["hosted_tools"] = hosted_tools+ return section+++def test_released_configs_load_with_every_tool_off_and_stay_without_the_section():+ section = json.loads((FIXTURES / "released_pre_vibey_consumer.json").read_text(encoding="utf-8"))+ config = ModelHubConfig.from_payload(section, repairing=True)+ assert config.hosted_tools == {}+ assert "hosted_tools" not in config.to_payload()+++def test_hosted_tool_toggles_round_trip_in_canonical_order():+ tools = {+ "x_search": {"enabled": False, "executor": None},+ "web_search": {"enabled": True, "executor": {"source_id": "src_xai00001", "model_id": "grok-4.6"}},+ }+ config = ModelHubConfig.from_payload(_section(tools))+ assert config.hosted_tools == {+ "web_search": ModelHubHostedToolConfig(True, ModelHubRouteHopConfig("src_xai00001", "grok-4.6")),+ "x_search": ModelHubHostedToolConfig(False, None),+ }+ assert list(config.to_payload()["hosted_tools"]) == ["web_search", "x_search"]+ assert ModelHubConfig.from_payload(config.to_payload()).to_payload() == config.to_payload()+++GOOD = {"enabled": True, "executor": None}+# (case, raw section, tools that survive as (enabled, executor), whether a warning is logged)+DEGRADED = [+ ("not-an-object", ["web_search"], {}, True),+ ("unknown-tool", {"code_interpreter": GOOD, "web_search": GOOD}, {"web_search": (True, None)}, True),+ ("missing-executor", {"web_search": {"enabled": True}, "x_search": GOOD}, {"x_search": (True, None)}, True),+ ("extra-field", {"web_search": {**GOOD, "replay": True}}, {}, True),+ ("non-boolean-enabled", {"web_search": {"enabled": "yes", "executor": None}}, {}, True),+ ("bad-executor-shape", {"web_search": {"enabled": True, "executor": {"source_id": "xai"}}}, {}, True),+ (+ "executor-source-gone",+ {"web_search": {"enabled": True, "executor": {"source_id": "src_gone0001", "model_id": "grok-4.6"}}},+ {"web_search": (True, None)},+ False,+ ),+ (+ "executor-model-gone",+ {"x_search": {"enabled": True, "executor": {"source_id": "src_xai00001", "model_id": "grok-3"}}},+ {"x_search": (True, None)},+ False,+ ),+]++[email protected]("raw,expected,warns", [case[1:] for case in DEGRADED], ids=[case[0] for case in DEGRADED])+def test_a_broken_hosted_tool_entry_turns_off_only_itself(raw, expected, warns, caplog):+ """MH-HOSTED-002: a broken entry turns off only its tool; Sources and Agents still load."""+ with caplog.at_level(logging.WARNING, logger="config.v2_config"):+ config = ModelHubConfig.from_payload(_section(raw))+ assert [source.id for source in config.sources] == ["src_xai00001"]+ assert {tool: (entry.enabled, entry.executor) for tool, entry in config.hosted_tools.items()} == expected+ assert bool(caplog.records) == warns+++def test_disk_load_with_a_broken_hosted_tools_section_keeps_model_hub(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ payload["model_hub"] = _section({"web_search": {"enabled": 1, "executor": None}, "x_search": GOOD})+ config_path = tmp_path / "config.json"+ original = json.dumps(payload)+ config_path.write_text(original, encoding="utf-8")++ loaded = V2Config.load(config_path=config_path)++ assert not loaded.load_warnings+ assert [source.id for source in loaded.model_hub.sources] == ["src_xai00001"]+ assert set(loaded.model_hub.hosted_tools) == {"x_search"}+ assert config_path.read_text(encoding="utf-8") == original+ assert not list(tmp_path.glob("config.json.bak-recovery-*"))+++def test_hosted_tools_never_hold_credential_material():+ section = _section({"web_search": {"enabled": True, "executor": {"source_id": "src_xai00001", "model_id": "sk-live-abc"}}})+ config = ModelHubConfig.from_payload(copy.deepcopy(section))+ assert "web_search" not in config.hosted_tools+++def _api_service(tmp_path):+ from config.v2_config import ModelHubSourceConfig+ from tests.test_model_hub_api import _service++ service, store, _adapter = _service(tmp_path)+ store.config = ModelHubConfig.from_payload(+ {+ "sources": [+ SOURCE,+ {**SOURCE, "id": "src_gem00001", "vendor": "custom", "protocol": "google", "credential_ref": "cred_g",+ "models": [{**SOURCE["models"][0], "id": "gemini-3-pro"}]},+ ]+ }+ )+ assert all(isinstance(source, ModelHubSourceConfig) for source in store.config.sources)+ return service, store+++async def test_the_tools_api_reads_and_writes_one_tool_at_a_time(tmp_path):+ """MH-HOSTED-004: the Tools tab writes one toggle; nothing else in Model Hub changes."""+ from core.handlers.model_hub.service import ModelHubError++ service, store = _api_service(tmp_path)+ before = store.config.to_payload()++ status = service.hosted_tools_status()["hosted_tools"]+ assert [tool["name"] for tool in status["tools"]] == ["web_search", "x_search", "image_generation"]+ assert not any(tool["enabled"] for tool in status["tools"])+ x_search = next(tool for tool in status["tools"] if tool["name"] == "x_search")+ assert [(c["source_id"], c["model_id"], c["call"]["status"]) for c in x_search["candidates"]] == [+ ("src_xai00001", "grok-4.6", "unknown")+ ]+ assert status["reverify"] == {"engine_upgraded": 0, "aged": 0}++ executor = {"source_id": "src_xai00001", "model_id": "grok-4.6"}+ written = await service.set_hosted_tool("x_search", {"enabled": True, "executor": executor})+ after = store.config.to_payload()+ assert after.pop("hosted_tools") == {"x_search": {"enabled": True, "executor": executor}}+ assert after == before+ assert next(tool for tool in written["hosted_tools"]["tools"] if tool["name"] == "x_search")["executor"] == executor++ for tool, body, code, status_code in [+ ("code_interpreter", {"enabled": True, "executor": None}, "invalid_parameter", 400),+ ("web_search", {"enabled": True}, "invalid_parameter", 400),+ ("web_search", {"enabled": True, "executor": {"source_id": "src_gone0001", "model_id": "x"}}, "source_not_found", 404),+ ("web_search", {"enabled": True, "executor": {"source_id": "src_gem00001", "model_id": "gemini-3-pro"}}, "invalid_parameter", 400),+ ("web_search", {"enabled": True, "executor": {"source_id": "src_xai00001", "model_id": "grok-3"}}, "invalid_parameter", 400),+ ("image_generation", {"enabled": True, "executor": executor}, "invalid_parameter", 400),+ ]:+ with pytest.raises(ModelHubError) as refused:+ await service.set_hosted_tool(tool, body)+ assert (refused.value.code, refused.value.status) == (code, status_code), (tool, body)+ assert store.config.to_payload()["hosted_tools"] == {"x_search": {"enabled": True, "executor": executor}}diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.pynew file mode 100644index 000000000..30b727601--- /dev/null+++ b/tests/test_model_hub_hosted_tools_resolution.py@@ -0,0 +1,239 @@+"""Hosted-tool hop resolution (``vibey-hosted-tools.md`` §3.4, §3.5; §12 items 7, 14, 19, 20).++Native is reachable only through positive evidence on the current wire, an+eligible credential and an untranslated path; everything else is the proxy.+The executor is bound for every enabled tool, whatever the mode.+"""++from __future__ import annotations++import json+from dataclasses import replace+from datetime import datetime, timezone++import pytest++from config.v2_config import (+ ModelHubAgentSupplyConfig,+ ModelHubConfig,+ ModelHubHostedToolConfig,+ ModelHubModelConfig,+ ModelHubRouteHopConfig,+ ModelHubSourceConfig,+ ModelHubSourceStateConfig,+)+from core.handlers.model_hub.capability_evidence import (+ CapabilityEvidenceStore,+ EvidenceFeature,+ EvidenceRecord,+ identity_digest,+)+from core.handlers.model_hub.hosted_tools import hosted_tools_status, resolve_hosted_tools+from vibe.backend_model_catalog import HostedToolSpec++NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)+ENGINE = "model-hub-engine-v8.0.23-3"+++def _spec(declaration: dict, include: tuple[str, ...] = ()) -> HostedToolSpec:+ return HostedToolSpec(declaration_json=json.dumps(declaration), price=None, include=include)+++SPECS = {+ ("xai", "openai_responses", "web_search"): _spec({"type": "web_search"}),+ ("xai", "openai_responses", "x_search"): _spec({"type": "x_search"}),+ ("openai", "openai_responses", "web_search"): _spec({"type": "web_search"}, ("web_search_call.action.sources",)),+ ("openai", "openai_responses", "image_generation"): _spec({"type": "image_generation", "partial_images": 2}),+ ("anthropic", "anthropic", "web_search"): _spec({"type": "web_search_20250305", "name": "web_search"}),+ ("google", "google", "web_search"): _spec({"type": "google_search"}),+}+++def _spec_for(vendor, protocol, model_id, tool):+ return SPECS.get((vendor, protocol, tool))+++def _source(source_id, vendor, protocol, model_id, *, kind="api_key") -> ModelHubSourceConfig:+ return ModelHubSourceConfig(+ id=source_id,+ kind=kind,+ vendor=vendor,+ display_name=source_id,+ protocol=protocol,+ supply_channel="hub",+ billing="monthly" if kind == "subscription" else "metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id=model_id, provenance="discovered")],+ credential_ref=f"cred_{source_id}",+ )+++XAI = _source("src_xai00001", "xai", "openai_responses", "grok-4.6")+OPENAI = _source("src_oai00001", "openai", "openai_responses", "gpt-6-astra")+CLAUDE_SUB = _source("src_cla00001", "anthropic", "anthropic", "claude-opus-5-5", kind="subscription")+GEMINI = _source("src_gem00001", "google", "google", "gemini-3-pro")+ALL = [CLAUDE_SUB, XAI, OPENAI, GEMINI]+++def _config(tools: dict[str, ModelHubHostedToolConfig]) -> ModelHubConfig:+ vibey = ModelHubAgentSupplyConfig.default("vibey", mode="hub")+ vibey = replace(vibey, sources=replace(vibey.sources, order=[source.id for source in ALL]))+ config = ModelHubConfig(sources=list(ALL), hosted_tools=tools)+ config.agents["vibey"] = vibey+ return config+++def _store(tmp_path, *verified, engine=ENGINE) -> CapabilityEvidenceStore:+ store = CapabilityEvidenceStore(tmp_path / "evidence.json")+ for source, tool, aspect in verified:+ store.write(+ EvidenceRecord(+ source_id=source.id,+ model_id=source.models[0].id,+ feature=EvidenceFeature.hosted(tool, aspect),+ status="verified",+ basis="probe",+ observed_at=NOW,+ engine=engine,+ shape=1,+ source_identity=identity_digest(source),+ ),+ live=ALL,+ )+ return store+++def _resolve(tmp_path, tools, primary, *verified, engine=ENGINE, evidence_engine=ENGINE):+ return resolve_hosted_tools(+ _config(tools),+ source=primary,+ model_id=primary.models[0].id,+ evidence=_store(tmp_path, *verified, engine=evidence_engine),+ spec_for=_spec_for,+ engine=engine,+ now=NOW,+ )+++ON = ModelHubHostedToolConfig(enabled=True)+++def test_only_enabled_tools_resolve(tmp_path):+ assert _resolve(tmp_path, {}, XAI) == {}+ assert _resolve(tmp_path, {"web_search": ModelHubHostedToolConfig(enabled=False)}, XAI) == {}+++def test_no_evidence_means_proxy_without_an_executor(tmp_path):+ assert _resolve(tmp_path, {"web_search": ON, "image_generation": ON}, XAI) == {+ "web_search": {"mode": "proxy", "executor": None, "replay": False},+ "image_generation": {"mode": "proxy", "executor": None, "replay": False},+ }+++def test_verified_call_makes_the_hop_native_and_binds_the_first_verified_executor(tmp_path):+ resolved = _resolve(+ tmp_path,+ {"web_search": ON, "x_search": ON},+ OPENAI,+ (OPENAI, "web_search", "call"),+ (OPENAI, "web_search", "replay"),+ (XAI, "x_search", "call"),+ )+ assert resolved == {+ "web_search": {+ "mode": "native",+ "declaration": {"type": "web_search"},+ "include": ["web_search_call.action.sources"],+ "executor": {"source_id": "src_oai00001", "model_id": "gpt-6-astra"},+ "replay": True,+ },+ "x_search": {+ "mode": "proxy",+ "executor": {"source_id": "src_xai00001", "model_id": "grok-4.6"},+ "replay": False,+ },+ }+++def test_evidence_from_another_engine_routes_as_proxy(tmp_path):+ resolved = _resolve(+ tmp_path,+ {"web_search": ON},+ XAI,+ (XAI, "web_search", "call"),+ (XAI, "web_search", "replay"),+ engine="model-hub-engine-v8.0.24-1",+ )+ assert resolved == {"web_search": {"mode": "proxy", "executor": None, "replay": False}}+++ "primary",+ [CLAUDE_SUB, GEMINI],+ ids=["claude-subscription-is-never-eligible", "google-is-a-translated-path"],+)+def test_ineligible_or_translated_hops_never_go_native_or_execute(tmp_path, primary):+ resolved = _resolve(+ tmp_path, {"web_search": ON}, primary, (primary, "web_search", "call"), (primary, "web_search", "replay")+ )+ assert resolved == {"web_search": {"mode": "proxy", "executor": None, "replay": False}}+++def test_the_chosen_executor_wins_only_while_verified(tmp_path):+ chosen = ModelHubHostedToolConfig(enabled=True, executor=ModelHubRouteHopConfig("src_xai00001", "grok-4.6"))+ verified_both = (+ (OPENAI, "web_search", "call"),+ (XAI, "web_search", "call"),+ )+ assert _resolve(tmp_path / "a", {"web_search": chosen}, GEMINI, *verified_both)["web_search"]["executor"] == {+ "source_id": "src_xai00001",+ "model_id": "grok-4.6",+ }+ assert _resolve(tmp_path / "b", {"web_search": chosen}, GEMINI, verified_both[0])["web_search"]["executor"] == {+ "source_id": "src_oai00001",+ "model_id": "gpt-6-astra",+ }+++def test_image_generation_is_never_replayed(tmp_path):+ resolved = _resolve(tmp_path, {"image_generation": ON}, OPENAI, (OPENAI, "image_generation", "call"))+ assert resolved["image_generation"] == {+ "mode": "native",+ "declaration": {"type": "image_generation", "partial_images": 2},+ "include": [],+ "executor": {"source_id": "src_oai00001", "model_id": "gpt-6-astra"},+ "replay": False,+ }+++def test_status_lists_where_each_tool_can_run_and_counts_re_verifications(tmp_path):+ store = _store(tmp_path, (XAI, "x_search", "call"), (OPENAI, "web_search", "call"), engine="model-hub-engine-v8.0.22-1")+ store.write(+ EvidenceRecord(+ source_id=XAI.id,+ model_id="grok-4.6",+ feature=EvidenceFeature.hosted("web_search", "call"),+ status="verified",+ basis="probe",+ observed_at=NOW.replace(month=8),+ engine=ENGINE,+ shape=1,+ source_identity=identity_digest(XAI),+ ),+ live=ALL,+ )+ status = hosted_tools_status(+ _config({"x_search": ON}), evidence=store, spec_for=_spec_for, engine=ENGINE, now=NOW+ )+ by_name = {tool["name"]: tool for tool in status["tools"]}+ assert [tool["name"] for tool in status["tools"]] == ["web_search", "x_search", "image_generation"]+ assert by_name["x_search"]["enabled"] is True and by_name["web_search"]["enabled"] is False+ assert [(c["source_id"], c["call"]["status"], c["call"]["stale"]) for c in by_name["x_search"]["candidates"]] == [+ ("src_xai00001", "unknown", "wire")+ ]+ assert [(c["source_id"], c["call"]["status"], c["call"]["stale"]) for c in by_name["web_search"]["candidates"]] == [+ ("src_xai00001", "verified", "age"),+ ("src_oai00001", "unknown", "wire"),+ ]+ assert by_name["image_generation"]["candidates"][0]["replay"] is None+ assert status["reverify"] == {"engine_upgraded": 2, "aged": 1}diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex de3cdc7eb..c2c0c02af 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -5579,7 +5579,7 @@ def test_backend_failure_keeps_the_gateway_terminal_error_no_later_request_superdef test_released_backend_rejection_records_read_unchanged(tmp_path: Path) -> None:"""Records the earlier bridge wrote stay as written: no reason or phase is re-derived on read."""released = {- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_released_rejection","ts": NOW.isoformat(),"agent": "vibey",@@ -7055,7 +7055,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(_assert_valid("observation-result.schema.json",{- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -9586,7 +9586,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:probe = asyncio.run(service.probe_agent("codex", "shared-model"))assert probe == {- "contract_version": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex 037ce0f97..cd8305bdc 100644--- a/tests/test_model_hub_provenance.py+++ b/tests/test_model_hub_provenance.py@@ -261,7 +261,7 @@ def test_live_recovery_snapshots_never_revive_invalid_or_terminal_owners(tmp_patdef _record(turn_id, *, backend="claude", model=MODEL, outcome="failed_terminal"):identity = {"source_id": "src_deleted01", "configured_model_id": "unknown-model", "channel": "hub"}return {- "contract_version": 11,+ "contract_version": 12,"turn_id": turn_id,"ts": "2026-09-06T00:00:00Z","agent": backend,@@ -461,6 +461,6 @@ def test_model_history_client_rpc_http_share_nullable_read_only_result(monkeypatf"/api/models/agents/claude/provenance?model={MODEL}", headers=csrf_headers(client, origin), base_url=origin)assert response.status_code == 200- assert response.get_json() == {"ok": True, "contract_version": 11, "provenance": record}+ assert response.get_json() == {"ok": True, "contract_version": 12, "provenance": record}assert store.config.to_payload() == beforeassert adapter.synced == []diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 9c12b0f03..9fd04d697 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1707,7 +1707,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):)assert result["observation"] == {- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -1738,7 +1738,7 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):assert exc.value.code == "discovery_failed"assert exc.value.detail == "modelHub.errors.adapter_error"assert exc.value.data["observation"] == {- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex cb33fbe66..56f11b7db 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1349,7 +1349,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(installer=manager,state_store=EngineStateStore(tmp_path / "state"),)- projected = {"contract_version": 11, **supervisor.status()}+ projected = {"contract_version": 12, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"diff --git a/tests/test_model_hub_vibey_consumer.py b/tests/test_model_hub_vibey_consumer.pyindex 3141e857c..b3af2200e 100644--- a/tests/test_model_hub_vibey_consumer.py+++ b/tests/test_model_hub_vibey_consumer.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport asyncioimport copyimport json+import threadingfrom dataclasses import replacefrom datetime import timedeltafrom pathlib import Path@@ -24,6 +25,7 @@ from config.v2_config import (ModelHubAgentSupplyConfig,ModelHubBackendModelConfig,ModelHubConfig,+ ModelHubHostedToolConfig,ModelHubModelConfig,ModelHubRouteConfig,ModelHubRouteHopConfig,@@ -31,7 +33,9 @@ from config.v2_config import (ModelHubSourceStateConfig,)from core.handlers.model_hub.adapter import RawOutcomeKind-from core.handlers.model_hub.provenance import BoundedProvenanceStore, HopOrigin, SERVED_HOP_HEADER+from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest+from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp+from core.handlers.model_hub.provenance import BoundedProvenanceStore, SERVED_HOP_HEADERfrom core.handlers.model_hub.request import ModelHubRequestfrom core.handlers.model_hub.service import ModelHubErrorfrom core.handlers.model_hub.turn_gateway import ModelHubTurnGateway@@ -69,6 +73,7 @@ MANDATORY_FIELDS = {(): ("backend", "requested_model", "protocol", "base_url", "token","runtime_model", "source_id", "provider", "request_headers", "capabilities",+ "hosted_tools",),("capabilities",): ("context_window", "input_limit", "max_output_tokens", "supports_tools",@@ -84,6 +89,9 @@ MANDATORY_FIELDS = {("served",): ("source_id", "configured_model_id", "channel", "origin"),("served", "origin"): ("provider", "api", "model"),},+ "served-hop.schema.json": {+ (): ("provider", "api", "model", "source"),+ },}@@ -96,8 +104,15 @@ def _validate(schema_name, value):Draft7Validator(schema, registry=Registry().with_resources(resources.items())).validate(value)-def _assert_mandatory_fields(schema_name, payload):- for path, fields in MANDATORY_FIELDS[schema_name].items():+# Each enabled hosted tool's promised fields, for a native and a proxied entry.+HOSTED_TOOL_MANDATORY_FIELDS = {+ ("hosted_tools", "web_search"): ("mode", "executor", "replay", "declaration", "include"),+ ("hosted_tools", "image_generation"): ("mode", "executor", "replay"),+}+++def _assert_mandatory_fields(schema_name, payload, table=None):+ for path, fields in (table or MANDATORY_FIELDS[schema_name]).items():for field in fields:incomplete = copy.deepcopy(payload)target = incomplete@@ -111,6 +126,18 @@ def _assert_mandatory_fields(schema_name, payload):assert missing.value.message == f"'{field}' is a required property"+def _served_hop(response):+ """The exact served-hop header, validated against its own schema."""+ report = json.loads(response.headers[SERVED_HOP_HEADER])+ _validate("served-hop.schema.json", report)+ return report+++def _recorded_hop(attempt):+ """A provenance attempt in the header's shape: its persisted origin plus its Source."""+ return {**attempt["origin"], "source": attempt["source_id"]}++def _vibey_service(tmp_path, sources, *, handles=()):service = _service(tmp_path, sources=sources, live_handles=list(handles))_canonicalize_fixed_test_routes(service)@@ -238,8 +265,9 @@ async def test_failover_strips_opaque_history_only_when_origin_changes(tmp_path,) as response:assert response.status == 200assert await response.read() == b"{}"- assert json.loads(response.headers[SERVED_HOP_HEADER]) == {+ assert _served_hop(response) == {"provider": fallback.vendor, "api": fallback.protocol, "model": fallback.models[0].id,+ "source": fallback.id,}assert [entry[0] for entry in service.adapter.invocations] == [primary.id, fallback.id]assert service.adapter.requests[0] == {**common, **original}@@ -449,7 +477,7 @@ async def test_sequential_vibey_retry_replaces_route_and_retains_served_provenan) as response:assert response.status == 200await response.read()- origin = json.loads(response.headers[SERVED_HOP_HEADER])+ origin = _served_hop(response)# A late old credential must not arm/poison the retry's attribution,# even if the request is invalid before the model is parsed.service.store.config.agents["vibey"].routes["menu-alias"] = ModelHubRouteConfig((@@ -466,7 +494,7 @@ async def test_sequential_vibey_retry_replaces_route_and_retains_served_provenanassert response.status == (400 if late_request == "malformed" else 200)await response.read()if late_request == "valid":- assert json.loads(response.headers[SERVED_HOP_HEADER])["model"] == "late-model"+ assert _served_hop(response)["model"] == "late-model"completion = router.settle_turn(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())if completion:await completion@@ -474,7 +502,7 @@ async def test_sequential_vibey_retry_replaces_route_and_retains_served_provenanassert record is not Noneassert record["outcome"] == "served"assert record["served"]["source_id"] == fallback.id- assert record["served"]["origin"] == origin+ assert _recorded_hop(record["served"]) == origin_validate("turn-provenance.schema.json", record)finally:await gateway.close()@@ -941,6 +969,92 @@ def test_native_cli_and_direct_are_not_vibey_channels(tmp_path):}) is None+async def test_hop_resolution_states_each_enabled_hosted_tool(tmp_path):+ """MH-HOSTED-001: native only on current-wire call evidence; every enabled tool binds an executor."""+ primary = _source("src_primary01", "Primary", protocol="openai_responses", model_id="gpt-6-astra")+ service = _vibey_service(tmp_path, [primary])+ service.store.config.hosted_tools = {+ "web_search": ModelHubHostedToolConfig(enabled=True),+ "x_search": ModelHubHostedToolConfig(enabled=False),+ "image_generation": ModelHubHostedToolConfig(enabled=True),+ }+ for aspect in ("call", "replay"):+ service.capability_evidence.write(+ EvidenceRecord(+ source_id=primary.id,+ model_id="gpt-6-astra",+ feature=EvidenceFeature.hosted("web_search", aspect),+ status="verified",+ basis="probe",+ observed_at=service.now(),+ engine=engine_stamp(),+ shape=HOSTED_PROBE_SHAPE,+ source_identity=identity_digest(primary),+ ),+ live=[primary],+ )+ resolving_threads = []+ resolve_on_worker = service.hosted_tools_for_hop++ def recorded(*args):+ resolving_threads.append(threading.current_thread())+ return resolve_on_worker(*args)++ service.hosted_tools_for_hop = recorded+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:test", turn_id="turn-hosted")+ # The first resolution may load the evidence file, so it never runs on the controller loop.+ assert resolving_threads and threading.main_thread() not in resolving_threads+ _validate("hop-resolution.schema.json", hop)+ assert hop["hosted_tools"] == {+ "web_search": {+ "mode": "native",+ "declaration": {"type": "web_search"},+ "include": ["web_search_call.action.sources"],+ "executor": {"source_id": "src_primary01", "model_id": "gpt-6-astra"},+ "replay": True,+ },+ "image_generation": {"mode": "proxy", "executor": None, "replay": False},+ }+ _assert_mandatory_fields("hop-resolution.schema.json", hop, HOSTED_TOOL_MANDATORY_FIELDS)+ for broken in (+ {"mode": "proxy", "declaration": {"type": "web_search"}, "executor": None, "replay": False},+ {"mode": "native", "executor": None, "replay": False, "include": []},+ {"mode": "proxy", "executor": {"source_id": "src_primary01"}, "replay": False},+ ):+ with pytest.raises(ValidationError):+ _validate("hop-resolution.schema.json", {**hop, "hosted_tools": {"web_search": broken}})+ with pytest.raises(ValidationError):+ _validate(+ "hop-resolution.schema.json",+ {**hop, "hosted_tools": {"image_generation": {"mode": "proxy", "executor": None, "replay": True}}},+ )+ finally:+ await gateway.close()+++def test_both_hop_resolution_copies_state_the_same_contract():+ """MH-HOSTED-001: the agent-core copy and the Model Hub copy cannot drift."""+ agent_core = json.loads((CONTRACTS.parent / "agent-core-contracts/hop-resolution.schema.json").read_text())+ model_hub = json.loads((CONTRACTS / "hop-resolution.schema.json").read_text())+ assert sorted(agent_core["required"]) == sorted(model_hub["required"])+ assert set(agent_core["properties"]) == set(model_hub["properties"])++ def constraints(schema):+ if isinstance(schema, dict):+ return {key: constraints(value) for key, value in schema.items() if key != "description"}+ if isinstance(schema, list):+ return [constraints(value) for value in schema]+ return schema++ # The copies differ only in prose and in where `protocol` points (both name the same four values).+ for name in set(agent_core["properties"]) - {"protocol"}:+ assert constraints(agent_core["properties"][name]) == constraints(model_hub["properties"][name]), name++@pytest.mark.asyncio@pytest.mark.parametrize("protocol", PROTOCOL_ENDPOINTS)@pytest.mark.parametrize("known", [False, True])@@ -1018,8 +1132,10 @@ async def test_failover_origin_is_available_before_body_and_matches_served_attemjson={"model": hop["runtime_model"], "stream": stream, "messages": []},) as response:assert response.status == 200, await response.text() if response.status != 200 else ""- origin = json.loads(response.headers[SERVED_HOP_HEADER])- assert origin == {"provider": "anthropic", "api": fallback_protocol, "model": "模型/β"}+ origin = _served_hop(response)+ assert origin == {+ "provider": "anthropic", "api": fallback_protocol, "model": "模型/β", "source": second.id,+ }assert response.headers[SERVED_HOP_HEADER].isascii()assert await response.read() == answercompletion = router.settle_turn(@@ -1030,17 +1146,22 @@ async def test_failover_origin_is_available_before_body_and_matches_served_attemrecord = service.provenance.get("turn-fallback")_validate("turn-provenance.schema.json", record)_assert_mandatory_fields("turn-provenance.schema.json", record)+ _assert_mandatory_fields("served-hop.schema.json", origin)# The new Avibe promise must not tighten native or released records.# Exercise the persistence reader, not only in-memory schema payloads.history = []for backend in ("claude", "codex", "opencode"):- for version in (5, 6, 7, 8, 9, 10):+ for version in (5, 6, 7, 8, 9, 10, 11):native = copy.deepcopy(record)native.update(agent=backend, contract_version=version, turn_id=f"{backend}-{version}")native["served"].pop("origin")for attempt in native["failed_attempts"]:attempt.pop("origin", None)history.append(native)+ # Vibey records written before the served-hop report named its Source.+ released_vibey = copy.deepcopy(record)+ released_vibey.update(contract_version=11, turn_id="vibey-11")+ history.append(released_vibey)history_path = tmp_path / "native-history.json"history_path.write_text(json.dumps(history))history_store = BoundedProvenanceStore(history_path)@@ -1048,7 +1169,7 @@ async def test_failover_origin_is_available_before_body_and_matches_served_attemloaded = history_store.get(native["turn_id"])assert loaded == native_validate("turn-provenance.schema.json", loaded)- assert record["served"]["origin"] == origin+ assert _recorded_hop(record["served"]) == originassert record["served"]["source_id"] == second.idassert record["failed_attempts"][0]["source_id"] == first.idassert [entry[0] for entry in service.adapter.invocations] == [first.id, second.id]@@ -1158,8 +1279,10 @@ async def test_terminal_response_origin_follows_its_carrier(assert response.status == expected_statusorigin = Noneif backend == "vibey" and has_producer:- origin = json.loads(response.headers[SERVED_HOP_HEADER])- assert origin == {"provider": "anthropic", "api": "anthropic", "model": "模型/β"}+ origin = _served_hop(response)+ assert origin == {+ "provider": "anthropic", "api": "anthropic", "model": "模型/β", "source": source.id,+ }else:assert SERVED_HOP_HEADER not in response.headersassert (await response.json())["error"]@@ -1182,7 +1305,7 @@ async def test_terminal_response_origin_follows_its_carrier(if cause == "upstream":assert record["terminal_error"]["source_id"] == source.idif backend == "vibey":- assert record["terminal_error"]["origin"] == origin+ assert _recorded_hop(record["terminal_error"]) == originelse:assert "origin" not in record["terminal_error"]elif failure == "exhaustion":@@ -1199,8 +1322,8 @@ async def test_terminal_response_origin_follows_its_carrier(@pytest.mark.asyncio@pytest.mark.parametrize("fallback", [False, True])@pytest.mark.parametrize("model_id,allowed", [- pytest.param("a" * 4044, True, id="exact-bound"), # 52 bytes of JSON envelope.- pytest.param("a" * 4045, False, id="one-over"),+ pytest.param("a" * 4019, True, id="exact-bound"), # 77 bytes of JSON envelope.+ pytest.param("a" * 4020, False, id="one-over"),pytest.param("模" * 1350, False, id="unicode-expansion"),])async def test_origin_header_limit_is_checked_before_each_vibey_hop(tmp_path, model_id, allowed, fallback):@@ -1236,7 +1359,7 @@ async def test_origin_header_limit_is_checked_before_each_vibey_hop(tmp_path, moif allowed:assert response.status == 200assert len(response.headers[SERVED_HOP_HEADER].encode("ascii")) == 4096- assert json.loads(response.headers[SERVED_HOP_HEADER])["model"] == model_id+ assert _served_hop(response)["model"] == model_idassert await response.read() == b"{}"else:assert response.status == 422@@ -1302,13 +1425,13 @@ async def test_slow_anthropic_resolution_waits_to_publish_origin_and_keeps_sourcrelease.set()response = await asyncio.wait_for(task, 2)async with response:- origin = json.loads(response.headers[SERVED_HOP_HEADER])- assert origin == HopOrigin("anthropic", "anthropic", "shared-model").payload()+ origin = _served_hop(response)+ assert origin == {"provider": "anthropic", "api": "anthropic", "model": "shared-model", "source": source.id}assert await response.read() == answercompletion = router.settle_turn("turn-slow", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())if completion:await completion- assert service.provenance.get("turn-slow")["served"]["origin"] == origin+ assert _recorded_hop(service.provenance.get("turn-slow")["served"]) == originfinally:release.set()if task is not None and not task.done():@@ -1360,7 +1483,7 @@ async def test_concurrent_responses_keep_their_own_origin(tmp_path):json={"model": hop["runtime_model"], "stream": True, "messages": []},) as response:assert response.status == 200- origin = json.loads(response.headers[SERVED_HOP_HEADER])+ origin = _served_hop(response)assert await response.read() == _body(hop["protocol"], True)return origin@@ -1369,13 +1492,13 @@ async def test_concurrent_responses_keep_their_own_origin(tmp_path):second_origin = await asyncio.wait_for(read(hops[1]), 2)release.set()first_origin = await asyncio.wait_for(pending, 2)- assert first_origin == {"provider": "openai", "api": "openai_chat", "model": "model-one"}- assert second_origin == {"provider": "anthropic", "api": "anthropic", "model": "model-two"}+ assert first_origin == {"provider": "openai", "api": "openai_chat", "model": "model-one", "source": first.id}+ assert second_origin == {"provider": "anthropic", "api": "anthropic", "model": "model-two", "source": second.id}for index, origin in enumerate((first_origin, second_origin)):completion = router.settle_turn(f"turn-{index}", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())if completion:await completion- assert service.provenance.get(f"turn-{index}")["served"]["origin"] == origin+ assert _recorded_hop(service.provenance.get(f"turn-{index}")["served"]) == originfinally:release.set()if pending is not None and not pending.done():diff --git a/tests/test_model_hub_vibey_contract_matrix.py b/tests/test_model_hub_vibey_contract_matrix.pyindex a5318a571..7d6717f34 100644--- a/tests/test_model_hub_vibey_contract_matrix.py+++ b/tests/test_model_hub_vibey_contract_matrix.py@@ -48,13 +48,13 @@ def _fixture(kind):# Start from a valid native response so no Hub latency constraint can# accidentally reject the Avibe/native pairing for an unrelated cause.return {- "contract_version": 11, "backend": "claude", "channel": "native_cli", "reachable": True,+ "contract_version": 12, "backend": "claude", "channel": "native_cli", "reachable": True,"source_id": "src_fixture01", "model_id": "fixture-model", "latency_ms": None,"error": None,}if kind == "chain":return {- "contract_version": 11, "backend": "vibey", "model_id": "fixture-model",+ "contract_version": 12, "backend": "vibey", "model_id": "fixture-model","manual_override": None, "route_origin": "automatic","chain": [{"source_id": "src_fixture01", "model_id": "fixture-model", "channel": "hub","health": "healthy", "runnable": True, "reason": None, "retry_at": None}],@@ -66,7 +66,7 @@ def _fixture(kind):"proposed_action": "import", "selected": False,}return {- "contract_version": 11, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",+ "contract_version": 12, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z","agent": "vibey", "requested_model_id": "fixture-model", "outcome": kind,"failed_attempts": [{**identity, "reason": "rate_limited"}] if kind == "exhausted" else [],"served": identity if kind == "served" else None,diff --git a/tests/test_provider_overlay.py b/tests/test_provider_overlay.pynew file mode 100644index 000000000..11d075320--- /dev/null+++ b/tests/test_provider_overlay.py@@ -0,0 +1,257 @@+"""The overlay's ``providers`` section (``model-hub-capability-model.md`` §4).++The loader is the one reader of the bundled section, so its resolution and its+degradation are pinned here, with the JSON Schema held to the same verdicts.+"""++from __future__ import annotations++import copy+import json+import logging+from datetime import date+from pathlib import Path++import pytest+from jsonschema import Draft7Validator, FormatChecker+from referencing import Registry, Resource++from vibe import backend_model_catalog as catalog+from vibe.backend_model_catalog import HostedToolPrice, HostedToolPriceComponent++CONTRACTS = Path(__file__).parents[1] / "docs/plans/model-hub-contracts"+BUNDLED = json.loads(catalog.get_bundled_catalog_path().read_text(encoding="utf-8"))+BUNDLED_ROWS = catalog.load_bundled_catalog()["backends"]+AS_OF = date(2026, 10, 13)+_DROP = object()++[email protected](autouse=True)+def _fresh_overlay():+ catalog.bundled_provider_overlay.cache_clear()+ yield+ catalog.bundled_provider_overlay.cache_clear()+++def _validator() -> Draft7Validator:+ schemas = [+ json.loads((CONTRACTS / name).read_text(encoding="utf-8"))+ for name in ("provider-overlay.schema.json", "source.schema.json")+ ]+ registry = Registry().with_resources(+ (schema["$id"], Resource.from_contents(schema)) for schema in schemas+ )+ return Draft7Validator(schemas[0], registry=registry, format_checker=FormatChecker())+++def _use_bundled(monkeypatch, tmp_path: Path, providers: object) -> None:+ path = tmp_path / "backend_models.json"+ path.write_text(json.dumps({**BUNDLED, "providers": providers}), encoding="utf-8")+ monkeypatch.setattr(catalog, "get_bundled_catalog_path", lambda *_args, **_kwargs: path)+++def _overlay_warnings(caplog) -> list[str]:+ return [+ record.getMessage()+ for record in caplog.records+ if record.name == catalog.__name__ and record.levelno == logging.WARNING+ ]+++def test_bundled_providers_section_satisfies_its_schema():+ _validator().validate(BUNDLED["providers"])+++ ("vendor", "protocol", "model", "tool", "expected"),+ [+ (+ "openai",+ "openai_responses",+ "gpt-6-astra",+ "web_search",+ (+ {"type": "web_search"},+ ("web_search_call.action.sources",),+ HostedToolPrice("call", 10.0, AS_OF, "https://developers.openai.com/api/docs/pricing"),+ ),+ ),+ (+ "openai",+ "openai_responses",+ " gpt-6-astra ",+ "image_generation",+ ({"type": "image_generation", "partial_images": 2}, (), None),+ ),+ (+ "xai",+ "openai_responses",+ "grok-4.6",+ "x_search",+ (+ {"type": "x_search"},+ (),+ HostedToolPrice(+ "post",+ 5.0,+ AS_OF,+ "https://docs.x.ai/developers/pricing",+ extra=(HostedToolPriceComponent("profile", 10.0),),+ ),+ ),+ ),+ (+ "anthropic",+ "anthropic",+ "claude-opus-5-5",+ "web_search",+ (+ {"type": "web_search_20250305", "name": "web_search"},+ (),+ HostedToolPrice("search", 10.0, AS_OF, "https://platform.claude.com/docs/en/about-claude/pricing"),+ ),+ ),+ ("mistral", "openai_responses", "gpt-6-astra", "web_search", None),+ ("openai", "openai_responses", "o3", "web_search", None),+ ("xai", "openai_responses", "grok-3", "web_search", None),+ ("xai", "anthropic", "grok-4.6", "web_search", None),+ ],+)+def test_bundled_overlay_resolves_hosted_tools(vendor, protocol, model, tool, expected):+ """MH-HOSTED-005: the bundled overlay resolves each hosted tool declaration, include and price."""+ spec = catalog.hosted_tool_spec(vendor, protocol, model, tool)++ if expected is None:+ assert spec is None+ return+ assert (spec.declaration, spec.include, spec.price) == expected+ spec.declaration["type"] = "changed"+ assert catalog.hosted_tool_spec(vendor, protocol, model, tool).declaration == expected[0]+++ ("model", "wire_efforts", "has_web_search"),+ [+ ("gpt-6-astra", ("low", "high"), False),+ ("gpt-6-astra-mini", None, True),+ ("gpt-5.5", ("minimal",), False),+ ("gpt", None, None),+ ],+)+def test_overlay_families_match_in_order_and_the_first_match_wins(+ monkeypatch, tmp_path, model, wire_efforts, has_web_search+):+ web_search = {"openai_responses": {"web_search": {"declaration": {"type": "web_search"}}}}+ _use_bundled(+ monkeypatch,+ tmp_path,+ {+ "openai": {+ "models": [+ {"match": {"id": "gpt-6-astra"}, "wire_efforts": ["low", "high"]},+ {"match": {"prefix": "gpt-6"}, "wire_efforts": None, "hosted_tools": web_search},+ {"match": {"prefix": "gpt-"}, "wire_efforts": ["minimal"]},+ ]+ }+ },+ )++ entry = catalog.provider_overlay_entry("openai", model)+ spec = catalog.hosted_tool_spec("openai", "openai_responses", model, "web_search")++ if has_web_search is None:+ assert entry is None and spec is None+ return+ assert entry.wire_efforts == wire_efforts+ assert (spec is not None) is has_web_search+++def _edit(path: tuple, value: object):+ def invalid(entry: dict) -> dict:+ entry = copy.deepcopy(entry)+ *parents, leaf = path+ node = entry+ for key in parents:+ node = node[key]+ if value is _DROP:+ del node[leaf]+ else:+ node[leaf] = value+ return entry++ return invalid+++_FAMILY = ("models", 0)+_X_SEARCH = (*_FAMILY, "hosted_tools", "openai_responses", "x_search")+_PRICE = (*_X_SEARCH, "price")+++ ("key", "invalid"),+ [+ pytest.param("xai", lambda entry: [], id="entry-not-an-object"),+ pytest.param("xAI", lambda entry: entry, id="vendor-not-canonical"),+ pytest.param("xai", _edit(("models",), _DROP), id="models-missing"),+ pytest.param("xai", _edit(("models",), {}), id="models-not-a-list"),+ pytest.param("xai", _edit(("note",), "x"), id="unknown-vendor-key"),+ pytest.param("xai", _edit((*_FAMILY, "tier"), 1), id="unknown-family-key"),+ pytest.param("xai", _edit((*_FAMILY, "match"), _DROP), id="match-missing"),+ pytest.param("xai", _edit((*_FAMILY, "match"), {}), id="match-empty"),+ pytest.param("xai", _edit((*_FAMILY, "match", "id"), "grok-4.6"), id="match-prefix-and-id"),+ pytest.param("xai", _edit((*_FAMILY, "match"), {"prefix": " grok-4"}), id="match-padded"),+ pytest.param("xai", _edit((*_FAMILY, "wire_efforts"), "high"), id="wire-efforts-not-a-list"),+ pytest.param("xai", _edit((*_FAMILY, "wire_efforts"), ["high", "high"]), id="wire-efforts-repeated"),+ pytest.param("xai", _edit((*_FAMILY, "hosted_tools", "responses"), {}), id="unknown-protocol"),+ pytest.param(+ "xai",+ _edit(+ (*_FAMILY, "hosted_tools", "openai_responses", "code_interpreter"),+ {"declaration": {"type": "code_interpreter"}},+ ),+ id="unknown-tool",+ ),+ pytest.param("xai", _edit((*_X_SEARCH, "declaration"), _DROP), id="declaration-missing"),+ pytest.param("xai", _edit((*_X_SEARCH, "declaration"), {"name": "x_search"}), id="declaration-untyped"),+ pytest.param("xai", _edit((*_X_SEARCH, "include"), [""]), id="include-blank"),+ pytest.param("xai", _edit(_PRICE, None), id="price-null"),+ pytest.param("xai", _edit((*_PRICE, "unit"), "image"), id="price-unit-unknown"),+ pytest.param("xai", _edit((*_PRICE, "usd_per_1k"), -1), id="price-negative"),+ pytest.param("xai", _edit((*_PRICE, "usd_per_1k"), True), id="price-boolean"),+ pytest.param("xai", _edit((*_PRICE, "as_of"), "2026/10/13"), id="as-of-not-iso"),+ pytest.param("xai", _edit((*_PRICE, "as_of"), "2026-02-30"), id="as-of-impossible"),+ pytest.param("xai", _edit((*_PRICE, "url"), "http://docs.x.ai/developers/pricing"), id="url-not-https"),+ pytest.param("xai", _edit((*_PRICE, "url"), _DROP), id="url-missing"),+ pytest.param("xai", _edit((*_PRICE, "extra", 0, "unit"), "image"), id="extra-unit-unknown"),+ ],+)+def test_an_invalid_vendor_entry_disables_only_that_vendor(monkeypatch, tmp_path, caplog, key, invalid):+ providers = {+ "anthropic": BUNDLED["providers"]["anthropic"],+ "openai": BUNDLED["providers"]["openai"],+ key: invalid(BUNDLED["providers"]["xai"]),+ }+ assert not _validator().is_valid(providers)+ _use_bundled(monkeypatch, tmp_path, providers)++ with caplog.at_level(logging.WARNING, logger=catalog.__name__):+ overlay = catalog.bundled_provider_overlay()++ assert set(overlay) == {"anthropic", "openai"}+ assert catalog.hosted_tool_spec("openai", "openai_responses", "gpt-6-astra", "web_search") is not None+ warnings = _overlay_warnings(caplog)+ assert len(warnings) == 1 and repr(key) in warnings[0]++[email protected]("providers", [[], "openai", None])+def test_a_providers_value_that_is_not_an_object_disables_only_the_overlay(+ monkeypatch, tmp_path, caplog, providers+):+ _use_bundled(monkeypatch, tmp_path, providers)++ with caplog.at_level(logging.WARNING, logger=catalog.__name__):+ overlay = catalog.bundled_provider_overlay()++ assert dict(overlay) == {}+ assert len(_overlay_warnings(caplog)) == 1+ assert catalog.load_bundled_catalog()["backends"] == BUNDLED_ROWSdiff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 49d618492..d5a1266cf 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -2351,7 +2351,9 @@ async def test_a_turn_runs_through_the_real_provider_registry(engine, session, twire = "openai_chat" if hub_protocol == "google" else hub_protocolpath, body = _TEXT_STREAMS[wire]- served = json.dumps({"provider": "upstream", "api": wire, "model": "served-model"}, separators=(",", ":"))+ served = json.dumps(+ {"provider": "upstream", "api": wire, "model": "served-model", "source": "src_upstream01"}, separators=(",", ":")+ )seen: list[str] = []def gateway(request: httpx.Request) -> httpx.Response:@@ -2400,7 +2402,10 @@ async def test_a_stream_that_drops_after_thinking_alone_gets_one_retry_then_its_from modules.agents.vibey.models import registry_providers- served = json.dumps({"provider": "upstream", "api": "openai_responses", "model": "served-model"}, separators=(",", ":"))+ served = json.dumps(+ {"provider": "upstream", "api": "openai_responses", "model": "served-model", "source": "src_upstream01"},+ separators=(",", ":"),+ )ending, copy = _THINKING_DROPS[drop]thinking_then_cut = ('data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'diff --git a/tests/test_vibey_agent_context.py b/tests/test_vibey_agent_context.pyindex eab7e6dd9..203b7f745 100644--- a/tests/test_vibey_agent_context.py+++ b/tests/test_vibey_agent_context.py@@ -506,7 +506,10 @@ async def test_a_threshold_checkpoint_and_an_overflow_roll_through_the_real_loopfrom modules.agents.vibey.models import registry_providers- served = json.dumps({"provider": "upstream", "api": "anthropic", "model": "served-model"}, separators=(",", ":"))+ served = json.dumps(+ {"provider": "upstream", "api": "anthropic", "model": "served-model", "source": "src_upstream01"},+ separators=(",", ":"),+ )overflow = json.dumps({"type": "error", "error": {"type": "invalid_request_error", "message": "prompt is too long: 40000 tokens > 32000 maximum"}})diff --git a/ui/e2e/chat-interactions/interactions.spec.ts b/ui/e2e/chat-interactions/interactions.spec.tsindex eea1c136c..bb0b28206 100644--- a/ui/e2e/chat-interactions/interactions.spec.ts+++ b/ui/e2e/chat-interactions/interactions.spec.ts@@ -11,7 +11,7 @@ for (const lang of ['en', 'zh'] as const) {if (url.origin !== 'http://127.0.0.1:5227' || route.request().method() !== 'GET') return route.abort();if (url.pathname === `/api/models/turns/${TURN}/provenance`) {return route.fulfill({ json: { provenance: {- contract_version: 11, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',+ contract_version: 12, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',outcome: 'failed_terminal', failed_attempts: [], blockers: [],terminal_error: { source_id: 'fixture-source', configured_model_id: 'fixture-model', reason: 'engine_down' },} } });diff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsxindex 2a4b7dc47..4b8312830 100644--- a/ui/e2e/model-catalog/gatewayFixture.tsx+++ b/ui/e2e/model-catalog/gatewayFixture.tsx@@ -35,13 +35,13 @@ export function GatewayFixture() {}],};const chains = Object.fromEntries(ids.map((model_id, index) => [modelChainKey(backend, model_id), readyRegion<AgentChain>({- contract_version: 11, backend, model_id, route_origin: origins[index],+ contract_version: 12, backend, model_id, route_origin: origins[index],manual_override: origins[index] === 'manual' ? { hops: [{ source_id: source.id, model_id }] } : null,current: { source_id: source.id, model_id }, supply_state: 'ok',chain: [{ source_id: source.id, model_id, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],})]));const runtime = freshRuntimeProjection(readyRegion({- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },}));diff --git a/ui/e2e/model-catalog/routeFixture.tsx b/ui/e2e/model-catalog/routeFixture.tsxindex d207e015d..f66b83a97 100644--- a/ui/e2e/model-catalog/routeFixture.tsx+++ b/ui/e2e/model-catalog/routeFixture.tsx@@ -28,7 +28,7 @@ const supply: AgentSupply = {sources: { order: sources.map((source) => source.id), eligibility: sources.map((source) => ({ source_id: source.id, eligible: true })) },};const makeChain = (hops: RouteHop[], manual: boolean): AgentChain => ({- contract_version: 11, backend, model_id: modelId,+ contract_version: 12, backend, model_id: modelId,manual_override: manual ? { hops } : null,route_origin: manual ? 'manual' : origin === 'passthrough' ? 'passthrough' : 'automatic',current: hops[0] ?? null, supply_state: hops.length ? 'ok' : 'interrupted',diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.tsindex a986e549f..edcf8e26d 100644--- a/ui/e2e/model-routing-origin.spec.ts+++ b/ui/e2e/model-routing-origin.spec.ts@@ -102,7 +102,7 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve expwould_remove_hops: [{ backend: gateway.backend, menu_model: gateway.model, ...manual.hops[0], position: 1 }],would_interrupt: [],};- expect(await refused.json()).toMatchObject({ ok: false, contract_version: 11, error: 'source_in_route_chain', ...plan });+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 12, error: 'source_in_route_chain', ...plan });expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);// The one question is its own modal over the chain the user was editing.const guard = hub.dialogTitled(copy('guard.title.saveRoute', { menuModel: gateway.model }));diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.tsindex 5c9f4bff5..a03ead302 100644--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts@@ -92,7 +92,7 @@ for (const width of [1200, 390]) {if (path === '/api/models/runtime/status') return answer({ok: true,runtime: {- contract_version: 11, enabled: true, host_platform: 'linux',+ contract_version: 12, enabled: true, host_platform: 'linux',manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: 'fixture', verified: true, health: 'ok' },},diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.tsindex bbd708ac7..1e4ad330d 100644--- a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts@@ -18,7 +18,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] asconst config=()=>({version:'v2',mode:'self_host',setup_completed:completed,setup_state:{needs_setup:!completed},capabilities:{model_hub:{enabled:true}},platforms:{primary:'slack',enabled:[]},runtime:{},agents:Object.fromEntries(['claude','codex','opencode'].map(b=>[b,{enabled:b!=='opencode',cli_path:b}])),agent:{default_cwd:'/fixture/work'},model_hub:{enabled:true,runtime_default_applied:true}});const source={id:'src_fixture',kind:'api_key',vendor:'openai',display_name:'Fixture source',protocol:'openai_chat',supply_channel:'hub',billing:'metered',state:{status:'active'},masked_credential:'fixture-only',models:hops.map(h=>({id:h.model_id,display_name:h.model_id==='gpt-5'?'GPT-5':undefined,origin:'discovered',reasoning_efforts:[],reasoning_efforts_source:null})),last_discovered_at:null};const supply=(b:string)=>({backend:b,cli_present:true,mode:'hub',menu_kind:'fixed',sources:{order:[source.id],eligibility:[{source_id:source.id,eligible:true}]},routes:{},builtin_models:[],catalog_models:[],menu:null,model_supply:[],named_agents:[{name:b,effective_model_id:agent(b).model,supply_status:saved[b].length?'ok':'unavailable'}],supply_status:saved[b].length?'ok':'unavailable'});- const chain=(b:string,hs=saved[b])=>({contract_version:11,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});+ const chain=(b:string,hs=saved[b])=>({contract_version:12,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});await page.addInitScript(()=>localStorage.setItem('i18nextLng','en'));await page.route(`${ORIGIN}/api/**`,async route=>{const req=route.request(),path=new URL(req.url()).pathname;@@ -34,7 +34,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as}if(path==='/api/agents')return answer({ok:true,default_agent_name:defaultName,agents:[agent('claude'),agent('codex')]});if(/^\/api\/agents\/(claude|codex)$/.test(path))return answer({ok:true,agent:agent(path.split('/').at(-1)!),default_agent_name:defaultName});- if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:11,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});+ if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:12,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});if(path==='/api/models/sources')return answer({ok:true,sources:[source]});if(path==='/api/models/agents')return answer({ok:true,agents:[supply('claude'),supply('codex')]});if(/\/api\/models\/agents\/(claude|codex)\/chains$/.test(path)){diff --git a/ui/e2e/onboarding-fidelity/provider-support.ts b/ui/e2e/onboarding-fidelity/provider-support.tsindex 230ef1215..b48def30b 100644--- a/ui/e2e/onboarding-fidelity/provider-support.ts+++ b/ui/e2e/onboarding-fidelity/provider-support.ts@@ -129,7 +129,7 @@ const CONFIG = {/** Installed, verified and serving: the screen's `gatewayIntent` reads `running` and* starts no install, which is the state every proof below is about something else. */const RUNTIME = {- contract_version: 11,+ contract_version: 12,enabled: true,host_platform: 'darwin',manifest: {diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex f86edd8e3..bb09eb38c 100644--- a/ui/e2e/onboarding-fidelity/support.ts+++ b/ui/e2e/onboarding-fidelity/support.ts@@ -87,7 +87,7 @@ export async function serveProduct(page: Page) {const backend = new URL(route.request().url()).pathname.split('/')[4];return route.fulfill({ json: { ok: true, agent: { backend, mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' } } });});- await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 11, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 12, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));await page.route(`${ORIGIN}/status`, (route) => route.fulfill({ json: { state: 'running' } }));await page.route('**/api/backend/*/connection', (route) => route.fulfill({ json: { ok: true, backend: new URL(route.request().url()).pathname.split('/').at(-2), installed: true, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false } }));await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex 32d43f0ed..aeeeede5f 100644--- a/ui/e2e/workbench-general/geometry.spec.ts+++ b/ui/e2e/workbench-general/geometry.spec.ts@@ -48,7 +48,7 @@ const MODEL_HUB_AGENT = {};const MODEL_HUB_RUNTIME = {- contract_version: 11,+ contract_version: 12,enabled: true,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'f'.repeat(40), assets: [] },status: { installed_version: 'fixture', verified: true, listening: { host: '127.0.0.1', port: 43123 }, health: 'ok' },diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsxindex f6308950e..7df614a40 100644--- a/ui/src/components/onboarding/AssistantSetup.test.tsx+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx@@ -50,7 +50,7 @@ const hubAgent = (enabled = true) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true },});const hubChain = (modelId: string) => ({- contract_version: 11, backend: 'claude', model_id: 'opus-5',+ contract_version: 12, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],@@ -340,7 +340,7 @@ describe('assistant installation presentation', () => {mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });mock.models.listSources.mockResolvedValue([]);const chain = {- contract_version: 11, backend: 'claude', model_id: 'opus-5',+ contract_version: 12, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },chain: [diff --git a/ui/src/components/onboarding/BuiltinAssistant.test.tsx b/ui/src/components/onboarding/BuiltinAssistant.test.tsxindex daab15927..3ec523fb3 100644--- a/ui/src/components/onboarding/BuiltinAssistant.test.tsx+++ b/ui/src/components/onboarding/BuiltinAssistant.test.tsx@@ -65,7 +65,7 @@ const vibeyAgent = (model: string | null) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true, lock_delete: true },});const chain = (modelId: string) => ({- contract_version: 11, backend: 'vibey', model_id: modelId,+ contract_version: 12, backend: 'vibey', model_id: modelId,manual_override: null, route_origin: 'automatic', current: { source_id: 'src_openai', model_id: modelId },chain: [{ source_id: 'src_openai', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],supply_state: 'ok',diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex 0fde4060b..e0454ea13 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -79,7 +79,7 @@ const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }});const runtimeOf = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },status: { verified: true, health },...over,diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsindex b24869d6d..ec793bb21 100644--- a/ui/src/components/onboarding/providers/providerStage.test.ts+++ b/ui/src/components/onboarding/providers/providerStage.test.ts@@ -660,7 +660,7 @@ describe('adoptionBackend', () => {});const runtime = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },status: { verified: true, health },...over,diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 17d740c46..7ab7c340b 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -17,7 +17,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';import type { AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};@@ -414,7 +414,7 @@ describe('AgentCard', () => {['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {const key = modelChainKey('claude', 'claude-opus-4-6');- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 12, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.getByText(/Backup/)).toBeTruthy();expect(screen.getByTitle(mappingCopy)).toBeTruthy();expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();@@ -434,7 +434,7 @@ describe('AgentCard', () => {sources={[source('src_b', 'Backup source')]}chains={{[key]: readyRegion({ manual_override: {hops:[{source_id:'src_b',model_id:'routed-opus'}]}, route_origin: "manual" as const,- contract_version: 11,+ contract_version: 12,backend: 'claude',model_id: 'claude-opus-4-6',current: { source_id: 'src_b', model_id: 'routed-opus' },@@ -467,7 +467,7 @@ describe('AgentCard', () => {it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {const key = modelChainKey('claude', 'claude-opus-4-6');- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 12, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.getByText(/Backup/)).toBeTruthy();expect(screen.queryByText(/takeover/i)).toBeNull();});@@ -475,7 +475,7 @@ describe('AgentCard', () => {it('hides current and takeover projections while the runtime is stopped', () => {const key = modelChainKey('claude', 'claude-opus-4-6');const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 12, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Backup/)).toBeNull();expect(screen.queryByText(/takeover/i)).toBeNull();@@ -487,7 +487,7 @@ describe('AgentCard', () => {const onOpenModels = vi.fn();const key = modelChainKey('claude', 'claude-opus-4-6');const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 12, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Adjust priority/i)).toBeNull();expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();expect(screen.queryByText(/Backup/)).toBeNull();diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex 6f11302cf..ee4c7118f 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx@@ -34,7 +34,7 @@ const CLAUDE_KEY: MigrationItem = {};const RUNTIME: RuntimeDependency = {- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: '1', verified: true, health: 'ok' },};diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsxindex d3dd1136f..3e75e5a8e 100644--- a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx@@ -17,7 +17,7 @@ const sources: Source[] = ['a', 'b'].map((id) => ({}));const hops = sources.map((source) => ({ source_id: source.id, model_id: 'gpt-test' }));const makeChain = (backend: AgentSupply['backend'], routeOrigin: 'automatic' | 'passthrough' | 'manual'): AgentChain => ({- contract_version: 11, backend, model_id: 'gpt-test', route_origin: routeOrigin,+ contract_version: 12, backend, model_id: 'gpt-test', route_origin: routeOrigin,manual_override: routeOrigin === 'manual' ? { hops } : null,current: hops[0], supply_state: 'ok',chain: hops.map((hop) => ({ ...hop, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null })),diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxindex d9f4d7b82..cd5c4315d 100644--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -57,7 +57,7 @@ const sources: Source[] = [},];const chain: AgentChain = { manual_override: {hops:[{source_id:"src_a",model_id:"claude-opus-5"},{source_id:"src_b",model_id:"opus-5"}]}, route_origin: "manual" as const,- contract_version: 11,+ contract_version: 12,backend: "claude",model_id: "opus-5",current: { source_id: "src_b", model_id: "opus-5" },diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsxindex d1102661f..b27f2e518 100644--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx@@ -15,7 +15,7 @@ import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';import type { RouteHop, TurnProvenance } from './types';const record: TurnProvenance = {- contract_version: 11, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',+ contract_version: 12, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },};diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex 90176016a..63103c1f7 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -31,7 +31,7 @@ const runtime = (? 'unresolved' as const: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;return {- contract_version: 11,+ contract_version: 12,...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 85b5d4a6e..991b9643c 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -48,7 +48,7 @@ const manifest = {} satisfies RuntimeManifest;const runtime: RuntimeDependency = {- contract_version: 11,+ contract_version: 12,manifest,status: { installed_version: '1', verified: true, health: 'ok' },};@@ -119,7 +119,7 @@ const takeoverAgent: AgentSupply = {};const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head',model_id:'gpt-5.6-sol'},{source_id:'src_relay',model_id:'gpt-5.6-sol'}]}, route_origin: "manual" as const,- contract_version: 11,+ contract_version: 12,backend: 'codex',model_id: 'gpt-5.6-sol',current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },@@ -222,7 +222,7 @@ const routedHubAgent: AgentSupply = {const routedChain: AgentChain = {manual_override: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] },route_origin: 'manual' as const,- contract_version: 11,+ contract_version: 12,backend: 'claude',model_id: routedModelId,current: { source_id: retainedSource.id, model_id: routedModelId },diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex a2e1df5b3..365ec8414 100644--- a/ui/src/components/settings/models/SupplyGraph.test.ts+++ b/ui/src/components/settings/models/SupplyGraph.test.ts@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};@@ -47,7 +47,7 @@ const agent: AgentSupply = {};const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({ manual_override: {hops:[{source_id:'native',model_id:'model-a'},{source_id:'relay',model_id:'model-a'},{source_id:'unused',model_id:'model-a'}]}, route_origin: "manual" as const,- contract_version: 11,+ contract_version: 12,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 61902b1b2..fa7e14c91 100644--- a/ui/src/components/settings/models/apiFailure.test.ts+++ b/ui/src/components/settings/models/apiFailure.test.ts@@ -33,7 +33,7 @@ afterEach(() => {describe('apiFailure — whether the route named the failure', () => {it('posts installation to the dedicated runtime route', async () => {const runtime = {- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },} as const;diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex 9ffe4994d..3ebedfed9 100644--- a/ui/src/components/settings/models/gatewayAdoption.test.ts+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({});const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },});diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.tsindex bf6da53b7..d794c0ec8 100644--- a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts+++ b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts@@ -24,7 +24,7 @@ const source: Source = {};const report: RouteReport = {chain: {- contract_version: 11,+ contract_version: 12,backend: "claude",model_id: "模型/opus",manual_override: null,diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.tsindex 23ff4039c..d4c914abb 100644--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({});const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({- contract_version: 11,+ contract_version: 12,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex f4ec5696b..41b9f9f08 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -10,8 +10,8 @@// and the PR records the server implementation and feature-flag activation// edge. The client never synthesizes a fallback payload shape.-export const CONTRACT_VERSION = 11 as const;-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11] as const;+export const CONTRACT_VERSION = 12 as const;+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12] as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 0231f1eef..52129603c 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -549,6 +549,8 @@ _MEMBER_HTTP_RULES = tuple(("GET", r"^/api/models/(?:events|usage)$"),("GET", r"^/api/models/quota$"),("POST", r"^/api/models/quota/refresh$"),+ ("GET", r"^/api/models/hosted-tools$"),+ ("PUT", r"^/api/models/hosted-tools/[^/]+$"),("POST", r"^/api/models/oauth/(?:start|submit|cancel)$"),("GET", r"^/api/models/oauth/status/[^/]+$"),("POST", r"^/api/models/migration/(?:scan|apply)$"),diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.pyindex e680dcbdf..de50e2781 100644--- a/vibe/backend_model_catalog.py+++ b/vibe/backend_model_catalog.py@@ -1,9 +1,11 @@from __future__ import annotationsimport asyncio+import functoolsimport hashlibimport jsonimport logging+import mathimport osimport reimport stat@@ -14,12 +16,15 @@ import urllib.errorimport urllib.requestimport weakreffrom contextlib import contextmanager+from dataclasses import dataclass+from datetime import datefrom pathlib import Pathfrom types import MappingProxyType-from typing import TYPE_CHECKING, Any, Callable, Final, Iterable, Mapping, Sequence+from typing import TYPE_CHECKING, Any, Callable, Final, Iterable, Literal, Mapping, Sequencefrom config import pathsfrom config.atomic_io import write_atomic+from core.agent_core.messages import HOSTED_TOOLS, PROTOCOLSfrom core.command_runner import run_supervised_commandfrom vibe.claude_model_catalog import (DEFAULT_CLAUDE_MODEL_ALIASES,@@ -544,10 +549,24 @@ def load_bundled_catalog(path: Path | None = None) -> dict[str, Any]:def bundled_catalog_reasoning_efforts_by_model() -> Mapping[str, tuple[str, ...]]:"""Index bundled reasoning-effort rows without changing their declarations."""- efforts_by_model: dict[str, tuple[str, ...]] = {}+ return _bundled_catalog_lists_by_model("reasoning_efforts")+++def bundled_catalog_client_presets_by_model() -> Mapping[str, tuple[str, ...]]:+ """Index bundled client presets: efforts a client maps before sending.++ A preset such as Codex ``ultra`` stays in its row's ``reasoning_efforts``+ because the client's own menu offers it, but it is never a wire tier.+ """++ return _bundled_catalog_lists_by_model("client_presets")+++def _bundled_catalog_lists_by_model(key: str) -> Mapping[str, tuple[str, ...]]:+ values_by_model: dict[str, tuple[str, ...]] = {}backends = load_bundled_catalog().get("backends")if not isinstance(backends, dict):- return MappingProxyType(efforts_by_model)+ return MappingProxyType(values_by_model)for backend in backends.values():models = backend.get("models") if isinstance(backend, dict) else Noneif not isinstance(models, list):@@ -556,14 +575,14 @@ def bundled_catalog_reasoning_efforts_by_model() -> Mapping[str, tuple[str, ...]if not isinstance(model, dict):continuemodel_id = model.get("id")- efforts = model.get("reasoning_efforts")+ values = model.get(key)if (isinstance(model_id, str)- and model_id not in efforts_by_model- and isinstance(efforts, list)+ and model_id not in values_by_model+ and isinstance(values, list)):- efforts_by_model[model_id] = tuple(efforts)- return MappingProxyType(efforts_by_model)+ values_by_model[model_id] = tuple(values)+ return MappingProxyType(values_by_model)def bundled_catalog_reasoning_efforts_for_model(@@ -574,6 +593,253 @@ def bundled_catalog_reasoning_efforts_for_model(return bundled_catalog_reasoning_efforts_by_model().get(model_id)+# The ``providers`` section (model-hub-capability-model.md §4,+# docs/plans/model-hub-contracts/provider-overlay.schema.json): what a provider+# offers per model family and protocol. Priors only; whether a Source carries a+# feature is evidence. Read from the bundled file alone, never the remote copy:+# its declarations go on the wire and must be the ones this build shipped with.+_HOSTED_TOOL_PRICE_UNITS = ("call", "search", "post", "profile")+_OVERLAY_TOKEN = re.compile(r"\S(?:.*\S)?")+_OVERLAY_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")+_OVERLAY_URL = re.compile(r"https://[^\s/?#]+(?:[/?#]\S*)?")+++@dataclass(frozen=True)+class HostedToolPriceComponent:+ unit: str+ usd_per_1k: float+++@dataclass(frozen=True)+class HostedToolPrice:+ """A provider's list price for one hosted tool, with the page it was read from."""++ unit: str+ usd_per_1k: float+ as_of: date+ url: str+ extra: tuple[HostedToolPriceComponent, ...] = ()+++@dataclass(frozen=True)+class HostedToolSpec:+ """One hosted tool as a provider offers it on one protocol.++ ``price`` is None when no list price is known, which is never a price of+ zero. ``include`` lists the Responses ``include`` values the tool needs.+ """++ declaration_json: str+ price: HostedToolPrice | None+ include: tuple[str, ...]++ @property+ def declaration(self) -> dict[str, Any]:+ """A fresh copy of the wire declaration, safe to place in a request body."""++ return json.loads(self.declaration_json)+++@dataclass(frozen=True)+class ProviderModelOverlay:+ """One model family of a provider; ``wire_efforts`` None defers to models.dev."""++ match_kind: Literal["prefix", "id"]+ match_value: str+ wire_efforts: tuple[str, ...] | None+ hosted_tools: Mapping[str, Mapping[str, HostedToolSpec]]++[email protected]_cache(maxsize=1)+def bundled_provider_overlay() -> Mapping[str, tuple[ProviderModelOverlay, ...]]:+ """Each vendor's model families from the bundled ``providers`` section.++ An invalid vendor entry is left out with a warning, and a ``providers``+ value that is not an object disables only the overlay; backend rows never+ depend on this section.+ """++ try:+ payload = json.loads(get_bundled_catalog_path().read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError):+ return MappingProxyType({})+ if not isinstance(payload, dict) or "providers" not in payload:+ return MappingProxyType({})+ providers = payload["providers"]+ if not isinstance(providers, dict):+ logger.warning("Backend model catalog providers section is not an object; the provider overlay is disabled")+ return MappingProxyType({})+ overlay: dict[str, tuple[ProviderModelOverlay, ...]] = {}+ for vendor, raw_vendor in providers.items():+ try:+ overlay[_overlay_vendor_id(vendor)] = _overlay_vendor_models(raw_vendor)+ except ValueError as exc:+ logger.warning("Provider overlay entry %r is disabled: %s", vendor, exc)+ return MappingProxyType(overlay)+++def provider_overlay_entry(vendor: str, model_id: str) -> ProviderModelOverlay | None:+ """Return the first model family of ``vendor`` that matches ``model_id``."""++ from core.handlers.model_hub.identifiers import normalized_model_id++ model = normalized_model_id(model_id)+ for entry in bundled_provider_overlay().get(vendor.strip().lower(), ()):+ if (entry.match_kind == "id" and model == entry.match_value) or (+ entry.match_kind == "prefix" and model.startswith(entry.match_value)+ ):+ return entry+ return None+++def hosted_tool_spec(vendor: str, protocol: str, model_id: str, tool: str) -> HostedToolSpec | None:+ """Return the matching family's declaration, price and include for one tool."""++ entry = provider_overlay_entry(vendor, model_id)+ if entry is None:+ return None+ return entry.hosted_tools.get(protocol, {}).get(tool)+++def _overlay_vendor_id(vendor: str) -> str:+ from config.v2_config import normalize_model_hub_vendor_id++ try:+ canonical = normalize_model_hub_vendor_id(vendor)+ except ValueError:+ canonical = None+ if canonical != vendor:+ raise ValueError("the key is not a canonical Source vendor id")+ return vendor+++def _overlay_vendor_models(raw: object) -> tuple[ProviderModelOverlay, ...]:+ vendor = _overlay_object(raw, "vendor entry", required=("models",))+ models = vendor["models"]+ if not isinstance(models, list):+ raise ValueError("models must be a list")+ return tuple(_overlay_model(item) for item in models)+++def _overlay_model(raw: object) -> ProviderModelOverlay:+ model = _overlay_object(raw, "model entry", required=("match",), optional=("wire_efforts", "hosted_tools"))+ match = _overlay_object(model["match"], "match", optional=("prefix", "id"))+ if len(match) != 1:+ raise ValueError("match must name exactly one of prefix or id")+ ((match_kind, match_value),) = match.items()+ wire_efforts = model.get("wire_efforts")+ protocols = _overlay_object(model.get("hosted_tools", {}), "hosted_tools", optional=PROTOCOLS)+ hosted_tools: dict[str, Mapping[str, HostedToolSpec]] = {}+ for protocol, raw_tools in protocols.items():+ tools = _overlay_object(raw_tools, f"hosted_tools.{protocol}", optional=HOSTED_TOOLS)+ hosted_tools[protocol] = MappingProxyType(+ {tool: _overlay_hosted_tool(spec, f"{protocol}.{tool}") for tool, spec in tools.items()}+ )+ return ProviderModelOverlay(+ match_kind=match_kind,+ match_value=_overlay_token(match_value, f"match.{match_kind}"),+ wire_efforts=None if wire_efforts is None else _overlay_tokens(wire_efforts, "wire_efforts"),+ hosted_tools=MappingProxyType(hosted_tools),+ )+++def _overlay_hosted_tool(raw: object, what: str) -> HostedToolSpec:+ spec = _overlay_object(raw, what, required=("declaration",), optional=("price", "include"))+ declaration = spec["declaration"]+ if not isinstance(declaration, dict):+ raise ValueError(f"{what}.declaration must be an object")+ _overlay_token(declaration.get("type"), f"{what}.declaration.type")+ return HostedToolSpec(+ declaration_json=json.dumps(declaration, ensure_ascii=False, allow_nan=False),+ price=_overlay_price(spec["price"], f"{what}.price") if "price" in spec else None,+ include=_overlay_tokens(spec.get("include", []), f"{what}.include"),+ )+++def _overlay_price(raw: object, what: str) -> HostedToolPrice:+ price = _overlay_object(raw, what, required=("unit", "usd_per_1k", "as_of", "url"), optional=("extra",))+ as_of = _overlay_date(price["as_of"], f"{what}.as_of")+ url = price["url"]+ if not isinstance(url, str) or not _OVERLAY_URL.fullmatch(url):+ raise ValueError(f"{what}.url must be an https URL")+ extra = price.get("extra", [])+ if not isinstance(extra, list):+ raise ValueError(f"{what}.extra must be a list")+ unit, usd_per_1k = _overlay_price_component(price, what)+ return HostedToolPrice(+ unit=unit,+ usd_per_1k=usd_per_1k,+ as_of=as_of,+ url=url,+ extra=tuple(+ HostedToolPriceComponent(+ *_overlay_price_component(+ _overlay_object(item, f"{what}.extra", required=("unit", "usd_per_1k")),+ f"{what}.extra",+ )+ )+ for item in extra+ ),+ )+++def _overlay_date(value: object, what: str) -> date:+ if isinstance(value, str) and _OVERLAY_DATE.fullmatch(value):+ try:+ return date.fromisoformat(value)+ except ValueError:+ pass+ raise ValueError(f"{what} must be a YYYY-MM-DD date")+++def _overlay_price_component(price: Mapping[str, Any], what: str) -> tuple[str, float]:+ unit = price["unit"]+ usd_per_1k = price["usd_per_1k"]+ if not isinstance(unit, str) or unit not in _HOSTED_TOOL_PRICE_UNITS:+ raise ValueError(f"{what}.unit is not a known price unit")+ if (+ not isinstance(usd_per_1k, (int, float))+ or isinstance(usd_per_1k, bool)+ or not math.isfinite(usd_per_1k)+ or usd_per_1k < 0+ ):+ raise ValueError(f"{what}.usd_per_1k must be a number of at least 0")+ return unit, float(usd_per_1k)+++def _overlay_object(+ value: object,+ what: str,+ *,+ required: Sequence[str] = (),+ optional: Sequence[str] = (),+) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise ValueError(f"{what} must be an object")+ missing = [key for key in required if key not in value]+ if missing:+ raise ValueError(f"{what} is missing {', '.join(missing)}")+ unknown = sorted(key for key in value if key not in required and key not in optional)+ if unknown:+ raise ValueError(f"{what} has unknown keys {', '.join(unknown)}")+ return value+++def _overlay_tokens(value: object, what: str) -> tuple[str, ...]:+ if not isinstance(value, list):+ raise ValueError(f"{what} must be a list")+ tokens = tuple(_overlay_token(item, what) for item in value)+ if len(set(tokens)) != len(tokens):+ raise ValueError(f"{what} repeats a value")+ return tokens+++def _overlay_token(value: object, what: str) -> str:+ if not isinstance(value, str) or not _OVERLAY_TOKEN.fullmatch(value):+ raise ValueError(f"{what} must be a nonblank string without surrounding whitespace")+ return value++def load_cached_remote_catalog(*,schedule_refresh: bool = True,@@ -1465,6 +1731,14 @@ def _validate_catalog_model_entry(item: object, backend: str) -> None:if not isinstance(efforts, list) or any(not isinstance(value, str) or not value.strip() for value in efforts):raise ValueError(f"Backend model catalog contains invalid reasoning efforts: {backend}/{raw_id}")+ presets = item.get("client_presets")+ if presets is not None and (+ not isinstance(presets, list)+ or any(not isinstance(value, str) or not value.strip() for value in presets)+ or not {value.strip() for value in presets} <= {value.strip() for value in efforts or ()}+ ):+ raise ValueError(f"Backend model catalog contains invalid client presets: {backend}/{raw_id}")+def _normalize_model_entry(item: object) -> dict[str, Any]:if isinstance(item, str):@@ -1490,6 +1764,16 @@ def _normalize_model_entry(item: object) -> dict[str, Any]:efforts = _coerce_reasoning_efforts(raw_efforts)if raw_efforts is not None:entry["reasoning_efforts"] = efforts+ # A preset is a menu effort the client maps before sending, so one the row+ # does not offer is invalid; the strict reader rejects it.+ raw_presets = item.get("client_presets")+ presets = [+ preset+ for preset in _dedupe_str_values(raw_presets if isinstance(raw_presets, list) else ())+ if preset in efforts+ ]+ if presets:+ entry["client_presets"] = presetsreturn entrydiff --git a/vibe/data/backend_models.json b/vibe/data/backend_models.jsonindex 9a346f549..98145ba9c 100644--- a/vibe/data/backend_models.json+++ b/vibe/data/backend_models.json@@ -32,12 +32,12 @@},"codex": {"models": [- {"id": "gpt-6-astra", "label": "GPT-6-Astra", "priority": 1, "visibility": "list", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]},+ {"id": "gpt-6-astra", "label": "GPT-6-Astra", "priority": 1, "visibility": "list", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"], "client_presets": ["ultra"]},{"id": "gpt-6.1-sol", "label": "GPT-6.1-Sol", "priority": 2, "visibility": "list", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},{"id": "gpt-6-sol", "label": "GPT-6-Sol", "priority": 3, "visibility": "list", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},{"id": "gpt-6-luna", "label": "GPT-6-Luna", "priority": 4, "visibility": "list", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},- {"id": "gpt-5.6-sol", "label": "GPT-5.6-Sol", "priority": 6, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]},- {"id": "gpt-5.6-terra", "label": "GPT-5.6-Terra", "priority": 7, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"]},+ {"id": "gpt-5.6-sol", "label": "GPT-5.6-Sol", "priority": 6, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"], "client_presets": ["ultra"]},+ {"id": "gpt-5.6-terra", "label": "GPT-5.6-Terra", "priority": 7, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"], "client_presets": ["ultra"]},{"id": "gpt-5.6-luna", "label": "GPT-5.6-Luna", "priority": 8, "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"]},{"id": "gpt-5.5", "label": "GPT-5.5", "priority": 12, "reasoning_efforts": ["low", "medium", "high", "xhigh"]},{"id": "gpt-5.4", "label": "GPT-5.4", "priority": 16, "reasoning_efforts": ["low", "medium", "high", "xhigh"]},@@ -45,5 +45,63 @@{"id": "gpt-5.2", "label": "GPT-5.2", "priority": 29, "visibility": "hide", "reasoning_efforts": ["low", "medium", "high", "xhigh"]}]}+ },+ "providers": {+ "anthropic": {+ "models": [+ {+ "match": {"prefix": "claude-"},+ "wire_efforts": null,+ "hosted_tools": {+ "anthropic": {+ "web_search": {+ "declaration": {"type": "web_search_20250305", "name": "web_search"},+ "price": {"unit": "search", "usd_per_1k": 10, "as_of": "2026-10-13", "url": "https://platform.claude.com/docs/en/about-claude/pricing"}+ }+ }+ }+ }+ ]+ },+ "openai": {+ "models": [+ {+ "match": {"prefix": "gpt-"},+ "wire_efforts": null,+ "hosted_tools": {+ "openai_responses": {+ "web_search": {+ "declaration": {"type": "web_search"},+ "include": ["web_search_call.action.sources"],+ "price": {"unit": "call", "usd_per_1k": 10, "as_of": "2026-10-13", "url": "https://developers.openai.com/api/docs/pricing"}+ },+ "image_generation": {+ "declaration": {"type": "image_generation", "partial_images": 2}+ }+ }+ }+ }+ ]+ },+ "xai": {+ "models": [+ {+ "match": {"prefix": "grok-4"},+ "wire_efforts": null,+ "hosted_tools": {+ "openai_responses": {+ "web_search": {+ "declaration": {"type": "web_search"},+ "price": {"unit": "call", "usd_per_1k": 5, "as_of": "2026-10-13", "url": "https://docs.x.ai/developers/pricing"}+ },+ "x_search": {+ "declaration": {"type": "x_search"},+ "price": {"unit": "post", "usd_per_1k": 5, "extra": [{"unit": "profile", "usd_per_1k": 10}], "as_of": "2026-10-13", "url": "https://docs.x.ai/developers/pricing"}+ }+ }+ }+ }+ ]+ }}}diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex d668c6a9b..bc2c481be 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -294,6 +294,12 @@ class ModelHubRemoteService:async def quota_summary(self, *, force: bool = False) -> dict:return await _rpc("quota_summary", {"force": force})+ async def hosted_tools_status(self) -> dict:+ return await _rpc("hosted_tools_status", {})++ async def set_hosted_tool(self, tool: str, setting: object) -> dict:+ return await _rpc("set_hosted_tool", {"tool": tool, "setting": setting})+def agent_chain(self, backend: str, model_id: str) -> dict:return _rpc_sync("get_agent_chain",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 586a48d63..dde80643c 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5153,6 +5153,33 @@ async def model_hub_quota_refresh(starlette_request: FastAPIRequest):return await _dispatch_native_ui_request(starlette_request, handler)[email protected]("/api/models/hosted-tools", include_in_schema=False)+async def model_hub_hosted_tools_get(starlette_request: FastAPIRequest):+ async def handler():+ from core.handlers.model_hub import ModelHubError++ try:+ return _model_hub_success(**await _model_hub_service().hosted_tools_status())+ except ModelHubError as exc:+ return _model_hub_error(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++[email protected]("/api/models/hosted-tools/{tool}", include_in_schema=False)+async def model_hub_hosted_tool_put(tool: str, starlette_request: FastAPIRequest):+ async def handler():+ from core.handlers.model_hub import ModelHubError++ try:+ status = await _model_hub_service().set_hosted_tool(tool, _model_hub_json_object("invalid_parameter"))+ return _model_hub_success(**status)+ except ModelHubError as exc:+ return _model_hub_error(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++@app.route("/api/models/agents/<backend>/chains", methods=["GET"])def model_hub_agent_chains_get(backend):from core.handlers.model_hub import ModelHubError