Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(model-hub): hosted tools v2 contracts, passive evidence and the Tools tab (#2638)

Call White4f31de3d4a33
diff --git a/config/v2_config.py b/config/v2_config.py
index bdee63684..1d4b48170 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -13,6 +13,7 @@ from dataclasses import dataclass, field, fields, replace
from datetime import datetime
from pathlib import Path
from typing import (
+ Any,
Callable,
ClassVar,
Iterator,
@@ -35,7 +36,6 @@ from config.platform_registry import (
supported_platform_ids,
supported_platform_set,
)
-from core.agent_core.messages import HOSTED_TOOLS
from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, AgentBackend, DEFAULT_AGENT_BACKEND
from modules.im.base import BaseIMConfig
from vibe.i18n import normalize_language
@@ -3033,8 +3033,10 @@ class ModelHubAgentSupplyConfig:
return payload
-# The hosted-tool catalog names are owned by the C-1 contract.
-MODEL_HUB_HOSTED_TOOLS: tuple[str, ...] = HOSTED_TOOLS
+# Model Hub's hosted-tool catalog (vibey-hosted-tools.md §2): two search tools a hop may run natively or
+# through the executor, and the direct image tool.
+MODEL_HUB_SEARCH_TOOLS: tuple[str, ...] = ("web_search", "x_search")
+MODEL_HUB_HOSTED_TOOLS: tuple[str, ...] = (*MODEL_HUB_SEARCH_TOOLS, "image_generate")
def _drop_vibey_client_presets(agent: "ModelHubAgentSupplyConfig") -> None:
@@ -3057,66 +3059,129 @@ def _drop_vibey_client_presets(agent: "ModelHubAgentSupplyConfig") -> None:
]
+def is_model_hub_source_id(value: object) -> bool:
+ """A Source id as Model Hub mints it, whether or not that Source exists now."""
+
+ return isinstance(value, str) and re.fullmatch(r"src_[a-z0-9]{8,}", value) is not None
+
+
+def is_model_hub_model_id(value: object) -> bool:
+ """A model id already in its canonical spelling, by the one admission rule (``canonical_model_id``)."""
+
+ from core.handlers.model_hub.identifiers import canonical_model_id
+
+ return isinstance(value, str) and canonical_model_id(value) == value
+
+
+def model_hub_executor_order(value: object, *, tool: str) -> tuple[str, ...]:
+ """A saved executor order: distinct Source ids. The one grammar the config loader and the API share."""
+
+ if not isinstance(value, list) or not all(is_model_hub_source_id(item) for item in value) or len(set(value)) != len(value):
+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.executor_order' must be distinct Source ids")
+ return tuple(value)
+
+
+@dataclass(frozen=True)
+class ModelHubImageModelChoice:
+ """The image model a user chose as ``image_generate``'s default."""
+
+ source_id: str
+ model_id: str
+
+ @classmethod
+ def from_payload(cls, payload: object, *, tool: str) -> "ModelHubImageModelChoice":
+ if (
+ not isinstance(payload, dict)
+ or set(payload) != {"source_id", "model_id"}
+ or not is_model_hub_source_id(payload["source_id"])
+ or not is_model_hub_model_id(payload["model_id"])
+ ):
+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.default_model' must name a source_id and model_id")
+ return cls(source_id=payload["source_id"], model_id=payload["model_id"])
+
+ def to_payload(self) -> dict:
+ return {"source_id": self.source_id, "model_id": self.model_id}
+
+
@dataclass(frozen=True)
class ModelHubHostedToolConfig:
- """One hosted tool's user toggle (``vibey-hosted-tools.md`` §3.3).
+ """One hosted tool's user settings (``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`` defaults to on. ``executor_order`` (search tools) is the Source order the user wants executors
+ tried in, None for automatic; ``default_image`` (``image_generate``, persisted as ``default_model``) is the
+ chosen default image model, None for the catalog default. Both are saved values, never resolved ones.
"""
- enabled: bool = False
- executor: Optional[ModelHubRouteHopConfig] = None
+ enabled: bool = True
+ executor_order: Optional[tuple[str, ...]] = None
+ default_image: Optional[ModelHubImageModelChoice] = 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):
+ """Read one entry; fields it does not know are ignored with a warning, the ones it knows are kept."""
+
+ if not isinstance(payload, dict):
+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must be an object")
+ known = {"enabled"} | ({"executor_order"} if tool in MODEL_HUB_SEARCH_TOOLS else {"default_model"})
+ unknown = set(payload) - known
+ if unknown:
+ logger.warning("Config 'model_hub.hosted_tools.%s' ignores unknown fields %s", tool, sorted(unknown))
+ enabled = payload.get("enabled", True)
+ if not isinstance(enabled, bool):
raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")
- executor = payload["executor"]
+ # Only the fields this tool knows are read; another tool's field was ignored above.
+ order = payload.get("executor_order") if "executor_order" in known else None
+ default = payload.get("default_model") if "default_model" in known else None
return cls(
- enabled=payload["enabled"],
- executor=None if executor is None else ModelHubRouteHopConfig.from_payload(executor),
+ enabled=enabled,
+ executor_order=model_hub_executor_order(order, tool=tool) if order is not None else None,
+ default_image=ModelHubImageModelChoice.from_payload(default, tool=tool) if default is not None else None,
)
def to_payload(self) -> dict:
- return {"enabled": self.enabled, "executor": None if self.executor is None else self.executor.to_payload()}
+ out: dict[str, Any] = {"enabled": self.enabled}
+ if self.executor_order is not None:
+ out["executor_order"] = list(self.executor_order)
+ if self.default_image is not None:
+ out["default_model"] = self.default_image.to_payload()
+ return out
-def _hosted_tools_from_payload(
- payload: object,
- sources: list["ModelHubSourceConfig"],
-) -> dict[str, ModelHubHostedToolConfig]:
+def _hosted_tools_from_payload(section: Mapping[str, Any]) -> 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.
+ Absent means every tool takes its defaults (on). An unknown tool key, or an unknown field inside an entry, is
+ ignored with a warning, and the fields the loader knows are kept, so a user's opt-out survives. A broken section
+ or entry turns its tools off, with a warning: hosted tools reach third parties and cost money, so damage never
+ turns one on. Sources and Agents still load.
"""
- if payload is None:
+ if "hosted_tools" not in section:
return {}
+ payload = section["hosted_tools"]
+ # Present but not an object, ``null`` included, is damage, never absence.
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}
+ return {tool: ModelHubHostedToolConfig(enabled=False) for tool in MODEL_HUB_HOSTED_TOOLS}
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)
+ logger.warning("Config 'model_hub.hosted_tools' ignores an unknown tool %r", tool)
continue
try:
- entry = ModelHubHostedToolConfig.from_payload(raw, tool=tool)
+ tools[tool] = 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
+ tools[tool] = ModelHubHostedToolConfig(enabled=False)
return tools
+def hosted_tool_setting(config: "ModelHubConfig", tool: str) -> ModelHubHostedToolConfig:
+ """One tool's settings, its defaults when the config says nothing."""
+
+ return config.hosted_tools.get(tool) or ModelHubHostedToolConfig()
+
+
@dataclass
class ModelHubConfig:
# New installations enable the runtime. Disk loading promotes pre-marker
@@ -3134,7 +3199,7 @@ 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.
+ # Absent on every released config: absence means every hosted tool takes its defaults (on).
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
@@ -3256,7 +3321,7 @@ class ModelHubConfig:
sources=sources,
agents=agents,
runtime_default_applied=runtime_default_applied,
- hosted_tools=_hosted_tools_from_payload(payload.get("hosted_tools"), sources),
+ hosted_tools=_hosted_tools_from_payload(payload),
)
_drop_vibey_client_presets(config.agents["vibey"])
agents = config.agents
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index c6441e78b..330117856 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 v14 (2026-10-14).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v15 (2026-10-15).
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.py
index 90dd159dd..0a655c827 100644
--- a/core/handlers/model_hub/capability_evidence.py
+++ b/core/handlers/model_hub/capability_evidence.py
@@ -1,58 +1,58 @@
"""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.
+Evidence is passive: it is written only from real requests, never probed. At
+most one record per (Source, model, feature, status):
+
+* ``unsupported`` is routing state, written by a narrow rule on a real upstream
+ refusal (``evidence_rules.py``). It has no time limit. It stops applying only
+ when the user clears it, or when the wire stamp it was learned under no longer
+ matches (the Source's rendered engine entry, the engine release or the Avibe
+ release changed).
+* ``verified`` is display history: a real response carried the feature. It
+ never changes routing, survives wire changes, and records how the call ran.
+
+Absence is ``unknown``, and unknown is never negative (#2505). Records follow
+Source identity: 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 logging
import re
import threading
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Iterable, Literal, Mapping, Optional
+from typing import Any, Callable, 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
+logger = logging.getLogger(__name__)
+
+EVIDENCE_VERSION = 2
MAX_RECORDS = 4000
-OBSERVED_TTL_SECONDS = 7 * 24 * 3600
-PROBE_REVERIFY_AFTER_SECONDS = 30 * 24 * 3600
DETAIL_MAX_CHARS = 64
-# The engine stamp when the engine manifest cannot be read. It names no release,
-# so probe evidence taken under it, or checked against it, never vouches for a wire.
-UNKNOWN_ENGINE_STAMP = "unknown-engine"
+# A positive record is rewritten at most this often per key: each write rewrites the file.
+POSITIVE_REFRESH_SECONDS = 3600
FeatureKind = Literal["effort", "hosted_tool"]
EvidenceStatus = Literal["verified", "unsupported"]
-EvidenceBasis = Literal["probe", "observed"]
-RoutingStatus = Literal["verified", "unsupported", "unknown"]
-Staleness = Literal["wire", "age"]
+RoutingStatus = Literal["unsupported", "unknown"]
+ExecutionMode = Literal["native", "executor", "direct"]
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",),
+ # An image call is an ordinary tool call and result, so only its call is evidence.
+ "image_generate": ("call",),
}
+EXECUTION_MODES: frozenset[str] = frozenset({"native", "executor", "direct"})
_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
@@ -86,6 +86,17 @@ class EvidenceFeature:
def hosted(cls, tool: str, aspect: Literal["call", "replay"]) -> "EvidenceFeature":
return cls("hosted_tool", tool, aspect)
+ @classmethod
+ def from_payload(cls, payload: object) -> "EvidenceFeature":
+ """The exact shape ``payload()`` writes: ``{kind, name}`` for an effort, ``{kind, name, aspect}`` for a tool."""
+
+ if not isinstance(payload, Mapping):
+ raise ValueError("invalid evidence feature")
+ keys = {"kind", "name", "aspect"} if payload.get("kind") == "hosted_tool" else {"kind", "name"}
+ if set(payload) != keys:
+ raise ValueError("invalid evidence feature")
+ return cls(payload["kind"], payload["name"], payload.get("aspect"))
+
def payload(self) -> dict[str, str]:
out = {"kind": self.kind, "name": self.name}
if self.aspect is not None:
@@ -99,38 +110,35 @@ class EvidenceRecord:
model_id: str
feature: EvidenceFeature
status: EvidenceStatus
- basis: EvidenceBasis
observed_at: datetime
- engine: str
- shape: int
+ wire: str
source_identity: str
detail: Optional[str] = None
+ """``unsupported`` only: the HTTP status and upstream machine code, never upstream text."""
+ mode: Optional[ExecutionMode] = None
+ """``verified`` only: how the call ran."""
def __post_init__(self) -> None:
- for name in ("source_id", "model_id", "engine", "source_identity"):
+ for name in ("source_id", "model_id", "wire", "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.status == "unsupported":
+ if self.mode is not None or not isinstance(self.detail, str):
+ raise ValueError("a refusal carries its detail and no mode")
+ if not 0 < len(self.detail) <= DETAIL_MAX_CHARS:
+ raise ValueError(f"evidence detail is at most {DETAIL_MAX_CHARS} characters")
+ elif self.status == "verified":
+ if self.detail is not None or self.mode not in EXECUTION_MODES:
+ raise ValueError("a success carries its mode and no detail")
+ else:
+ raise ValueError("invalid evidence status")
if self.observed_at.tzinfo is None:
raise ValueError("evidence time must be timezone-aware")
- try:
- # Its expiry and re-verify instants must be representable, or every
- # read that resolves it would fail; such a record reads as unknown.
- self.observed_at + timedelta(seconds=max(OBSERVED_TTL_SECONDS, PROBE_REVERIFY_AFTER_SECONDS))
- except OverflowError:
- raise ValueError("evidence time is out of range") from None
@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 key(self) -> tuple[str, str, str, str, str, str]:
+ return evidence_key(self.source_id, self.model_id, self.feature, self.status)
def payload(self) -> dict[str, Any]:
out: dict[str, Any] = {
@@ -139,63 +147,52 @@ class EvidenceRecord:
"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,
+ "basis": "observed",
+ "observed_at": utc_text(self.observed_at),
+ "wire": self.wire,
"source_identity": self.source_identity,
}
if self.detail is not None:
out["detail"] = self.detail
+ if self.mode is not None:
+ out["mode"] = self.mode
return out
@classmethod
def from_payload(cls, payload: Any) -> "EvidenceRecord":
+ # Records an rc build wrote (version 1: probe basis, engine and shape) do not validate and are pruned.
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",
+ "version", "source_id", "model_id", "feature", "status", "basis", "observed_at", "wire",
+ "source_identity", "detail", "mode",
}
- if set(payload) - allowed:
+ if set(payload) - allowed or payload.get("basis") != "observed":
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")),
+ feature=EvidenceFeature.from_payload(payload.get("feature")),
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"),
+ wire=payload.get("wire"),
source_identity=payload.get("source_identity"),
detail=payload.get("detail"),
+ mode=payload.get("mode"),
)
-@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.
- """
+def evidence_key(
+ source_id: str, model_id: str, feature: EvidenceFeature, status: EvidenceStatus
+) -> tuple[str, str, str, str, str, str]:
+ return (source_id, model_id, feature.kind, feature.name, feature.aspect or "", status)
- status: RoutingStatus
- stale: Optional[Staleness] = None
- record: Optional[EvidenceRecord] = None
- changes_at: Optional[datetime] = None
- """When this record stops reading as it does now (observed expiry, probe re-verify mark); None when nothing is scheduled."""
-
-UNKNOWN = EvidenceView("unknown")
+def utc_text(moment: datetime) -> str:
+ return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def identity_digest(source: ModelHubSourceConfig) -> str:
@@ -205,48 +202,50 @@ def identity_digest(source: ModelHubSourceConfig) -> str:
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.
- if age > OBSERVED_TTL_SECONDS:
- return UNKNOWN
- return EvidenceView("unsupported", None, record, record.observed_at + timedelta(seconds=OBSERVED_TTL_SECONDS))
- wire_stale = (
- record.engine != engine
- or record.shape != shape
- or UNKNOWN_ENGINE_STAMP in (record.engine, engine)
- )
- stale: Optional[Staleness] = "wire" if wire_stale else "age" if age > PROBE_REVERIFY_AFTER_SECONDS else None
- changes_at = (
- record.observed_at + timedelta(seconds=PROBE_REVERIFY_AFTER_SECONDS) if stale is None else None
+def render_fields(source: ModelHubSourceConfig, model_id: str) -> tuple[Any, ...]:
+ """What the engine entry renders for this (Source, model) beyond the Source identity.
+
+ The renderer (``vibe/model_hub_runtime/config.py``) reads, per Source: the vendor, protocol, base URL and
+ credential (whose auth scheme is fixed per credential ref), all in ``source_identity``; and, per model, the
+ reasoning tiers it registers (``thinking.levels``), which decide whether the engine forwards or strips an
+ effort. Those tiers are the only Source-config input the identity does not cover, so they join the stamp.
+ Not here: which models are registered (membership does not change how a registered model is sent), the
+ routing prefix and reload marker (engine-internal), and the text-only marking (from the models.dev copy, not
+ Source config; it only replaces images in tool results). A future per-Source engine flag joins here.
+ """
+
+ listed = next((model for model in source.models if model.id == model_id), None)
+ return (tuple(listed.reasoning_efforts) if listed is not None and not listed.retired else (),)
+
+
+def wire_stamp(*, engine: str, avibe: str, source: ModelHubSourceConfig, model_id: str) -> str:
+ """The wire a record is observed under: engine release, Avibe release, and the model's rendered fields."""
+
+ raw = json.dumps(
+ [engine, avibe, list(render_fields(source, model_id))], ensure_ascii=False, separators=(",", ":"), default=list,
)
- 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, changes_at)
+ return "sha256:" + hashlib.sha256(raw.encode("utf-8")).hexdigest()
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, when the store is built at controller
- startup, and memory is authoritative afterwards. No lookup ever touches the
- disk, so none can block the loop.
+ """The evidence records, held in memory and persisted to one small file.
+
+ Bounded by Sources x models x features x two statuses. The controller is the
+ only writer (the gateway's rules run there; other processes reach it over
+ RPC), so the file is read once, when the store is built at controller
+ startup, and memory is authoritative afterwards. Lookups never touch the
+ disk. Writes rewrite the file, so callers run them off the loop.
+
+ Persistence order differs by kind, and both are deliberate:
+
+ * a refusal is routing state: memory takes it first, so the re-render that
+ follows cannot declare the refused feature again, and a failed file write
+ is logged rather than raised;
+ * a clear is what the user is shown: the file takes it first, and a failed
+ write raises with nothing changed, so it never comes back after a restart;
+ * a success is display history: memory takes every one at once, so every
+ read is current, and the file at most hourly per key. Memory is the one
+ source of success history; nothing projects it separately.
"""
def __init__(self, path: Path, *, max_records: int = MAX_RECORDS):
@@ -255,7 +254,12 @@ class CapabilityEvidenceStore:
self._lock = threading.RLock()
self._records: dict[tuple, EvidenceRecord] = {}
self._by_hop: dict[tuple[str, str], list[EvidenceRecord]] = {}
- self._remember(self._read_file())
+ records = self._read_file()
+ # The file's copy of each success, which throttles the next write of that key.
+ self._persisted: dict[tuple, EvidenceRecord] = {
+ key: record for key, record in records.items() if record.status == "verified"
+ }
+ self._remember(records)
def _read_file(self) -> dict[tuple, EvidenceRecord]:
try:
@@ -276,26 +280,25 @@ class CapabilityEvidenceStore:
by_hop: dict[tuple[str, str], list[EvidenceRecord]] = {}
for record in records.values():
by_hop.setdefault((record.source_id, record.model_id), []).append(record)
- # The index first: a reader that sees the new records also sees their index.
+ # Published snapshots are never mutated, so a reader needs no lock: a
+ # write builds the next snapshot and swaps the references, index first.
self._by_hop = by_hop
self._records = records
- def get(self, source_id: str, model_id: str, feature: EvidenceFeature) -> Optional[EvidenceRecord]:
- # Published snapshots are never mutated, so a reader needs no lock: a
- # write builds the next snapshot and swaps the references.
- return self._records.get((source_id, model_id, feature.kind, feature.name, feature.aspect or ""))
+ def get(
+ self, source_id: str, model_id: str, feature: EvidenceFeature, status: EvidenceStatus
+ ) -> Optional[EvidenceRecord]:
+ return self._records.get(evidence_key(source_id, model_id, feature, status))
- 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 refusal(
+ self, source: ModelHubSourceConfig, model_id: str, feature: EvidenceFeature, *, wire: str
+ ) -> Optional[EvidenceRecord]:
+ """The refusal that applies to this hop now: same identity, same wire stamp; None otherwise."""
+
+ record = self.get(source.id, model_id, feature, "unsupported")
+ if record is None or record.source_identity != identity_digest(source) or record.wire != wire:
+ return None
+ return record
def records(self) -> list[EvidenceRecord]:
return list(self._records.values())
@@ -305,22 +308,135 @@ class CapabilityEvidenceStore:
return list(self._by_hop.get((source_id, model_id), ()))
- def write(self, record: EvidenceRecord, *, live: Iterable[ModelHubSourceConfig]) -> None:
- """Replace the record for its key; prune records of removed or re-identified Sources.
+ def _write_locked(self, records: dict[tuple, EvidenceRecord], identities: Mapping[str, str]) -> list[EvidenceRecord]:
+ """The records to keep: current identities only, within the bound, successes evicted before refusals.
- Memory changes only once the file holds the new records.
+ A refusal is routing state, so the bound takes display history first; only refusals beyond the bound on
+ their own, which no real installation reaches, drop their oldest, with a warning.
"""
+ def by_age(items: Iterable[EvidenceRecord]) -> list[EvidenceRecord]:
+ return sorted(items, key=lambda item: item.observed_at)
+
+ kept = [
+ record for record in records.values() if identities.get(record.source_id) == record.source_identity
+ ]
+ if len(kept) <= self.max_records:
+ return by_age(kept)
+ refusals = by_age(record for record in kept if record.status == "unsupported")
+ if len(refusals) > self.max_records:
+ logger.warning("Model Hub capability evidence holds more refusals than its bound; the oldest are dropped")
+ refusals = refusals[-self.max_records :]
+ room = self.max_records - len(refusals)
+ successes = by_age(record for record in kept if record.status == "verified")[-room:] if room else []
+ return by_age([*refusals, *successes])
+
+ def _persist_locked(self, kept: Iterable[EvidenceRecord]) -> None:
+ """Write the kept records to the file; raises OSError. Every writer goes through here."""
+
+ kept = list(kept)
+ write_state_document(self.path, [item.payload() for item in kept])
+ self._persisted = {item.key: item for item in kept if item.status == "verified"}
+
+ @staticmethod
+ def _supersedes(record: EvidenceRecord, existing: Optional[EvidenceRecord]) -> bool:
+ """The one ordering rule every write follows: per key, the newest record of the current wire wins.
+
+ Writes settle concurrently, so arrival order is not time order. A record replaces one of another identity
+ (or, for a refusal, another wire) at once; within the same one, only a newer record replaces it.
+ """
+
+ if existing is None or existing.source_identity != record.source_identity:
+ return True
+ if record.status == "unsupported" and existing.wire != record.wire:
+ return True
+ return record.observed_at > existing.observed_at
+
+ def write_refusal(self, record: EvidenceRecord, *, live: Iterable[ModelHubSourceConfig]) -> None:
+ """Record a refusal: memory first, then the file; a failed write is logged, not raised."""
+
+ self.write_refusals([record], live=live)
+
+ def write_refusals(self, records: Iterable[EvidenceRecord], *, live: Iterable[ModelHubSourceConfig]) -> None:
+ records = list(records)
+ identities = {source.id: identity_digest(source) for source in live}
+ for record in records:
+ if record.status != "unsupported":
+ raise ValueError("write_refusals writes refusals only")
+ 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:
+ updated = dict(self._records)
+ for record in records:
+ if self._supersedes(record, updated.get(record.key)):
+ updated[record.key] = record
+ kept = self._write_locked(updated, identities)
+ self._remember({item.key: item for item in kept})
+ try:
+ self._persist_locked(kept)
+ except OSError:
+ # Routing state: memory keeps the refusal even when the file does not.
+ logger.warning("Model Hub could not persist capability evidence; it holds until restart")
+
+ def note_success(
+ self,
+ record: EvidenceRecord,
+ *,
+ live: Iterable[ModelHubSourceConfig],
+ now: datetime,
+ ) -> None:
+ """Record a real success: memory at once, the file at most hourly per key.
+
+ A success never replaces a refusal (they are separate keys), so a late
+ success cannot re-enable what a concurrent refusal took away.
+ """
+
+ if record.status != "verified":
+ raise ValueError("note_success writes successes only")
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")
+ return
with self._lock:
- records = {
- key: existing
- for key, existing in self._records.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])
+ if not self._supersedes(record, self._records.get(record.key)):
+ return
+ updated = dict(self._records)
+ updated[record.key] = record
+ kept = {item.key: item for item in self._write_locked(updated, identities)}
+ self._remember(kept)
+ persisted = self._persisted.get(record.key)
+ # Throttled only while the file holds a recent success of this same Source identity: the first success
+ # after an identity change is written at once, since the file's copy no longer counts.
+ if (
+ persisted is not None
+ and persisted.source_identity == record.source_identity
+ and (now - persisted.observed_at) < timedelta(seconds=POSITIVE_REFRESH_SECONDS)
+ ):
+ return
+ try:
+ self._persist_locked(kept.values())
+ except OSError:
+ logger.warning("Model Hub could not persist a hosted-tool success")
+
+ def clear(
+ self,
+ matches: Callable[[EvidenceRecord], bool],
+ *,
+ live: Iterable[ModelHubSourceConfig],
+ ) -> int:
+ """Remove the refusals ``matches`` selects: the file first, then memory; a failed write raises.
+
+ Returns how many were removed; zero writes nothing.
+ """
+
+ identities = {source.id: identity_digest(source) for source in live}
+ with self._lock:
+ removed = [
+ key for key, record in self._records.items() if record.status == "unsupported" and matches(record)
+ ]
+ if not removed:
+ return 0
+ updated = {key: record for key, record in self._records.items() if key not in set(removed)}
+ kept = self._write_locked(updated, identities)
+ self._persist_locked(kept)
self._remember({item.key: item for item in kept})
+ return len(removed)
diff --git a/core/handlers/model_hub/hosted_admission.py b/core/handlers/model_hub/hosted_admission.py
index 34c94dd39..097d2820d 100644
--- a/core/handlers/model_hub/hosted_admission.py
+++ b/core/handlers/model_hub/hosted_admission.py
@@ -20,15 +20,14 @@ change (the turn's pin identity claim, made atomically at final admission).
from __future__ import annotations
from dataclasses import dataclass
-from datetime import datetime
from functools import lru_cache
from typing import Any, Callable, Final, Mapping, Optional
from config.v2_config import ModelHubSourceConfig
from vibe.backend_model_catalog import HostedToolSpec, bundled_provider_overlay
-from .capability_evidence import HOSTED_TOOL_ASPECTS, CapabilityEvidenceStore, EvidenceFeature
-from .hosted_tools import runs_on
+from .capability_evidence import HOSTED_TOOL_ASPECTS
+from .hosted_tools import HostedEvidence, hosted_tool_facts
PIN_SOURCE_HEADER: Final = "x-avibe-pin-source"
# The served-hop model a continuation was rendered for; without it a pin is the launch's primary hop.
@@ -210,35 +209,29 @@ def admits(
source: ModelHubSourceConfig,
model_id: str,
spec_for: SpecLookup,
- evidence: CapabilityEvidenceStore,
- engine: str,
- shape: int,
- now: datetime,
+ evidence: HostedEvidence,
) -> bool:
- """Whether this hop runs every piece of hosted content and has current positive evidence for it.
-
- Where a tool may run is ``runs_on``, the rule hop resolution uses for
- native mode, so the two agree by construction; a declaration must also
- carry the type the overlay declares there. Evidence is read from memory.
+ """Whether this hop runs every piece of hosted content, by the hop's own facts (``hosted_tool_facts``).
+
+ Admission asks the one function that states a hop's facts, so the two agree
+ by construction: a declaration needs ``native`` assumed and the type the
+ overlay declares there, and a replayed item needs ``replay`` assumed, which
+ a current ``call`` refusal also withdraws. Evidence is read from memory, and
+ only refusals count: a tool the priors offer is assumed until a real request
+ refuses it.
"""
if not content:
return True
- def offered(tool: str) -> HostedToolSpec | None:
- return runs_on(source, model_id, tool, spec_for=spec_for)
-
- def verified(tool: str, aspect: str) -> bool:
- if aspect not in HOSTED_TOOL_ASPECTS.get(tool, ()):
+ def facts(tool: str):
+ if tool not in HOSTED_TOOL_ASPECTS:
# A generated image is never replayed verbatim, so nothing can admit it.
- return False
- view = evidence.view(
- source, model_id, EvidenceFeature.hosted(tool, aspect), engine=engine, shape=shape, now=now,
- )
- return view.status == "verified"
+ return None
+ return hosted_tool_facts(source, model_id, tool, evidence=evidence, spec_for=spec_for)
for tool, kind in content.calls:
- spec = offered(tool)
- if spec is None or spec.declaration["type"] != kind or not verified(tool, "call"):
+ stated = facts(tool)
+ if stated is None or stated.native != "assumed" or (stated.declaration or {}).get("type") != kind:
return False
- return all(offered(tool) is not None and verified(tool, "replay") for tool in content.replays)
+ return all((stated := facts(tool)) is not None and stated.replay == "assumed" for tool in content.replays)
diff --git a/core/handlers/model_hub/hosted_probe.py b/core/handlers/model_hub/hosted_probe.py
deleted file mode 100644
index 3bdb0acd5..000000000
--- a/core/handlers/model_hub/hosted_probe.py
+++ /dev/null
@@ -1,539 +0,0 @@
-"""The hosted-tool probes (``vibey-hosted-tools.md`` §3.2, capability model §3.3).
-
-A probe is the production request. Vibey's own builder makes it, from a probe
-resolution that pins the probed (Source, model) and carries the overlay's native
-declaration whatever the current evidence. Two things differ from a real turn:
-the transcript is one fixed user message, and on protocols that allow it the
-hosted tool is forced. Vibey's adapter reads the response, so a result is
-recognized only as the ``HostedToolBlock`` a real turn would keep. Nothing here
-parses a provider's wire format.
-
-The ``call`` probe asks the model to use the tool. When it verifies, the
-``replay`` probe sends that turn back with the tool's native payload in place,
-as Vibey replays history to the Source that produced it, and asks for a result
-without using the tool again.
-
-Every request the adapter sends runs on exactly one Source through Model Hub's
-own invocation, with no route and no failover. This module only builds the
-request, serves each pinned call to the adapter, and names the outcome; the
-service owns the calls themselves.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import base64
-import binascii
-import json
-import re
-from dataclasses import dataclass, replace
-from typing import Any, AsyncIterator, Awaitable, Callable, Final, Literal, Optional, Protocol
-
-import httpx
-
-from config.v2_config import ModelHubSourceConfig
-from core.agent_core.ai.provider import (
- RETRYABLE_ERROR_KINDS,
- Done,
- HostedToolRoute,
- ModelEndpoint,
- ModelRequest,
- ProviderError,
-)
-from core.agent_core.ai.registry import create_adapter
-from core.agent_core.cancel import CancelToken
-from core.agent_core.messages import (
- IMAGE_MIME_TYPES,
- AssistantMessage,
- HostedImage,
- HostedToolBlock,
- TextBlock,
- ThinkingBlock,
- UserMessage,
-)
-from core.agent_core.tools.hosted import hosted_tool_spec as canonical_tool_spec
-from core.agent_core.tools.read import detect_supported_image_mime_type
-from vibe.backend_model_catalog import HostedToolSpec
-
-from .adapter import InvokeHandle, RawCallOutcome, RawOutcomeKind
-from .classification import classify_outcome
-from .evidence_rules import LearnedEvidence
-from .stream_wire import ProtocolUsageReport
-
-ProbeOutcome = Literal["verified", "unsupported", "inconclusive", "transient"]
-
-# Every catalog tool: Vibey's adapters parse each one's results.
-PROBED_TOOLS: tuple[str, ...] = ("web_search", "x_search", "image_generation")
-
-# The web search asks for fresh articles: the replay probe asks about the other results, and a model given only the
-# first could infer the rest of a fixed topic's results (its site's other pages), but not a page published after it
-# was trained.
-_MESSAGES = {
- "web_search": "Search the web for a news article published today about technology and reply with its URL.",
- "x_search": "Search X for posts about 'Avibe local-first agent OS' and reply with the first post's URL.",
- "image_generation": "Generate a small, simple image: a blue circle on a white background.",
-}
-# The replay probe's question: one a model can answer only from the results the replayed payload holds, since the
-# answer it already gave shows just the first.
-_REPLAY_MESSAGE = (
- "Without using any tool again, list the URLs of the other results you found, beyond the one you already gave."
-)
-_SYSTEM = "You check that a tool works: use it, then answer in one line."
-# The replay's own instructions: the call's would ask for the very call the replay checks the model does not need.
-_REPLAY_SYSTEM = "You check that a tool's earlier results can be read back: answer from them in one line, without using any tool."
-# Room for a reasoning model to think, call the tool and answer in one line; a hop whose Vibey turns ask for less
-# gets that instead.
-PROBE_MAX_OUTPUT_TOKENS = 4096
-# What one call probe is estimated to use, for its cost hint before it runs: the
-# fixed message and the tool's results in context, a one-line answer, and one
-# search (an X search reads up to ten posts). The 2026-10-13 spike measured
-# such probes at about $0.01-0.11.
-ESTIMATED_USAGE = ProtocolUsageReport.of(input_tokens=8000, cached_input_tokens=0, output_tokens=500)
-ESTIMATED_COUNTS: dict[str, dict[str, int]] = {
- "web_search": {"web_search_calls": 1, "web_search_requests": 1},
- "x_search": {"x_search_calls": 1, "x_posts_fetched": 10, "x_users_fetched": 0},
- "image_generation": {},
-}
-# What the replay probe is estimated to use: the call probe's turn with its results, a question, and a one-line
-# answer, with no tool fee (the answer uses no tool).
-ESTIMATED_REPLAY_USAGE = ProtocolUsageReport.of(input_tokens=12000, cached_input_tokens=0, output_tokens=300)
-# The protocols whose adapters send a hosted call's native payload back in place (``transform.native_replay``).
-NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})
-# The adapter's requests never leave this process: the transport serves each
-# with a Model Hub call pinned to the probed Source.
-_IN_PROCESS_URL = "http://model-hub-probe.invalid"
-# The classified failures a later try may not meet: a dropped connection or a
-# timeout, an overload or 5xx, and a rate limit.
-_TRANSIENT_REASONS = frozenset({"network", "server_error", "rate_limited"})
-
-
-def probe_request(
- source: ModelHubSourceConfig, model_id: str, tool: str, spec: HostedToolSpec, *, max_tokens: int
-) -> ModelRequest:
- """The call probe for ``tool`` on this Source and model, as Vibey would send it natively.
-
- It matches a real turn's declaration, include and provider shaping, and Vibey's own adapter and transport send
- it; ``max_tokens`` is the smallest output any Vibey turn on this hop would ask for, at most
- ``PROBE_MAX_OUTPUT_TOKENS``.
- """
-
- route = HostedToolRoute(
- mode="native",
- executor=None,
- replay=False,
- declaration=spec.declaration,
- include=tuple(spec.include),
- )
- return ModelRequest(
- # As the Vibey launch builds a hop's endpoint: the Source's vendor is its provider, which shapes the
- # request (Anthropic's one-hour cache lifetime), and the model is the one the Source serves.
- endpoint=ModelEndpoint(
- protocol=source.protocol, # type: ignore[arg-type]
- base_url=_IN_PROCESS_URL,
- model_id=model_id,
- token="",
- provider=source.vendor,
- source_id=source.id,
- hosted_tools={tool: route},
- ),
- system=_SYSTEM,
- messages=(UserMessage(content=(TextBlock(text=_MESSAGES[tool]),)),),
- tools=(canonical_tool_spec(tool),),
- max_tokens=max_tokens,
- # Current Claude models refuse a forced choice, so Anthropic is asked in the message alone.
- tool_choice=None if source.protocol == "anthropic" else tool,
- )
-
-
-def replay_request(call: ModelRequest, tool: str, answered: AssistantMessage) -> ModelRequest:
- """The replay probe after a verified ``call`` probe: its turn sent back, with the native declaration still
- present and the hop allowed to take the tool's native payload, and a question only those results answer.
-
- The answer goes back without its reasoning, which may restate the results, readably or encrypted: a Source that
- dropped the payload could read a result there. A provider that wants a completed turn's reasoning back refuses
- the request, which no narrow rule learns from, so the replay reads as inconclusive, never as unsupported.
- """
-
- route = call.endpoint.hosted_tools[tool]
- answered = replace(answered, content=tuple(block for block in answered.content if not isinstance(block, ThinkingBlock)))
- return replace(
- call,
- endpoint=replace(
- call.endpoint, hosted_tools={tool: HostedToolRoute("native", None, True, route.declaration, route.include)}
- ),
- system=_REPLAY_SYSTEM,
- messages=(*call.messages, answered, UserMessage(content=(TextBlock(text=_REPLAY_MESSAGE),))),
- # A forced choice would ask for the very call the replay checks the model does not need.
- tool_choice=None,
- )
-
-
-def hidden_result_urls(message: AssistantMessage) -> frozenset[str]:
- """The result URLs a response's hosted calls returned that its visible answer does not show.
-
- Only these prove a replay: a model that names one read the replayed native
- payload, since nothing else it was sent holds it. A URL the answer wrote or
- cited is visible text, which any request carries.
- """
-
- returned = {source.url for block in message.content if isinstance(block, HostedToolBlock) for source in block.record.sources}
- # Read generously, a trailing slash aside: a result the answer shows but the probe takes for hidden is what could
- # verify a replay falsely.
- shown = {key.rstrip("/") for key in written_urls(message)}
- return frozenset(url for url in returned if url and not {key.rstrip("/") for key in _readings(url)} & shown)
-
-
-def written_urls(message: AssistantMessage) -> frozenset[str]:
- """Every URL a response's answer shows, as comparison keys: each reading of a URL its text writes
- (``_readings``) and each URL it cites, as given."""
-
- text = " ".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
- keys = {key for url in _URL.findall(text) for key in _readings(url)}
- cited = [
- citation.url
- for block in message.content
- if isinstance(block, TextBlock) and block.citations
- for citation in block.citations
- ]
- if message.hosted_summary is not None:
- cited.extend(source.url for source in message.hosted_summary.cited_sources)
- keys.update(_same_url(url) for url in cited if url)
- return frozenset(keys)
-
-
-def carries_native_payload(body: Any, message: AssistantMessage) -> bool:
- """Whether a request body sends every hosted call of ``message`` back verbatim, its provider items in place."""
-
- def canonical(value: Any) -> str:
- return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
-
- # Every object the body holds, once, then a lookup per item: one walk, whatever the payload's size.
- held: set[str] = set()
- pending = [body]
- while pending:
- node = pending.pop()
- if isinstance(node, dict):
- held.add(canonical(node))
- pending.extend(node.values())
- elif isinstance(node, list):
- pending.extend(node)
- items = [item for block in message.content if isinstance(block, HostedToolBlock) for item in block.native.payload]
- return bool(items) and all(canonical(item) in held for item in items)
-
-
-class ProbeImageCheck:
- """The image probe's media sink: it checks a generated image is one Vibey can keep, and keeps nothing.
-
- A probe asks whether the tool works, so its image is decoded and recognized
- exactly as a turn's would be, and then discarded.
- """
-
- async def save_image(self, encoded: str) -> HostedImage:
- return await asyncio.to_thread(self._check, encoded)
-
- @staticmethod
- def _check(encoded: str) -> HostedImage:
- try:
- data = base64.b64decode(encoded, validate=True)
- except (binascii.Error, ValueError):
- raise ValueError("the image is not valid base64") from None
- mime_type = detect_supported_image_mime_type(data)
- # The kinds a turn's sink keeps (``IMAGE_MIME_TYPES``, which ``MediaSnapshots`` stores); any other is refused there.
- if mime_type not in IMAGE_MIME_TYPES:
- raise ValueError("the image is not a PNG, JPEG, GIF or WebP")
- return HostedImage(path="probe:discarded", mime=mime_type, bytes=len(data))
-
-
-# How long the UI process waits for any Model Hub RPC (``vibe/model_hub_client.py`` reads it from here). A probe
-# answers inside it, with room for the RPC's own overhead.
-MODEL_HUB_RPC_TIMEOUT_SECONDS: Final = 300.0
-PROBE_BUDGET_SECONDS: Final = MODEL_HUB_RPC_TIMEOUT_SECONDS - 20.0
-# The replay probe runs only with at least this long left; otherwise it reports a transient failure, sending nothing.
-REPLAY_MIN_SECONDS: Final = 60.0
-
-# A probe sends at most this many requests: its own, and the one resend an adapter makes when an endpoint refuses
-# a field before answering (Anthropic's one-hour cache lifetime). Only an answered request runs the model.
-MAX_PROBE_REQUESTS = 2
-
-class CallResult(Protocol):
- """How one pinned call settled: the Source it ran on and its outcome (``ModelHubService._user_test_call``)."""
-
- source: ModelHubSourceConfig
- outcome: RawCallOutcome
-
-
-# Model Hub's one pinned call for a request body: it opens the call on the probed Source, hands it to the reader,
-# and settles and meters it once the reader returns.
-PinnedCall = Callable[[dict[str, Any], Callable[[InvokeHandle], Awaitable[None]]], Awaitable[CallResult]]
-
-
-@dataclass(frozen=True)
-class ProbeCall:
- """One request the adapter sent, and how Model Hub's pinned call for it ended."""
-
- body: dict[str, Any]
- source: ModelHubSourceConfig
- outcome: RawCallOutcome
-
-
-class _CallStream(httpx.AsyncByteStream):
- """The adapter's side of one pinned call: what the call's own task read from its stream, in order.
-
- Only that task ever iterates the call's stream, so the call can settle (and
- close it) whatever the adapter is doing, a deadline included.
- """
-
- def __init__(self, chunks: asyncio.Queue, released: asyncio.Event) -> None:
- self._chunks = chunks
- self._released = released
-
- async def __aiter__(self) -> AsyncIterator[bytes]:
- while (item := await self._chunks.get()) is not None:
- if isinstance(item, BaseException):
- raise item
- yield item
-
- async def aclose(self) -> None:
- self._released.set()
-
-
-async def _pump(handle: InvokeHandle, chunks: asyncio.Queue) -> None:
- """Read the call's stream into ``chunks`` and always end the queue: on a failure the adapter meets the same error
- where it would have read it."""
-
- try:
- if handle.stream is not None:
- async for chunk in handle.stream:
- chunks.put_nowait(chunk)
- except Exception as failed:
- chunks.put_nowait(failed)
- finally:
- chunks.put_nowait(None)
-
-
-def _failure_body(outcome: RawCallOutcome) -> dict[str, Any]:
- """What an adapter reads for a call that failed before any output: the upstream's status and its own words."""
-
- message = outcome.upstream_detail or outcome.redacted_message or "the upstream call failed"
- return {"type": "error", "error": {"type": outcome.error_type or outcome.error_code or "api_error", "message": message}}
-
-
-class PinnedCallTransport(httpx.AsyncBaseTransport):
- """Serves every request the adapter sends with its own pinned call of the probed Source.
-
- The adapter runs exactly as it does for a real turn, resend included, and
- each of its requests is one Model Hub call on that Source alone, with no
- route and no failover. ``calls`` records them in order.
- """
-
- def __init__(self, call: PinnedCall) -> None:
- self._call = call
- # In request order: each request reserves its place before its call settles.
- self._slots: list[Optional[ProbeCall]] = []
- self._tasks: list[asyncio.Task[None]] = []
- self._releases: list[asyncio.Event] = []
-
- async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
- if len(self._tasks) >= MAX_PROBE_REQUESTS:
- raise RuntimeError("a probe sends at most two requests")
- body = json.loads(await request.aread())
- slot = len(self._slots)
- self._slots.append(None)
- opened: asyncio.Future[InvokeHandle] = asyncio.get_running_loop().create_future()
- released = asyncio.Event()
- self._releases.append(released)
- chunks: asyncio.Queue = asyncio.Queue()
-
- async def read(handle: InvokeHandle) -> None:
- opened.set_result(handle)
- # The call's own reader runs until the stream ends or the adapter closes its side, as production closes a
- # response it has finished with; it is always over before the call settles and closes the stream.
- pump = asyncio.create_task(_pump(handle, chunks))
- closed = asyncio.create_task(released.wait())
- try:
- await asyncio.wait({pump, closed}, return_when=asyncio.FIRST_COMPLETED)
- finally:
- pump.cancel()
- closed.cancel()
- await asyncio.gather(pump, closed, return_exceptions=True)
- await released.wait()
-
- async def run() -> None:
- settled = await self._call(body, read)
- self._slots[slot] = ProbeCall(body, settled.source, settled.outcome)
-
- task = asyncio.create_task(run())
- self._tasks.append(task)
- await asyncio.wait({opened, task}, return_when=asyncio.FIRST_COMPLETED)
- if not opened.done() and task.exception() is not None:
- # Refused before any call opened (the Source changed, the engine is down): ``settle`` raises it.
- raise RuntimeError("the probe's call did not open")
- if opened.done() and opened.result().stream is not None:
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_CallStream(chunks, released))
- # The call failed before any output, or timed out before it opened: answer as the upstream did, so the
- # adapter decides what to do as it would for a real turn.
- released.set()
- await task
- outcome = self._slots[slot].outcome # type: ignore[union-attr]
- status = outcome.http_status or (504 if outcome.kind is RawOutcomeKind.TIMEOUT else 502)
- return httpx.Response(status, json=_failure_body(outcome))
-
- @property
- def calls(self) -> list[ProbeCall]:
- """Every request the adapter sent whose call settled, in the order the adapter sent them."""
-
- return [call for call in self._slots if call is not None]
-
- async def settle(self) -> None:
- """Let every call finish settling; re-raise the first one Model Hub refused to open."""
-
- for released in self._releases:
- released.set()
- results = await asyncio.gather(*self._tasks, return_exceptions=True)
- for result in results:
- if isinstance(result, BaseException):
- raise result
-
-
-async def run_probe(
- request: ModelRequest, call: PinnedCall, *, media_sink: Optional[ProbeImageCheck] = None
-) -> tuple[Done | ProviderError | None, list[ProbeCall]]:
- """Run Vibey's adapter for ``request`` over pinned calls; its terminal event and the calls it made."""
-
- transport = PinnedCallTransport(call)
- terminal: Done | ProviderError | None = None
- try:
- async with httpx.AsyncClient(transport=transport) as client:
- # Only the image probe has an image to keep, and only the Responses adapter produces one.
- adapter = create_adapter(
- request.endpoint.protocol,
- client=client,
- gateway=False,
- **({"media_sink": media_sink} if media_sink is not None else {}),
- )
- async for event in adapter.stream(request, CancelToken()):
- if isinstance(event, (Done, ProviderError)):
- terminal = event
- finally:
- await transport.settle()
- return terminal, transport.calls
-
-
-def call_outcome(
- tool: str,
- terminal: Done | ProviderError | None,
- outcome: RawCallOutcome,
- learned: Optional[LearnedEvidence],
-) -> ProbeOutcome:
- """What one call probe shows about ``tool`` on its Source and model.
-
- * ``unsupported``: only a 400 that names the tool's declared type, through the same narrow rule real requests
- learn from;
- * ``verified``: a completed response that carries the tool's own completed result;
- * ``inconclusive``: a completed response without one (the model may simply not have used the tool, which looks
- like a silent drop), or a request that failed for another reason;
- * ``transient``: an overload, a 5xx, a rate limit, a dropped connection or a timeout.
-
- Only the first two are evidence. A call that failed before any output has no
- ``terminal``; Model Hub's own reading of its ``outcome`` says which failure it was.
- """
-
- if learned is not None and (learned.feature.kind, learned.feature.name, learned.feature.aspect) == (
- "hosted_tool", tool, "call"
- ):
- return "unsupported"
- if isinstance(terminal, Done):
- used = any(
- isinstance(block, HostedToolBlock)
- and block.tool == tool
- and block.record.status == "completed"
- # A generated image counts only once Vibey could keep it.
- and (block.record.images is None or bool(block.record.images))
- for block in terminal.message.content
- )
- return "verified" if used else "inconclusive"
- return _failure(terminal, outcome)
-
-
-def replay_outcome(
- tool: str,
- terminal: Done | ProviderError | None,
- outcome: RawCallOutcome,
- learned: Optional[LearnedEvidence],
- *,
- asked: frozenset[str],
- carried: bool,
-) -> ProbeOutcome:
- """What one replay probe shows about sending ``tool``'s native payload back to its Source (§12 item 23).
-
- * ``unsupported``: a 400 naming the replayed content, through the narrow rule real requests learn from, or an
- answer that calls the tool again instead of using the results it holds;
- * ``verified``: an answer that names a URL only those results hold (``asked``, ``hidden_result_urls``) without
- calling the tool;
- * ``inconclusive``: an answer that names none, or a refusal, and any request that did not carry the native
- payload verbatim (``carried``), since it tested nothing;
- * ``transient``: as for the call probe.
- """
-
- if not carried:
- # A request that did not send the payload verbatim tested nothing, whatever the provider said about it.
- return "inconclusive"
- if learned is not None and (learned.feature.kind, learned.feature.name, learned.feature.aspect) == (
- "hosted_tool", tool, "replay"
- ):
- return "unsupported"
- if isinstance(terminal, Done):
- message = terminal.message
- if any(isinstance(block, HostedToolBlock) and block.tool == tool for block in message.content):
- return "unsupported"
- if message.stop_reason in ("refusal", "safety"):
- # A refused or blocked answer proves nothing, whatever it quotes.
- return "inconclusive"
- named = written_urls(message) & {_same_url(url) for url in asked}
- return "verified" if named else "inconclusive"
- return _failure(terminal, outcome)
-
-
-# A URL as an answer writes it: up to the whitespace, quote or bracket that ends it. Parentheses stay, since a URL
-# may hold them; one that closes the prose around it is trailing text.
-_URL = re.compile(r"https?://[^\s<>\[\]{}\"'`]+", re.IGNORECASE)
-# What prose and Markdown can leave right after a URL, and a URL can also end in.
-_TRAILING = ".,;:!?)*_"
-
-
-def _readings(written: str) -> frozenset[str]:
- """The comparison keys a URL written in prose can stand for: as written, and without each run of the trailing
- text a sentence may leave on it. A provider's URL is exact; only where prose ends a URL is ambiguous."""
-
- readings = {_same_url(written)}
- while written and written[-1] in _TRAILING:
- written = written[:-1]
- readings.add(_same_url(written))
- return frozenset(readings)
-
-
-def _same_url(url: str) -> str:
- """A URL as a comparison key: exactly as given but for what RFC 3986 makes equivalent, the case of its scheme and
- host and an empty path, which is ``/``. Anything else, such as a trailing slash or the case of its user
- information, names another URL."""
-
- scheme, separator, rest = url.partition("://")
- if not separator:
- return url
- authority = _AUTHORITY.match(rest)[0]
- path = rest[len(authority):]
- userinfo, at, host = authority.rpartition("@")
- return f"{scheme.lower()}://{userinfo}{at}{host.lower()}{path if path.startswith('/') else '/' + path}"
-
-
-_AUTHORITY = re.compile(r"[^/?#]*")
-
-
-def _failure(terminal: ProviderError | None, outcome: RawCallOutcome) -> ProbeOutcome:
- """A probe request that failed: ``transient`` when a later try may not meet the same failure."""
-
- if terminal is not None:
- # By what failed, not by ``retryable``: an adapter never retries a response that already streamed output,
- # but a dropped connection or an overload is just as transient for a probe the user can run again.
- return "transient" if terminal.kind in RETRYABLE_ERROR_KINDS else "inconclusive"
- return "transient" if classify_outcome(outcome).reason in _TRANSIENT_REASONS else "inconclusive"
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index 8ad992a18..42fee6acb 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -1,43 +1,67 @@
-"""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.
+"""Hosted-tool facts and the Tools read (``vibey-hosted-tools.md`` §3).
+
+Nothing here probes or guesses. A search tool is ``assumed`` on a hop when the
+overlay offers it there (``runs_on``) and no current refusal exists; Vibey then
+decides what each request declares. Search tools that are not native run
+through the executor chain, the Sources whose vendor offers the tool, each on
+its vendor's lightweight model. ``image_generate`` names its model, chosen from
+the image models the user's Sources make available.
+
+Every function is pure over a config snapshot and a ``HostedEvidence`` reader,
+so it is safe off the loop and decides the same way wherever it is asked.
"""
from __future__ import annotations
import json
import os
-from dataclasses import dataclass
-from datetime import datetime, timezone
+from dataclasses import dataclass, replace
+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, UNKNOWN_ENGINE_STAMP, 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
-
+from typing import Any, Callable, Literal, Mapping, Optional
+
+from config.v2_config import (
+ MODEL_HUB_HOSTED_TOOLS,
+ MODEL_HUB_SEARCH_TOOLS,
+ ModelHubConfig,
+ ModelHubHostedToolConfig,
+ ModelHubImageModelChoice,
+ ModelHubSourceConfig,
+ hosted_tool_setting,
+ is_model_hub_model_id,
+ is_model_hub_source_id,
+ model_hub_executor_order,
+)
+from vibe.backend_model_catalog import (
+ HostedToolSpec,
+ ImageModelSpec,
+ provider_executor_model,
+ provider_image_models,
+)
+
+from .capability_evidence import (
+ HOSTED_TOOL_ASPECTS,
+ CapabilityEvidenceStore,
+ EvidenceFeature,
+ EvidenceRecord,
+ identity_digest,
+ utc_text,
+ wire_stamp,
+)
SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]
+# The engine release when the engine manifest cannot be read. It names no release, so a refusal learned under it
+# never matches a real one.
+UNKNOWN_ENGINE_RELEASE = "unknown-engine"
+NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})
+
+Assumption = Literal["assumed", "unsupported"]
def credential_eligible(source: ModelHubSourceConfig) -> bool:
- """Whether a Source may run hosted tools at all: natively, as executor, or for a probe.
+ """Whether a Source may run hosted tools at all: natively, as executor, or for images.
Anthropic restricts OAuth credentials to Claude Code and its own apps
(``model-hub-tos-review.md``), so a Claude subscription never is.
@@ -52,99 +76,224 @@ def untranslated(source: ModelHubSourceConfig) -> bool:
return source.protocol != "google"
+def _serves(source: ModelHubSourceConfig, model_id: str) -> bool:
+ """Whether a hub Source serves this model by its admission rule.
+
+ An API-key Source serves any model it does not list as a retired tombstone; a subscription only its listed
+ models.
+ """
+
+ listed = next((model for model in source.models if model.id == model_id), None)
+ return not listed.retired if listed is not None else source.kind == "api_key"
+
+
@lru_cache(maxsize=1)
-def _manifest_engine_stamp(path: Optional[str]) -> str:
+def _manifest_engine_release(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"))
- for key in ("hosted_wire", "asset_release_tag", "release_tag", "version"):
- stamp = payload.get(key)
- if isinstance(stamp, str) and stamp:
- return stamp
+ for key in ("asset_release_tag", "release_tag", "version"):
+ release = payload.get(key)
+ if isinstance(release, str) and release:
+ return release
raise ValueError("the engine manifest names no release")
def engine_stamp() -> str:
- """The engine wire evidence is stamped with: the shipped manifest's ``hosted_wire``, else its asset release.
-
- ``hosted_wire`` names the oldest engine release whose hosted passthrough is
- byte-identical to this one; the engine release gate carries it forward
- across such upgrades and sets it to the new asset release otherwise, so a
- byte-identical upgrade keeps evidence current and anything else makes it
- stale. A manifest without it is stamped with its asset release (a patched
- rebuild of the same upstream version gets a new one), which is the value
- the gate first carries forward. Read once, when Model Hub's service is
- built; a manifest that cannot be read is the fixed unknown engine, whose
- evidence never matches a real release and never raises on a request.
+ """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. Read once, when Model Hub's
+ service is built; a manifest that cannot be read is the fixed unknown
+ engine, never raised on a request.
"""
try:
- return _manifest_engine_stamp(os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH") or None)
+ return _manifest_engine_release(os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH") or None)
except (OSError, ValueError, TypeError, AttributeError):
- return UNKNOWN_ENGINE_STAMP
+ return UNKNOWN_ENGINE_RELEASE
+
+
+def runs_on(source: ModelHubSourceConfig, model_id: str, tool: str, *, spec_for: SpecLookup) -> Optional[HostedToolSpec]:
+ """The declaration a search ``tool`` runs with natively on this (Source, model), or None where it cannot.
+
+ One rule for every place that asks: a hop's facts, an executor candidate,
+ and admission. The Source is a hub Source with an eligible credential and an
+ untranslated path, it serves the model, and the overlay declares the tool
+ for it.
+ """
+
+ if source.supply_channel != "hub" or not credential_eligible(source) or not untranslated(source):
+ return None
+ if not _serves(source, model_id):
+ return None
+ return spec_for(source.vendor, source.protocol, model_id, tool)
@dataclass(frozen=True)
-class _Context:
- evidence: CapabilityEvidenceStore
- spec_for: SpecLookup
+class HostedEvidence:
+ """A reader over the evidence store that applies the current wire stamp. Take one per resolution."""
+
+ store: CapabilityEvidenceStore
engine: str
- shape: int
- now: datetime
+ avibe: str
+ def wire_for(self, source: ModelHubSourceConfig, model_id: str) -> str:
+ return wire_stamp(engine=self.engine, avibe=self.avibe, source=source, model_id=model_id)
-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 refusal(self, source: ModelHubSourceConfig, model_id: str, feature: EvidenceFeature) -> Optional[EvidenceRecord]:
+ return self.store.refusal(source, model_id, feature, wire=self.wire_for(source, model_id))
+ def unsupported(self, source: ModelHubSourceConfig, model_id: str, feature: EvidenceFeature) -> bool:
+ return self.refusal(source, model_id, feature) is not None
-def runs_on(source: ModelHubSourceConfig, model_id: str, tool: str, *, spec_for: SpecLookup) -> Optional[HostedToolSpec]:
- """The declaration ``tool`` runs with on this (Source, model), or None where it may not run at all.
-
- One rule for every place that asks: the Tools-tab candidates, a chosen
- executor, the executor a turn binds, a hop's native mode and a probe's
- target. The Source is a hub Source with an eligible credential and an
- untranslated path, it serves the model as its admission rule says (an
- API-key Source serves any model it does not list as a retired tombstone; a
- subscription only its listed models), and the overlay declares the tool for
- it.
+
+@dataclass(frozen=True)
+class HostedToolFacts:
+ """What priors and evidence say about one search tool on one hop (§3.4).
+
+ ``declaration`` and ``include`` are set exactly when ``native`` is ``assumed``.
"""
- if source.supply_channel != "hub" or not credential_eligible(source) or not untranslated(source):
- return None
- listed = next((model for model in source.models if model.id == model_id), None)
- if (listed.retired if listed is not None else source.kind != "api_key"):
- return None
- return spec_for(source.vendor, source.protocol, model_id, tool)
+ native: Assumption
+ replay: Assumption
+ declaration: Optional[Mapping[str, Any]] = None
+ include: tuple[str, ...] = ()
-def _runnable_spec(
- context: _Context, source: ModelHubSourceConfig, model_id: str, tool: str
-) -> Optional[HostedToolSpec]:
- spec = runs_on(source, model_id, tool, spec_for=context.spec_for)
- if spec is None or not _verified(context, source, model_id, EvidenceFeature.hosted(tool, "call")):
- return None
- return spec
+def hosted_tool_facts(
+ source: ModelHubSourceConfig, model_id: str, tool: str, *, evidence: HostedEvidence, spec_for: SpecLookup
+) -> HostedToolFacts:
+ spec = runs_on(source, model_id, tool, spec_for=spec_for)
+ if spec is None or evidence.unsupported(source, model_id, EvidenceFeature.hosted(tool, "call")):
+ return HostedToolFacts(native="unsupported", replay="unsupported")
+ replay: Assumption = (
+ "assumed"
+ if "replay" in HOSTED_TOOL_ASPECTS[tool]
+ and source.protocol in NATIVE_REPLAY_PROTOCOLS
+ and not evidence.unsupported(source, model_id, EvidenceFeature.hosted(tool, "replay"))
+ else "unsupported"
+ )
+ return HostedToolFacts(native="assumed", replay=replay, declaration=spec.declaration, include=tuple(spec.include))
-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 enabled_tools(config: ModelHubConfig) -> tuple[str, ...]:
+ """The tools a turn would declare now, in catalog order: every tool the user has not turned off."""
+
+ return tuple(tool for tool in MODEL_HUB_HOSTED_TOOLS if hosted_tool_setting(config, tool).enabled)
+
+
+def _vibey_order(config: ModelHubConfig) -> list[ModelHubSourceConfig]:
+ """Every Source, 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]
+ return ordered + [source for source in config.sources if source not in ordered]
+
+
+@dataclass(frozen=True)
+class ExecutorCandidate:
+ """A Source that can run a proxied search: its vendor's lightweight model and the declaration it runs with."""
+
+ source: ModelHubSourceConfig
+ model_id: str
+ declaration: Mapping[str, Any]
+ include: tuple[str, ...]
+ price: Any = None
+
+
+def executor_candidates(
+ config: ModelHubConfig, tool: str, *, evidence: HostedEvidence, spec_for: SpecLookup
+) -> tuple[ExecutorCandidate, ...]:
+ """The executor chain for a search tool, in effective order (§6).
+
+ Sources whose vendor offers the tool natively on its ``executor_model``,
+ with no current refusal for that pair: the user's ``executor_order`` first,
+ then Vibey's Source order.
+ """
+
+ if tool not in MODEL_HUB_SEARCH_TOOLS:
+ return ()
+ candidates: dict[str, ExecutorCandidate] = {}
+ for source in _vibey_order(config):
+ model_id = provider_executor_model(source.vendor)
+ if model_id is None:
+ continue
+ spec = runs_on(source, model_id, tool, spec_for=spec_for)
+ if spec is None or evidence.unsupported(source, model_id, EvidenceFeature.hosted(tool, "call")):
+ continue
+ candidates[source.id] = ExecutorCandidate(source, model_id, spec.declaration, tuple(spec.include), spec.price)
+ order = hosted_tool_setting(config, tool).executor_order or ()
+ first = [candidates[source_id] for source_id in order if source_id in candidates]
+ return tuple(first + [candidate for source_id, candidate in candidates.items() if source_id not in order])
+
+
+@dataclass(frozen=True)
+class ImageChoice:
+ """One image model ``image_generate`` may name, on the Source that serves it."""
+
+ source_id: str
+ model_id: str
+ description: str
+ endpoint: Literal["images", "chat_image"]
+ params: tuple[str, ...]
+ size_forms: tuple[str, ...]
+ spec: ImageModelSpec
+
+
+@dataclass(frozen=True)
+class ImageChoices:
+ """The image models available now: the default first, the rest sorted by id. Empty when none is."""
+
+ models: tuple[ImageChoice, ...]
+ default: Optional[ImageChoice]
+ saved_default: Optional[ModelHubImageModelChoice] = None
+ saved_default_available: bool = False
+
+
+def _serves_image(source: ModelHubSourceConfig, model_id: str) -> bool:
+ return source.supply_channel == "hub" and credential_eligible(source) and _serves(source, model_id)
+
+
+def image_choices(config: ModelHubConfig, *, evidence: HostedEvidence) -> ImageChoices:
+ """The ``image_generate`` enum (§7.2): each available image model once, the default first.
+
+ A pair with a current refusal is not available. An id two Sources offer is
+ served by the first in Vibey's order, unless the saved default names the
+ other. The default is the saved one if available, else the same model id on
+ another Source, else the first available model in catalog order.
+ """
+
+ saved = hosted_tool_setting(config, "image_generate").default_image
+ available: list[ImageChoice] = []
+ for source in _vibey_order(config):
+ for spec in provider_image_models(source.vendor):
+ if not _serves_image(source, spec.id) or evidence.unsupported(
+ source, spec.id, EvidenceFeature.hosted("image_generate", "call")
+ ):
+ continue
+ available.append(
+ ImageChoice(source.id, spec.id, spec.description, spec.endpoint, spec.params, spec.size_forms, spec)
+ )
+ if not available:
+ return ImageChoices((), None, saved, False)
+ saved_choice = next(
+ (
+ choice for choice in available
+ if saved is not None and (choice.source_id, choice.model_id) == (saved.source_id, saved.model_id)
+ ),
+ None,
+ )
+ by_id: dict[str, ImageChoice] = {}
+ for choice in available:
+ by_id.setdefault(choice.model_id, choice)
+ if saved_choice is not None:
+ by_id[saved_choice.model_id] = saved_choice
+ default = saved_choice or (by_id.get(saved.model_id) if saved is not None else None) or by_id[available[0].model_id]
+ rest = sorted((choice for model_id, choice in by_id.items() if model_id != default.model_id), key=lambda c: c.model_id)
+ return ImageChoices((default, *rest), default, saved, saved_choice is not None)
def resolve_hosted_tools(
@@ -152,72 +301,46 @@ def resolve_hosted_tools(
*,
source: ModelHubSourceConfig,
model_id: str,
- evidence: CapabilityEvidenceStore,
+ evidence: HostedEvidence,
spec_for: SpecLookup,
- engine: str,
- now: datetime,
- shape: int = HOSTED_PROBE_SHAPE,
frozen: Mapping[str, Optional[tuple[str, str]]] | None = None,
) -> dict[str, dict[str, Any]]:
- """``HopResolution.hosted_tools`` for a Vibey hop served by ``source``/``model_id``.
+ """``HopResolution.hosted_tools`` for a Vibey hop, in the C-6 shape the consumer reads today.
- ``frozen`` is the turn's binding from its first resolution: which tools are
- on and the executor bound to each. A later resolution in the same turn
- keeps it, since settings apply from the next turn, and recomputes only what
- belongs to the hop (mode, declaration, include, replay).
+ The facts are v2's: native when assumed, replay when assumed. The executor
+ is the first candidate of the chain. ``frozen`` is the turn's tool set and
+ executors from its first resolution. The image tool is not part of this
+ shape; it arrives with the HopResolution change.
"""
- 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)
+ for tool in MODEL_HUB_SEARCH_TOOLS:
if frozen is not None:
if tool not in frozen:
continue
- elif toggle is None or not toggle.enabled:
+ elif not hosted_tool_setting(config, tool).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)
+ facts = hosted_tool_facts(source, model_id, tool, evidence=evidence, spec_for=spec_for)
+ entry: dict[str, Any] = {"mode": "native" if facts.native == "assumed" else "proxy"}
+ if facts.native == "assumed":
+ entry["declaration"] = dict(facts.declaration or {})
+ entry["include"] = list(facts.include)
if frozen is not None:
bound = frozen[tool]
entry["executor"] = {"source_id": bound[0], "model_id": bound[1]} if bound is not None else None
else:
- chosen = (
- (toggle.executor.source_id, toggle.executor.model_id)
- if toggle is not None and 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"))
- )
+ chain = executor_candidates(config, tool, evidence=evidence, spec_for=spec_for)
+ entry["executor"] = {"source_id": chain[0].source.id, "model_id": chain[0].model_id} if chain else None
+ entry["replay"] = facts.replay == "assumed"
resolved[tool] = entry
return resolved
-def _utc_text(moment: Optional[datetime]) -> Optional[str]:
- return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") if moment is not None else None
-
-
-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,
- "changes_at": _utc_text(view.changes_at),
- }
+# --- The Tools read (§3.3) ---------------------------------------------------------------------------------------
def _price_payload(price: Any) -> dict[str, Any] | None:
- """The overlay's list price for the cost hint; None when no list price is known, never zero."""
+ """An overlay list price; None when no list price is known, never zero."""
if price is None:
return None
@@ -230,101 +353,117 @@ def _price_payload(price: Any) -> dict[str, Any] | None:
}
-def _candidate_targets(
- config: ModelHubConfig, tool: str, *, spec_for: SpecLookup
-) -> list[tuple[ModelHubSourceConfig, str, HostedToolSpec]]:
- """The (Source, model)s the Tools tab lists for ``tool``, with its declaration on each, Vibey's Source order first.
+def is_relay(source: ModelHubSourceConfig) -> bool:
+ """Whether an API-key Source talks to an endpoint other than its vendor's own, whose bill Avibe cannot know."""
- Every model a Source lists that ``runs_on`` admits. A passthrough model an
- API-key Source may also serve is not listed: there is nothing to show for it.
- """
+ from vibe.model_hub_runtime.api_key_vendors import is_official_api_key_endpoint
- 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, model.id, spec)
- for source in ordered
- for model in source.models
- if (spec := runs_on(source, model.id, tool, spec_for=spec_for)) is not None
+ if source.kind != "api_key" or not source.base_url:
+ return False
+ return not is_official_api_key_endpoint(source.vendor, source.base_url)
+
+
+def _status(
+ config: ModelHubConfig, tool: str, evidence: HostedEvidence
+) -> dict[str, Any]:
+ """The status lines' data: the latest success, the current refusals, and the per-pair successes."""
+
+ live = {source.id: source for source in config.sources}
+ refused: list[dict[str, Any]] = []
+ successes: list[tuple[datetime, str, str, Optional[str]]] = []
+ for record in evidence.store.records():
+ source = live.get(record.source_id)
+ if (
+ record.feature.kind != "hosted_tool"
+ or record.feature.name != tool
+ or source is None
+ or record.source_identity != identity_digest(source)
+ ):
+ continue
+ if record.status == "unsupported":
+ if record.wire != evidence.wire_for(source, record.model_id):
+ continue
+ refused.append(
+ {
+ "source_id": record.source_id,
+ "model_id": record.model_id,
+ "aspect": record.feature.aspect,
+ "at": utc_text(record.observed_at),
+ "reason": record.detail,
+ }
+ )
+ else:
+ successes.append((record.observed_at, record.source_id, record.model_id, record.mode))
+ # Memory holds every success at once, so the newest identity-valid one is the latest.
+ newest = max(successes, key=lambda item: item[0], default=None)
+ verified = [
+ {"source_id": source_id, "model_id": model_id, "mode": mode, "at": utc_text(at)}
+ for at, source_id, model_id, mode in successes
]
+ return {
+ "latest_ok": (
+ {"source_id": newest[1], "model_id": newest[2], "mode": newest[3], "at": utc_text(newest[0])}
+ if newest is not None
+ else None
+ ),
+ "refused": sorted(refused, key=lambda item: (item["at"], item["source_id"], item["model_id"])),
+ "verified": sorted(verified, key=lambda item: (item["source_id"], item["model_id"])),
+ }
def hosted_tools_status(
config: ModelHubConfig,
*,
- evidence: CapabilityEvidenceStore,
+ evidence: HostedEvidence,
spec_for: SpecLookup,
- engine: str,
- now: datetime,
- probe_estimate: Callable[[ModelHubSourceConfig, str, str], Optional[dict[str, Any]]],
- shape: int = HOSTED_PROBE_SHAPE,
+ image_price: Callable[[ModelHubSourceConfig, ImageModelSpec], Optional[dict[str, Any]]],
) -> 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, with what probing it
- would cost (``probe_estimate``, None when unknown). ``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).
- """
+ """What Models → Tools reads (``hosted-tools-status.schema.json``): settings, saved and effective, and status."""
- tools = []
- # Every (Source, model, tool) the Tools tab lists, so a re-verify it counts is one it can offer.
- listed: set[tuple[str, str, str]] = set()
+ sources = {source.id: source for source in config.sources}
+ tools: list[dict[str, Any]] = []
for tool in MODEL_HUB_HOSTED_TOOLS:
- toggle = config.hosted_tools.get(tool)
- candidates = []
- for source, model_id, spec in _candidate_targets(config, tool, spec_for=spec_for):
- listed.add((source.id, model_id, tool))
- 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(
+ setting = hosted_tool_setting(config, tool)
+ entry: dict[str, Any] = {"name": tool, "enabled": setting.enabled, "status": _status(config, tool, evidence)}
+ if tool in MODEL_HUB_SEARCH_TOOLS:
+ chain = executor_candidates(config, tool, evidence=evidence, spec_for=spec_for)
+ entry["executor_order"] = list(setting.executor_order) if setting.executor_order is not None else None
+ entry["effective_order"] = [candidate.source.id for candidate in chain]
+ entry["executor_candidates"] = [
{
- "source_id": source.id,
- "model_id": model_id,
- "call": _evidence_payload(views["call"]),
- "replay": _evidence_payload(views["replay"]) if "replay" in views else None,
- "billing": source.billing,
- "price": _price_payload(spec.price),
- "probe_estimate": probe_estimate(source, model_id, tool),
+ "source_id": candidate.source.id,
+ "model_id": candidate.model_id,
+ "billing": candidate.source.billing,
+ "relay": is_relay(candidate.source),
+ "price": _price_payload(candidate.price),
}
+ for candidate in chain
+ ]
+ else:
+ choices = image_choices(config, evidence=evidence)
+ saved = choices.saved_default
+ entry["default_model"] = (
+ {**saved.to_payload(), "available": choices.saved_default_available} if saved is not None else None
)
- chosen = (toggle.executor.source_id, toggle.executor.model_id) if toggle and toggle.executor else None
- tools.append(
- {
- "name": tool,
- "enabled": bool(toggle and toggle.enabled),
- "executor": toggle.executor.to_payload() if toggle and toggle.executor else None,
- # What a turn would bind now, by the same rule hop resolution uses.
- "bound": _executor(_Context(evidence, spec_for, engine, shape, now), config, tool, chosen),
- "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
- or (record.source_id, record.model_id, record.feature.name) not in listed
- ):
- 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}
+ entry["effective_default"] = (
+ {"source_id": choices.default.source_id, "model_id": choices.default.model_id}
+ if choices.default is not None
+ else None
+ )
+ entry["models"] = [
+ {
+ "source_id": choice.source_id,
+ "model_id": choice.model_id,
+ "description": choice.description,
+ "price": image_price(sources[choice.source_id], choice.spec),
+ }
+ for choice in choices.models
+ ]
+ entry["image_offered_by"] = sorted(
+ {source.vendor for source in config.sources if provider_image_models(source.vendor)}
+ )
+ tools.append(entry)
+ return {"tools": tools}
class HostedToolSettingRefused(ValueError):
@@ -336,36 +475,68 @@ class HostedToolSettingRefused(ValueError):
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.
+def apply_hosted_tool_put(config: ModelHubConfig, tool: str, payload: object) -> ModelHubHostedToolConfig:
+ """One ``PUT /api/models/hosted-tools/<tool>`` body applied to the saved setting, field by field.
- The executor must be a ``hosted_tool_target``. Whether it is verified is
- evidence, decided at every resolution, never here.
+ An absent field is unchanged; ``null`` resets ``executor_order`` to automatic
+ or ``default_model`` to the default. Values are saved as given, never
+ resolved: an order naming a Source that is gone, or a default that is not
+ available now, stays saved and reads as such.
"""
if tool not in MODEL_HUB_HOSTED_TOOLS:
+ raise HostedToolSettingRefused("hosted_tool_not_found", 404)
+ allowed = {"enabled"} | ({"executor_order"} if tool in MODEL_HUB_SEARCH_TOOLS else {"default_model"})
+ if not isinstance(payload, dict) or not payload or set(payload) - allowed:
raise HostedToolSettingRefused("invalid_parameter", 400)
+ changes: dict[str, Any] = {}
try:
- setting = ModelHubHostedToolConfig.from_payload(payload, tool=tool)
+ if "enabled" in payload:
+ # Only the saved choices reset with null; a switch is a boolean.
+ if not isinstance(payload["enabled"], bool):
+ raise ValueError("enabled must be a boolean")
+ changes["enabled"] = payload["enabled"]
+ if "executor_order" in payload:
+ order = payload["executor_order"]
+ changes["executor_order"] = None if order is None else model_hub_executor_order(order, tool=tool)
+ if "default_model" in payload:
+ default = payload["default_model"]
+ changes["default_image"] = None if default is None else ModelHubImageModelChoice.from_payload(default, tool=tool)
except ValueError:
raise HostedToolSettingRefused("invalid_parameter", 400) from None
- executor = setting.executor
- if executor is not None:
- hosted_tool_target(config, tool, executor.source_id, executor.model_id, spec_for=spec_for)
- return setting
+ return replace(hosted_tool_setting(config, tool), **changes)
-def hosted_tool_target(
- config: ModelHubConfig, tool: str, source_id: str, model_id: str, *, spec_for: SpecLookup
-) -> tuple[ModelHubSourceConfig, HostedToolSpec]:
- """The Source a tool may run on with this model, as executor or for a probe, and its declaration there (``runs_on``)."""
+def clear_request(tool: str, payload: object) -> Callable[[EvidenceRecord], bool]:
+ """One ``POST /api/models/hosted-tools/<tool>/clear`` body read as the refusals it clears.
- source = next((item for item in config.sources if item.id == source_id), None)
- if source is None:
- raise HostedToolSettingRefused("source_not_found", 404)
- spec = runs_on(source, model_id, tool, spec_for=spec_for)
- if spec is None:
+ Each field is optional and, when present, a Source id or a canonical model id; ``model_id`` needs
+ ``source_id``. Nothing is nullable: a malformed body is refused, never widened into a broader clear.
+ """
+
+ if tool not in MODEL_HUB_HOSTED_TOOLS:
+ raise HostedToolSettingRefused("hosted_tool_not_found", 404)
+ if (
+ not isinstance(payload, dict)
+ or set(payload) - {"source_id", "model_id"}
+ or ("source_id" in payload and not is_model_hub_source_id(payload["source_id"]))
+ or ("model_id" in payload and ("source_id" not in payload or not is_model_hub_model_id(payload["model_id"])))
+ ):
raise HostedToolSettingRefused("invalid_parameter", 400)
- return source, spec
+ return clear_matcher(tool, payload.get("source_id"), payload.get("model_id"))
+
+
+def clear_matcher(
+ tool: str, source_id: Optional[str] = None, model_id: Optional[str] = None
+) -> Callable[[EvidenceRecord], bool]:
+ """Which refusals one Tools clear removes: the tool's, on one Source (one model) or on every Source."""
+
+ def matches(record: EvidenceRecord) -> bool:
+ return (
+ record.feature.kind == "hosted_tool"
+ and record.feature.name == tool
+ and (source_id is None or record.source_id == source_id)
+ and (model_id is None or record.model_id == model_id)
+ )
+
+ return matches
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 5fec0c736..cd9f1fc3d 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -2712,7 +2712,7 @@ class TurnCorrelationRegistry:
self.store.put(
{
- "contract_version": 14,
+ "contract_version": 15,
"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.py
index bf0d7ae46..996d4efdb 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -219,8 +219,10 @@ async def dispatch_model_hub_rpc(
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 == "probe_hosted_tool":
- return await service.probe_hosted_tool(payload.get("tool"), payload.get("target"))
+ if operation == "clear_hosted_refusals":
+ return await service.clear_hosted_refusals(payload.get("tool"), payload.get("target"))
+ if operation == "clear_source_evidence":
+ return await service.clear_source_evidence(payload.get("source_id"), payload.get("target"))
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.py
index 0b2af437f..6b8813736 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -26,6 +26,7 @@ from config.v2_config import (
ModelHubAgentSupplyConfig,
ModelHubBackendModelConfig,
ModelHubConfig,
+ is_model_hub_model_id,
model_hub_fixed_menu_ids,
ModelHubMenuConfig,
ModelHubModelConfig,
@@ -45,7 +46,6 @@ from config.v2_config import (
validate_model_hub_source_client_nonce,
)
from core.agent_auth_service import BackendLoginInProgressError
-from core.agent_core.ai.provider import Done, ModelCapabilities
from core.agent_core.ai.registry import sent_effort
from core.agent_core.messages import HostedCost
from core.os_errors import format_os_errno, local_error_detail
@@ -53,7 +53,7 @@ from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
from storage.models import MESSAGE_TURN_ID_SQL, agent_sessions, messages
from vibe.backend_model_catalog import (
- HostedToolSpec,
+ ImageModelSpec,
PROTOCOL_REASONING_EFFORT_DEFAULTS,
builtin_display_name,
bundled_catalog_wire_efforts_by_model,
@@ -115,7 +115,6 @@ from .events import (
contains_credential_material,
)
from .capability_evidence import (
- HOSTED_TOOL_ASPECTS,
CapabilityEvidenceStore,
EvidenceFeature,
EvidenceRecord,
@@ -140,34 +139,16 @@ from .hosted_executor import (
provider_charges,
responses_result,
)
-from .hosted_probe import ESTIMATED_COUNTS as ESTIMATED_PROBE_COUNTS
-from .hosted_probe import ESTIMATED_REPLAY_USAGE as ESTIMATED_REPLAY_PROBE_USAGE
-from .hosted_probe import ESTIMATED_USAGE as ESTIMATED_PROBE_USAGE
-from .hosted_probe import (
- NATIVE_REPLAY_PROTOCOLS,
- PROBE_MAX_OUTPUT_TOKENS,
- PROBE_BUDGET_SECONDS,
- PROBED_TOOLS,
- REPLAY_MIN_SECONDS,
- ProbeImageCheck,
- carries_native_payload,
- hidden_result_urls,
-)
-from .hosted_probe import call_outcome as hosted_call_outcome
-from .hosted_probe import probe_request as hosted_probe_request
-from .hosted_probe import replay_outcome as hosted_replay_outcome
-from .hosted_probe import replay_request as hosted_replay_request
-from .hosted_probe import run_probe as run_hosted_probe
from .hosted_tools import (
- HOSTED_PROBE_SHAPE,
+ HostedEvidence,
HostedToolSettingRefused,
+ apply_hosted_tool_put,
+ clear_request,
credential_eligible,
- untranslated,
engine_stamp,
- hosted_tool_target,
hosted_tools_status,
- parse_hosted_tool_setting,
resolve_hosted_tools,
+ untranslated,
)
from .identifiers import (
OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,
@@ -240,7 +221,7 @@ from .usage import (
local_usage_day,
)
-CONTRACT_VERSION = 14
+CONTRACT_VERSION = 15
def seeded_source_name(vendor: str) -> str:
@@ -363,8 +344,8 @@ def _described_as_unfit_for_agent_turns(match: Mapping[str, Any]) -> bool:
)
-AGENT_CHAIN_CONTRACT_VERSION = 14
-PROBE_RESULT_CONTRACT_VERSION = 14
+AGENT_CHAIN_CONTRACT_VERSION = 15
+PROBE_RESULT_CONTRACT_VERSION = 15
_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15
_SOURCE_PROBE_TIMEOUT_SECONDS = 60
# Background inventory refresh. The first tick doubles as the startup delay, so
@@ -1226,7 +1207,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
manager = EngineRuntimeManager()
return {
- "contract_version": 14,
+ "contract_version": 15,
"enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
@@ -1379,6 +1360,9 @@ class ModelHubService:
# Bundled state that never changes while this process runs, resolved once
# here at startup so that no request path reads a file on the loop.
self.engine_stamp = engine_stamp()
+ from vibe import __version__ as avibe_release
+
+ self.avibe_release = avibe_release
bundled_provider_overlay()
bundled_client_presets_once()
self.migration_blocked_backends: set[str] = set()
@@ -6038,50 +6022,54 @@ class ModelHubService:
await self._refresh_backend_catalog(backend)
return changed
+ def hosted_evidence(self) -> HostedEvidence:
+ """A reader over the evidence that applies the current wire stamp; memory only. Take one per resolution."""
+
+ return HostedEvidence(self.capability_evidence, self.engine_stamp, self.avibe_release)
+
def hosted_tools_status(self) -> dict:
- """The Tools tab read: toggles, where each tool can run, and pending re-verifications."""
+ """Models → Tools: each tool's settings, saved and effective, and what real use showed."""
return {
"hosted_tools": hosted_tools_status(
self.store.load(),
- evidence=self.capability_evidence,
+ evidence=self.hosted_evidence(),
spec_for=hosted_tool_spec,
- engine=self.engine_stamp,
- now=self.now(),
- probe_estimate=self._probe_estimate,
+ image_price=self._image_price,
)
}
- def _probe_estimate(self, source: ModelHubSourceConfig, model_id: str, tool: str) -> Optional[dict]:
- """What probing ``tool`` on this Source and model is estimated to cost at most; None when unknown.
+ def _image_price(self, source: ModelHubSourceConfig, spec: ImageModelSpec) -> Optional[dict]:
+ """One image's price for the Tools card: the vendor's list price, else an estimate, else None (never zero).
- Priced by the one pricing owner from each probe's nominal usage: the call
- probe, plus the replay probe that follows a verified call where the tool's
- payload can go back verbatim (that request uses no tool, so no tool fee).
+ Only an unqualified list price is one: a price for one size or quality would read as every image's, and the
+ card names neither. The estimate values the overlay's ``tokens_per_image`` at the model's output token rate,
+ through the one pricing owner.
"""
- if tool not in PROBED_TOOLS:
+ listed = next((entry.price for entry in spec.prices if entry.size is None and entry.quality is None), None)
+ if listed is not None:
+ return {"usd": round(listed.usd_per_1k / 1000, 6), "basis": "list"}
+ if spec.tokens_per_image is None:
return None
- costs = [
- self.hosted_call_cost(
- source, model_id, (tool,), usage=ESTIMATED_PROBE_USAGE, counts=ESTIMATED_PROBE_COUNTS[tool],
- )
- ]
- if "replay" in HOSTED_TOOL_ASPECTS[tool] and source.protocol in NATIVE_REPLAY_PROTOCOLS:
- costs.append(self.hosted_call_cost(source, model_id, (), usage=ESTIMATED_REPLAY_PROBE_USAGE, counts={}))
- if any(cost is None for cost in costs):
+ cost = self.hosted_call_cost(
+ replace(source, billing="metered"),
+ spec.id,
+ (),
+ usage=ProtocolUsageReport.of(input_tokens=0, cached_input_tokens=0, output_tokens=spec.tokens_per_image),
+ counts={},
+ )
+ if cost is None or cost.usd is None:
return None
- if any(cost.usd is None for cost in costs):
- return {"basis": "included"}
- return {"basis": "list", "usd": round(sum(cost.usd for cost in costs), 6)}
+ return {"usd": cost.usd, "basis": "estimated"}
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."""
+ """Change one hosted tool's settings, field by field; 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)
+ setting = apply_hosted_tool_put(previous, tool, payload)
except HostedToolSettingRefused as refused:
raise ModelHubError(refused.code, status=refused.status) from None
if previous.hosted_tools.get(tool) != setting:
@@ -6090,6 +6078,98 @@ class ModelHubService:
await self._commit_synced(previous, config)
return await asyncio.to_thread(self.hosted_tools_status)
+ async def clear_hosted_refusals(self, tool: str, payload: object) -> dict:
+ """Clear a tool's refusals on one Source (and model), or on every Source; it applies from the next request.
+
+ Persisted before it takes effect: a failed write changes nothing, so what the user is shown holds after a
+ restart.
+ """
+
+ try:
+ matches = clear_request(tool, payload)
+ except HostedToolSettingRefused as refused:
+ raise ModelHubError(refused.code, status=refused.status) from None
+ async with self._mutation_lock:
+ await self._clear_evidence(self.store.load(), matches)
+ return await asyncio.to_thread(self.hosted_tools_status)
+
+ async def clear_source_evidence(self, source_id: str, payload: object) -> dict:
+ """Clear one effort refusal of a Source's model (capability model §5); answers the Source."""
+
+ async with self._mutation_lock:
+ config = self.store.load()
+ source = next((item for item in config.sources if item.id == source_id), None)
+ if source is None:
+ raise ModelHubError("source_not_found", status=404)
+ if not isinstance(payload, dict) or set(payload) != {"model_id", "feature"}:
+ raise ModelHubError("invalid_parameter", status=400)
+ model_id = payload["model_id"]
+ try:
+ feature = EvidenceFeature.from_payload(payload["feature"])
+ except (TypeError, ValueError):
+ raise ModelHubError("invalid_parameter", status=400) from None
+ if not is_model_hub_model_id(model_id) or feature.kind != "effort":
+ raise ModelHubError("invalid_parameter", status=400)
+ await self._clear_evidence(
+ config,
+ lambda record: (record.source_id, record.model_id, record.feature) == (source_id, model_id, feature),
+ )
+ return {"source": self._source_payload(source, config)}
+
+ async def _clear_evidence(self, config: ModelHubConfig, matches: Callable[[EvidenceRecord], bool]) -> None:
+ """Clear under the Source mutation lock, so the identities it keeps are the ones the config holds."""
+
+ try:
+ await asyncio.to_thread(self.capability_evidence.clear, matches, live=config.sources)
+ except OSError:
+ logger.warning("Model Hub could not persist an evidence clear; nothing changed", exc_info=True)
+ raise ModelHubError("state_write_failed", status=500) from None
+
+ async def record_hosted_refusals(
+ self, source: ModelHubSourceConfig, refusals: Iterable[tuple[str, EvidenceFeature, str]],
+ ) -> None:
+ """Record refusals no upstream narrow rule writes (an executor model, an image endpoint); memory first.
+
+ Each is ``(model_id, feature, detail)`` under the current wire stamp. One call writes the batch, so sibling
+ image models of one endpoint land together. A failed file write is logged; memory keeps them.
+ """
+
+ evidence = self.hosted_evidence()
+ records = [
+ EvidenceRecord(
+ source_id=source.id,
+ model_id=model_id,
+ feature=feature,
+ status="unsupported",
+ observed_at=self.now(),
+ wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source),
+ detail=detail[:64],
+ )
+ for model_id, feature, detail in refusals
+ ]
+ if records:
+ await asyncio.to_thread(self.capability_evidence.write_refusals, records, live=self.store.load().sources)
+
+ async def record_hosted_success(
+ self, source: ModelHubSourceConfig, model_id: str, tool: str, mode: str,
+ ) -> None:
+ """Record a real success of a hosted tool (display only): the latest projection at once, the file hourly."""
+
+ record = EvidenceRecord(
+ source_id=source.id,
+ model_id=model_id,
+ feature=EvidenceFeature.hosted(tool, "call"),
+ status="verified",
+ observed_at=self.now(),
+ wire=self.hosted_evidence().wire_for(source, model_id),
+ source_identity=identity_digest(source),
+ mode=mode, # type: ignore[arg-type]
+ )
+ await asyncio.to_thread(
+ self.capability_evidence.note_success, record, live=self.store.load().sources, now=record.observed_at,
+ )
+
def _effort_refused(self, source: ModelHubSourceConfig, model_id: str, request: Any) -> bool:
"""Whether this hop has negative evidence for the effort the request sends.
@@ -6112,10 +6192,7 @@ class ModelHubService:
feature = EvidenceFeature.effort_or_none(token)
if feature is None:
return False
- view = self.capability_evidence.view(
- source, model_id, feature, engine=self.engine_stamp, shape=HOSTED_PROBE_SHAPE, now=now,
- )
- return view.status == "unsupported"
+ return self.hosted_evidence().unsupported(source, model_id, feature)
def _effort_menu(
self, backend: BackendName, model: ModelHubBackendModelConfig, resolution: ModelHubTurnResolution, now: datetime
@@ -6185,25 +6262,24 @@ class ModelHubService:
if learned is None:
return None
try:
+ # Routing state: memory takes it before the re-render that follows, even if the file write fails.
await asyncio.to_thread(
- self.capability_evidence.write,
+ self.capability_evidence.write_refusal,
EvidenceRecord(
source_id=source.id,
model_id=model_id,
feature=learned.feature,
status="unsupported",
- basis="observed",
observed_at=self.now(),
- engine=self.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
+ wire=self.hosted_evidence().wire_for(source, model_id),
source_identity=identity_digest(source),
detail=learned.detail,
),
live=self.store.load().sources,
)
- except (OSError, ValueError):
- # Evidence is advisory state: losing one record leaves the priors.
- logger.warning("Model Hub could not record capability evidence", exc_info=True)
+ except ValueError:
+ # The Source changed identity while the request ran: the refusal describes nothing that exists now.
+ logger.info("Model Hub dropped capability evidence for a Source that changed identity")
return learned
def _admits_hosted(self, content: HostedContent, source: ModelHubSourceConfig, model_id: str) -> bool:
@@ -6214,10 +6290,7 @@ class ModelHubService:
source=source,
model_id=model_id,
spec_for=hosted_tool_spec,
- evidence=self.capability_evidence,
- engine=self.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
- now=self.now(),
+ evidence=self.hosted_evidence(),
)
def hosted_call_cost(
@@ -6490,10 +6563,8 @@ class ModelHubService:
config,
source=source,
model_id=model_id,
- evidence=self.capability_evidence,
+ evidence=self.hosted_evidence(),
spec_for=hosted_tool_spec,
- engine=self.engine_stamp,
- now=self.now(),
frozen=frozen,
)
@@ -7588,28 +7659,20 @@ class ModelHubService:
def _refused_efforts(self, source: ModelHubSourceConfig, model_id: str, now: datetime) -> list[dict]:
"""The efforts this hop currently refuses, as routing reads the evidence."""
- refused = []
- for record in self.capability_evidence.for_hop(source.id, model_id):
- if record.feature.kind != "effort":
- continue
- view = self.capability_evidence.view(
- source, model_id, record.feature, engine=self.engine_stamp, shape=HOSTED_PROBE_SHAPE, now=now,
- )
- if view.status == "unsupported":
- refused.append(view)
+ evidence = self.hosted_evidence()
+ refused = [
+ record
+ for record in self.capability_evidence.for_hop(source.id, model_id)
+ if record.feature.kind == "effort" and evidence.refusal(source, model_id, record.feature) is record
+ ]
return [
{
- "effort": view.record.feature.name,
- "basis": view.record.basis,
- "observed_at": view.record.payload()["observed_at"],
- "detail": view.record.detail,
- "changes_at": (
- view.changes_at.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
- if view.changes_at is not None
- else None
- ),
+ "effort": record.feature.name,
+ "basis": "observed",
+ "observed_at": record.payload()["observed_at"],
+ "detail": record.detail,
}
- for view in sorted(refused, key=lambda item: (item.record.observed_at, item.record.feature.name))
+ for record in sorted(refused, key=lambda item: (item.observed_at, item.feature.name))
]
def agent_chain(self, backend: str, model_id: object) -> dict:
@@ -7750,261 +7813,6 @@ class ModelHubService:
"error": None if succeeded else self._test_call_failure(outcome),
}
- async def probe_hosted_tool(self, tool: str, payload: object) -> dict:
- """Run the call probe of one hosted tool on one (Source, model), and record what it shows.
-
- A user action starts every probe; nothing calls this on its own. Every
- request it sends is its own call pinned to the probed Source, with no
- route and no failover. Only ``verified``
- and ``unsupported`` are evidence; an inconclusive or transient probe
- leaves the current record as it is (``vibey-hosted-tools.md`` §3.2).
- """
-
- if (
- tool not in PROBED_TOOLS
- or not isinstance(payload, dict)
- or set(payload) != {"source_id", "model_id"}
- or not isinstance(payload["source_id"], str)
- or not payload["source_id"]
- ):
- raise ModelHubError("invalid_parameter", status=400)
- # The model as routing and evidence know it: the probe sends and records exactly that identity.
- source_id, model_id = payload["source_id"], canonical_model_id(payload["model_id"])
- if model_id is None:
- raise ModelHubError("invalid_parameter", status=400)
-
- def target(config: ModelHubConfig) -> tuple[ModelHubSourceConfig, HostedToolSpec]:
- try:
- return hosted_tool_target(config, tool, source_id, model_id, spec_for=hosted_tool_spec)
- except HostedToolSettingRefused as refused:
- raise ModelHubError(refused.code, status=refused.status) from None
-
- # Reading the config parses the whole file, so that alone runs off the controller loop. Everything after
- # reads the snapshot in memory, and recovery state stays on the loop that owns it.
- config = await asyncio.to_thread(self.store.load)
- source, spec = target(config)
- request = hosted_probe_request(
- source, model_id, tool, spec, max_tokens=self._probe_output_budget(config, source.id, model_id),
- )
-
- def selected(config: ModelHubConfig) -> ModelHubSourceConfig:
- current, current_spec = target(config)
- # The probe was built for this protocol and declaration; it is never sent as anything else.
- if current.protocol != source.protocol or current_spec.declaration != spec.declaration:
- raise ModelHubError("mapping_target_unavailable", status=409)
- return current
-
- # The whole probe answers inside the UI's RPC wait. Each call gets as long as a turn's executor gives the
- # tool, but never more than the probe has left.
- deadline = time.monotonic() + PROBE_BUDGET_SECONDS
-
- def remaining() -> float:
- return deadline - time.monotonic()
-
- def pinned(select: Callable[[ModelHubConfig], ModelHubSourceConfig]):
- async def call(body: dict, read: Callable[[InvokeHandle], Awaitable[None]]):
- return await self._user_test_call(
- source_id,
- model_id,
- select,
- lambda source: ModelHubRequest(body, protocol=source.protocol),
- stream=True,
- origin="vibey",
- consume=read,
- timeout=max(1.0, min(call_timeout(tool), remaining())),
- )
-
- return call
-
- pinned_call = pinned(selected)
-
- media_sink = ProbeImageCheck() if tool == "image_generation" else None
- terminal, calls = await run_hosted_probe(request, pinned_call, media_sink=media_sink)
- if not calls:
- logger.warning("Model Hub's %s probe sent no request", tool)
- raise ModelHubError("invalid_parameter", status=400)
- call_last = calls[-1]
- replays_natively = "replay" in HOSTED_TOOL_ASPECTS[tool] and source.protocol in NATIVE_REPLAY_PROTOCOLS
-
- # Each step reads what the provider sent, which can be megabytes of results and payload, off the controller
- # loop.
- def judge_call() -> tuple[Optional[LearnedEvidence], str, frozenset[str]]:
- learned = self._probe_rejection(call_last, model_id)
- verdict = hosted_call_outcome(tool, terminal, call_last.outcome, learned)
- # Only a result the visible answer does not show proves a replayed payload was read; with none, the
- # replay stays unknown and turns replay synthetically, which is lossless.
- verified = verdict == "verified" and isinstance(terminal, Done)
- return learned, verdict, hidden_result_urls(terminal.message) if verified and replays_natively else frozenset()
-
- call_learned, call_verdict, asked = await asyncio.to_thread(judge_call)
- recorded_for = await self._record_probe_evidence(
- EvidenceFeature.hosted(tool, "call"), call_verdict, call_last, call_learned, model_id,
- )
- replay: Optional[dict] = None
- # The replay probe follows a call probe that verified and was recorded for the Source as it is, on a tool
- # whose payload can go back verbatim, when the call returned a result the replay can ask about.
- replayable = recorded_for is not None and bool(asked)
- if replayable and remaining() < REPLAY_MIN_SECONDS:
- # Too little of the probe's time is left for a replay that could finish: try again.
- replay = {"outcome": "transient", "error": None}
- elif replayable:
- assert isinstance(terminal, Done)
-
- def replay_selected(config: ModelHubConfig) -> ModelHubSourceConfig:
- current = selected(config)
- # The replay carries the call's provider-native payload, so it goes only to the Source identity that
- # produced it and was recorded for it: never through a credential or endpoint that replaced it.
- if identity_digest(current) != recorded_for:
- raise ModelHubError("mapping_target_unavailable", status=409)
- return current
-
- try:
- replay_terminal, replay_calls = await run_hosted_probe(
- hosted_replay_request(request, tool, terminal.message), pinned(replay_selected),
- )
- except ModelHubError as refused:
- # The call's result stands; the replay did not run. A Source that changed has no replay to report,
- # and anything else (the engine went away) is worth trying again.
- replay_terminal, replay_calls = None, []
- if refused.code != "mapping_target_unavailable":
- replay = {"outcome": "transient", "error": None}
- if replay_calls:
- replay_last = replay_calls[-1]
-
- def judge_replay() -> tuple[Optional[LearnedEvidence], str]:
- learned = self._probe_rejection(replay_last, model_id)
- carried = carries_native_payload(replay_last.body, terminal.message)
- return learned, hosted_replay_outcome(
- tool, replay_terminal, replay_last.outcome, learned, asked=asked, carried=carried,
- )
-
- replay_learned, replay_verdict = await asyncio.to_thread(judge_replay)
- await self._record_probe_evidence(
- EvidenceFeature.hosted(tool, "replay"),
- replay_verdict,
- replay_last,
- replay_learned,
- model_id,
- identity=recorded_for,
- )
- replay = self._probe_aspect(replay_verdict, replay_terminal, replay_last)
- return {
- "probe": {
- "tool": tool,
- "source_id": call_last.source.id,
- "model_id": model_id,
- "call": self._probe_aspect(call_verdict, terminal, call_last),
- "replay": replay,
- },
- **await asyncio.to_thread(self.hosted_tools_status),
- }
-
- def _probe_rejection(self, call: Any, model_id: str) -> LearnedEvidence | None:
- """The one feature a probe request's refusal names, through the narrow rules real requests learn from.
-
- Only the request the response ended on speaks for the tool: a resend that completes outranks a refusal of
- the request it replaced.
- """
-
- if call.outcome.rejection is None:
- return None
- return learn_from_rejection(
- call.body,
- call.outcome.rejection,
- request_protocol=call.source.protocol,
- source=call.source,
- model_id=model_id,
- spec_for=hosted_tool_spec,
- )
-
- def _probe_aspect(self, verdict: str, terminal: Any, last: Any) -> dict:
- """One probe aspect's result, with why a request that never completed failed, as the Source test shows it."""
-
- return {
- "outcome": verdict,
- "error": (
- self._test_call_failure(last.outcome)
- if verdict != "unsupported" and not isinstance(terminal, Done)
- else None
- ),
- }
-
- async def _record_probe_evidence(
- self,
- feature: EvidenceFeature,
- verdict: str,
- last: Any,
- learned: LearnedEvidence | None,
- model_id: str,
- *,
- identity: str | None = None,
- ) -> str | None:
- """Record what a probe showed for the Source as it reads now; the identity recorded for, or None.
-
- Only ``verified`` and ``unsupported`` are evidence. A Source whose identity
- changed during the probe (a new credential, endpoint or protocol) is one the
- probe vouches for nothing on; verifying the credential it ran on is no such
- change. ``identity``, when given, is the one the probe's earlier aspect was
- recorded for: both records then describe the same Source.
- """
-
- current = await asyncio.to_thread(self.store.load)
- live = next((item for item in current.sources if item.id == last.source.id), None)
- if live is None or identity_digest(live) != identity_digest(last.source):
- return None
- digest = identity_digest(live)
- if identity is not None and digest != identity:
- return None
- if verdict in ("verified", "unsupported"):
- try:
- await asyncio.to_thread(
- self.capability_evidence.write,
- EvidenceRecord(
- source_id=live.id,
- model_id=model_id,
- feature=feature,
- status=verdict,
- basis="probe",
- observed_at=self.now(),
- engine=self.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
- source_identity=digest,
- detail=learned.detail if verdict == "unsupported" and learned is not None else None,
- ),
- live=current.sources,
- )
- except (OSError, ValueError):
- # Evidence is advisory state: the status read the probe returns shows what was kept.
- logger.warning("Model Hub could not record the %s probe result", feature.name, exc_info=True)
- return None
- return digest
-
- def _probe_output_budget(self, config: ModelHubConfig, source_id: str, model_id: str) -> int:
- """The smallest output any Vibey turn on this hop would ask for, at most the probe's own ceiling.
-
- A Vibey turn asks for its menu model's ``output_budget``, so a probe on a
- hop several menu models route to takes the smallest of theirs, and one
- no menu model routes to takes the budget of a model nothing describes.
- """
-
- from modules.agents.vibey.context import output_budget
-
- now = self.now()
- unavailable = self._unavailable_native_sources(config, "vibey")
- # ``config`` is the current snapshot, so recovery reads it directly rather than loading another.
- live_recovery = self.recovery.annotations(config)
- budgets = [
- output_budget(ModelCapabilities(context_window=model.context_window, max_output_tokens=model.max_output_tokens))
- for model in config.agents["vibey"].models
- if any(
- hop.source_id == source_id and hop.model_id == model_id
- for hop in resolve_model_hub_turn(
- config, "vibey", model.id, now=now, unavailable_source_ids=unavailable, live_recovery=live_recovery,
- ).inspected_hops
- )
- ]
- return min([PROBE_MAX_OUTPUT_TOKENS, *(budgets or [output_budget(ModelCapabilities())])])
-
def _test_call_failure(self, outcome: RawCallOutcome) -> str:
"""A failed user test call's detail key, for display only: it blocks nothing and changes no route state."""
diff --git a/docs/plans/model-hub-capability-model.md b/docs/plans/model-hub-capability-model.md
index 4fa7573da..04241225e 100644
--- a/docs/plans/model-hub-capability-model.md
+++ b/docs/plans/model-hub-capability-model.md
@@ -72,7 +72,7 @@ is its JSON Schema. The store is `core/handlers/model_hub/capability_evidence.py
| `basis` | `observed`: learned from a real request. There is no other basis (v1's `probe` is gone). |
| `observed_at` | UTC timestamp |
| `mode` | `verified` records only: how the call ran, `native`, `executor` or `direct` (`vibey-hosted-tools.md` §3.2) |
-| `wire` | the wire stamp the record was observed under: the engine release, the Avibe release, and a digest of the Source's rendered engine entry, credentials and model list excluded (§3.3) |
+| `wire` | the wire stamp the record was observed under: the engine release, the Avibe release, and the model's rendered fields the Source identity does not cover (§3.3) |
| `detail` | required when `status` is `unsupported`: 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 |
@@ -129,16 +129,28 @@ no marker, and a pending one's marker becomes its generation.
- **Nothing probes.** Since hosted tools design v2 (2026-10-15) no component calls a provider to learn a capability:
not on a user action, not in the background. Efforts were never probed; hosted tools no longer are. Every record
comes from a real request in a turn the user started (§3.2).
-- **Negative evidence never outlives the wire it was learned on.** Each record carries `wire`: the engine release,
- the Avibe release, and a digest of the Source's rendered engine entry (what Avibe writes into the engine config for
- that Source), credentials and the model list excluded. The Avibe release covers what Avibe itself sends: the
- bundled overlay's declarations and `include` values and the adapters' request shape, so an update that fixes a
- rejected declaration is tried again at once. Refusals are relearned once per release, each at the cost of one
- re-rendered request. An `unsupported` record whose stamp differs from the current one reads as unknown, for
- efforts and hosted tools alike; a `verified` record is display-only history and is kept. So a refusal learned under one engine or one rendered config cannot survive a
- change that could reverse it: an engine upgrade, or a rendering change such as the `is-compat` flag for xAI
- (#2620), which changes what xAI receives for replayed reasoning. A change on the provider's side, which the stamp
- cannot see, waits for the user's clear.
+- **Negative evidence never outlives the wire it was learned on** (owner rule: a Source config change resets it).
+ A record carries `source_identity` and `wire`, and reads as unknown once either differs from the current one.
+ Together they cover every input of the engine renderer (`vibe/model_hub_runtime/config.py`, `_append_source`)
+ and of the request:
+
+ | Input the renderer or request reads | Covered by |
+ | --- | --- |
+ | vendor, protocol, base URL (or the vendor's official default) | `source_identity` |
+ | credential (the API key value, or the OAuth auth file) and its auth scheme, which is fixed per credential ref | `source_identity` (`credential_ref`, `credential_generation`) |
+ | supply channel and Source kind | `source_identity` |
+ | the model's registered reasoning tiers (`thinking.levels`), which decide whether the engine forwards or strips an effort | `wire` (the model's rendered fields) |
+ | Avibe's own rendering and request code: entry shapes, fixed per-entry flags (`cloak`, `rebuild-mid-system-message`), vendor-wide flags such as xAI's `is-compat` (#2620), the bundled overlay's declarations and `include` values, the adapters' request shape | `wire` (the Avibe release) |
+ | the engine binary | `wire` (the engine release) |
+
+ Not inputs that can reverse a refusal, so not covered: which models are registered (membership does not change
+ how a registered model is sent), the routing prefix and reload marker (engine-internal), and the text-only marking
+ (from the models.dev copy, not Source config; it only replaces images in tool results). The Source config has no
+ custom headers. **Rule for future fields:** a Source field the renderer starts to read joins `source_identity`,
+ or, if it is per model, the model's rendered fields (`capability_evidence.render_fields`).
+ So a refusal learned under one engine, release or Source config cannot survive a change that could reverse it.
+ The stamp is computed from the config in memory, never on a request path from the engine state. A change on the
+ provider's side, which no stamp can see, waits for the user's clear.
- **What goes.** v1's `shape` field, probe-shape staleness, age-based re-verification, and the `hosted_wire`
manifest field (never introduced; `engine_stamp()` loses its `hosted_wire` branch). Positive evidence needed them
because it vouched for a wire; it no longer vouches for anything.
@@ -198,7 +210,7 @@ Fields of one vendor entry, mirrored by
| `wire_efforts` | a list of effort names, or `null` (or absent) to defer to models.dev |
| `hosted_tools` | optional; protocol (`anthropic`, `openai_responses`, `openai_chat`, `google`) → search tool (`web_search`, `x_search`) → `{declaration, price?, include?}`. `declaration` is required, has a `type`, and is sent verbatim. `price` is optional: absent means no list price is known, never zero. `include` lists Responses `include` values the tool needs (OpenAI web search: `web_search_call.action.sources`). v1's OpenAI `image_generation` entry is removed: no chat request declares a hosted image tool (`vibey-hosted-tools.md` §7). |
| `executor_model` | new, optional, at vendor scope (beside `models[]`): the vendor's lightweight model id that runs proxied search calls on this vendor's Sources (`vibey-hosted-tools.md` §6), e.g. a Haiku, mini or fast tier. The executor call's declaration and `include` are those of the family row that model id matches, on the Source's protocol. A vendor without it is never an executor. |
-| `image_models[]` | new, optional per vendor: `{id, description, endpoint: "images" \| "chat_image", params, price?}`. `description` is the one line the `image_generate` enum shows; `endpoint` says how the gateway runs it (the engine's images endpoints, or the chat route with the image response modality); `params` lists which common parameters the model takes (`size`, `images`, `n`), and `size_forms` which forms of `size` it accepts (`pixels`, `ratio`); `prices[]` is optional, each entry a `price` with an `image` unit keyed by the `size` and `quality` it applies to (absent keys match any), so a vendor that prices sizes or qualities apart is valued at the size the call resolved. `tokens_per_image` is optional: the documented output tokens of one image, which the pricing module values at the model's output token rate as an estimate (shown with ≈) where no per-image price exists. Only models whose route the implementation verified through the shipped engine are listed. |
+| `image_models[]` | new, optional per vendor: `{id, description, endpoint: "images" \| "chat_image", params, size_forms, prices?, tokens_per_image?}`. `description` is the one line the `image_generate` enum shows; `endpoint` says how the gateway runs it (the engine's images endpoints, or the chat route with the image response modality); `params` lists which common parameters the model takes (`size`, `images`, `n`), and `size_forms` which forms of `size` it accepts (`pixels`, `ratio`); `prices[]` is optional, each entry a `price` with an `image` unit keyed by the `size` and `quality` it applies to (absent keys match any), so a vendor that prices sizes or qualities apart is valued at the size the call resolved. `tokens_per_image` is optional: the documented output tokens of one image, which the pricing module values at the model's output token rate as an estimate (shown with ≈) where no per-image price exists. Only models whose route the implementation verified through the shipped engine are listed. |
| `price` | `unit` (`call`, `search`, `post`, `profile`, `image`), `usd_per_1k` ≥ 0, `as_of` (date) and `url` (https), all required; optional `extra[]` of `{unit, usd_per_1k}`. An `image` unit may carry `quality` and `size` when the vendor prices them apart. |
- The overlay records what the **provider** offers, and it is the prior every hop starts from: a hosted tool is
assumed where the overlay offers it, until a real request refuses it. Whether a Source (a relay, a subscription)
@@ -222,9 +234,9 @@ and the existing tone vocabulary (`TimeHint` for dates):
- Unknown draws nothing. A healthy unknown is the normal case and must not look like a warning (V6 rule:
exceptions only).
-- A chip opens a detail popover (time, basis, the refusal's HTTP status and code). Every refusal chip's popover has
+- A chip opens a detail popover (time, basis, the refusal's HTTP status and code). Every refusal chip carries
"清除" (owner-approved mockup, 2026-10-15); a hosted-tool refusal clears through the Tools `clear` endpoint
- (`vibey-hosted-tools.md` §3.3). An effort refusal's popover has its "清除" action, which clears that (Source, model, effort) record, so the next request at that effort tries the
+ (`vibey-hosted-tools.md` §3.3). An effort refusal's "清除" clears that (Source, model, effort) record, so the next request at that effort tries the
Source again (`POST /api/models/sources/<source_id>/evidence/clear` with `{model_id, feature}`, the same verb and
shape as the hosted clear). An unknown `source_id` is 404; a missing record is a no-op that answers the Source;
`feature` must be `{kind: "effort", name}`, and a hosted-tool feature is 400; the file is written first, and a
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index fa6ff5d43..0a4dfa1cf 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,6 +1,22 @@
# Model Hub contracts
-Status: **contract_version 14**, 2026-10-14: opaque history is bound to the account that issued it, the Source
+Status: **contract_version 15**, 2026-10-15: hosted tools design v2 (`../vibey-hosted-tools.md`), passive and
+default-on, with no probes. This bump publishes the Model Hub side; the hop-resolution and executor changes join it
+before it ships.
+- Capability evidence is passive (`capability-evidence.schema.json`, version 2): `basis` is `observed` only; a record is
+ keyed by status, so a `verified` success (with its `mode`) and an `unsupported` refusal coexist; refusals have no
+ time limit and read as unknown once the Source identity or the `wire` stamp (engine release, Avibe release, the
+ model's rendered fields) differs; `shape` and `engine` are gone.
+- Refused efforts lose `changes_at` and their `probe` basis (`agent-chain.schema.json`, `source.schema.json`).
+- The Tools read is rewritten (`hosted-tools-status.schema.json`): per tool `enabled`, passive `status` (`latest_ok`,
+ `refused[]`, `verified[]`), the search executor order (saved and effective, with candidates), and the image models
+ with their default.
+- The probe endpoint and `hosted-tool-probe-result.schema.json` are removed. `POST /api/models/hosted-tools/<tool>/clear`
+ and `POST /api/models/sources/<source_id>/evidence/clear` clear refusals; the PUT is per field.
+- The provider overlay gains a vendor's `executor_model` and `image_models[]`, and loses the native `image_generation`
+ declaration.
+
+It builds on v14 (2026-10-14): opaque history is bound to the account that issued it, the Source
identity, not only to the origin (#2620): a provider refuses another account's encrypted reasoning.
- `HopResolution.source_identity` (`hop-resolution.schema.json`) names the primary hop Source's credential-free
identity, which Vibey records on each response its own Source served and matches before replaying opaque payloads.
@@ -206,7 +222,7 @@ comparison. A gate may not report success by comparing stale input with itself.
## Version closure
-`contract_version` 14 must coexist in all registered version locations on the same tested head:
+`contract_version` 15 must coexist in all registered version locations on the same tested head:
- `mirror-registry.json`
- `agent-chain.schema.json`
@@ -264,8 +280,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-tool-probe-result.schema.json` | One user-started hosted-tool probe: per aspect, whether it verified the tool, showed it unsupported, or was inconclusive or transient (which write no evidence), with the Source test's failure detail for a request that failed. |
-| `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. |
+| `hosted-tools-status.schema.json` | The Tools read: each hosted tool's switch, its passive status (latest success, refusals, per-pair successes), the search executor order (saved, effective, candidates with their unit rates) and the image models with their default. 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. |
@@ -282,6 +297,6 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `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. |
+| `capability-evidence.schema.json` | One persisted (Source, model, feature, status) evidence record, observed from real traffic only: a refusal (routing state, no time limit) or a success (display history, with its mode), with the wire stamp 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.py
index c6441e78b..330117856 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 v14 (2026-10-14).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v15 (2026-10-15).
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.json
index 3fbeb36fe..9a5d76004 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": 14 },
+ "contract_version": { "const": 15 },
"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },
"model_id": { "type": "string" },
"manual_override": {
@@ -104,14 +104,13 @@
"description": "Reasoning efforts this exact hop is currently known to refuse (capability evidence, model-hub-capability-model.md §3.4), oldest evidence first; absent when none. A request at one of them skips this hop. The effort menu omits a tier only when every hop that can serve the model lists it, and otherwise marks it \"not on: <Source>\". Read-only: routing reads the evidence store itself.",
"items": {
"type": "object",
- "required": ["effort", "basis", "observed_at", "detail", "changes_at"],
+ "required": ["effort", "basis", "observed_at", "detail"],
"additionalProperties": false,
"properties": {
"effort": { "type": "string", "minLength": 1 },
- "basis": { "enum": ["probe", "observed"] },
+ "basis": { "const": "observed" },
"observed_at": { "type": "string", "format": "date-time" },
- "detail": { "type": ["string", "null"], "maxLength": 64 },
- "changes_at": { "type": ["string", "null"], "format": "date-time", "description": "When this refusal stops reading as it does now (observed expiry, probe re-verify mark); null when nothing is scheduled." }
+ "detail": { "type": ["string", "null"], "maxLength": 64 }
}
}
}
@@ -254,7 +253,7 @@
],
"examples": [
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"model_id": "unlisted-model",
"manual_override": null,
@@ -264,7 +263,7 @@
"supply_state": "ok"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -274,7 +273,7 @@
"supply_state": "ok"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": null,
@@ -284,7 +283,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "opencode",
"model_id": "glm-5.2",
"manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },
@@ -294,7 +293,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -304,7 +303,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -314,7 +313,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 14,
+ "contract_version": 15,
"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.json
index 25299822b..c982ad52a 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -38,8 +38,9 @@
{"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/hosted-tools/<tool>/probe", "response_schema": "HostedToolProbeResponse", "exercise": {"path": "/api/models/hosted-tools/web_search/probe", "status": 200, "json": {"source_id": "src_conform001", "model_id": "claude-opus-4-6"}}},
+ {"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_order": null}}},
+ {"method": "POST", "path": "/api/models/hosted-tools/<tool>/clear", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools/web_search/clear", "status": 200, "json": {"source_id": "src_conform001"}}},
+ {"method": "POST", "path": "/api/models/sources/<source_id>/evidence/clear", "response_schema": "SourceResponse", "exercise": {"path": "/api/models/sources/src_conform001/evidence/clear", "status": 200, "json": {"model_id": "claude-opus-4-6", "feature": {"kind": "effort", "name": "max"}}}},
{"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"}}},
@@ -59,7 +60,7 @@
"required": ["ok", "contract_version", "probe"],
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"probe": {"$ref": "model-hub/source-probe-result.schema.json"}
}
},
@@ -158,7 +159,7 @@
"SuccessCore": {
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14}
+ "contract_version": {"const": 15}
}
},
"SourceListResponse": {
@@ -167,7 +168,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}
}
},
@@ -177,7 +178,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"observation": {"$ref": "model-hub/observation-result.schema.json"}
}
},
@@ -187,7 +188,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"source": {"$ref": "#/definitions/SourceApi"},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},
"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}
@@ -199,7 +200,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"source": {"$ref": "#/definitions/SourceApi"}
}
},
@@ -209,7 +210,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"source": {"$ref": "#/definitions/SourceApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -221,7 +222,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
}
@@ -232,7 +233,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}
}
},
@@ -242,7 +243,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
@@ -259,7 +260,7 @@
],
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"agent": {"$ref": "#/definitions/AgentSupplyApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}
@@ -284,7 +285,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": false},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"error": {"const": "candidate_suppliers_changed"},
"detail": {"type": "string", "minLength": 1},
"changed": {
@@ -304,7 +305,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"agent": {
"type": "object",
"required": ["backend", "mode", "catalog_models"],
@@ -405,7 +406,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"candidates": {
"type": "object",
"required": ["builtin", "providers", "in_list"],
@@ -424,7 +425,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"matches": {
"type": "array",
"maxItems": 8,
@@ -458,7 +459,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
@@ -468,7 +469,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
}
},
@@ -478,7 +479,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"chain": {"$ref": "model-hub/agent-chain.schema.json"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -490,7 +491,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"probe": {"$ref": "model-hub/probe-result.schema.json"}
}
},
@@ -500,7 +501,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
@@ -510,7 +511,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
@@ -520,7 +521,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"quota": {"$ref": "model-hub/quota-summary.schema.json"}
}
},
@@ -530,18 +531,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
- "hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}
- }
- },
- "HostedToolProbeResponse": {
- "type": "object",
- "required": ["ok", "contract_version", "probe", "hosted_tools"],
- "additionalProperties": false,
- "properties": {
- "ok": {"const": true},
- "contract_version": {"const": 14},
- "probe": {"$ref": "model-hub/hosted-tool-probe-result.schema.json"},
+ "contract_version": {"const": 15},
"hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}
}
},
@@ -551,7 +541,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -573,7 +563,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -596,7 +586,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -621,7 +611,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14}
+ "contract_version": {"const": 15}
}
},
"RuntimeApi": {
@@ -643,7 +633,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"scan": {"$ref": "model-hub/migration-scan.schema.json"}
}
},
@@ -653,7 +643,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"applied": {"type": "integer", "minimum": 0},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}
@@ -665,7 +655,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}
}
},
@@ -676,7 +666,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"provenance": {
"anyOf": [
{"$ref": "model-hub/turn-provenance.schema.json"},
@@ -691,7 +681,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 14},
+ "contract_version": {"const": 15},
"runtime": {"$ref": "#/definitions/RuntimeApi"}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 8662070a4..0c0324595 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; unknown
API siblings retain the Owner default.
-Status: **Normative, `contract_version` 14** — 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` 15** — 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: 14, ...}`.
+Success envelope: `{ok: true, contract_version: 15, ...}`.
Failure envelope:
-`{ok: false, contract_version: 14, error: <machine_code>, detail?: <i18n_key>}`.
+`{ok: false, contract_version: 15, 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, requir
exercised HTTP response for every registry entry, and validates that response against
the route's named schema.
-The shared envelope and every versioned nested contract carry `contract_version` 14, the
+The shared envelope and every versioned nested contract carry `contract_version` 15, the
terminal value. Supported persisted config shapes and historical TurnProvenance
remain readable; ephemeral envelopes use only the terminal version.
@@ -71,9 +71,10 @@ 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 what one call probe there is estimated to cost (`probe_estimate`: `list` with `usd`, `included` on a monthly Source, or null when unknown, never zero), 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 serving that model (not a retired tombstone), with 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/hosted-tools/<tool>/probe` | `{source_id, model_id}` → `{probe: HostedToolProbeResult, hosted_tools: HostedToolsStatus}` | Runs the tool's call probe once on exactly that (Source, model), at the user's request: the production request Vibey would send natively, with one fixed message and, except on Anthropic, the tool forced. Vibey's adapter runs unchanged, and every request it sends is its own real, metered call pinned to that Source with no failover. Each probe step (the call, and the replay below) sends at most two requests, the second only when the endpoint refused a field before answering (Anthropic's one-hour cache lifetime), so each step runs the model once: an action makes at most four requests, of which at most two run the model (`hosted-tool-probe-result.schema.json`). `verified` and `unsupported` write `probe` evidence for the tool's `call`; `inconclusive` (the response completed without the tool's result, or the request failed for another reason) and `transient` (overload, 5xx, rate limit, timeout) write none. A generated image counts only when Vibey's parsing could keep it; the probe keeps no file. When the call verifies and was recorded, a tool with a `replay` aspect (`web_search`, `x_search`) on a protocol that replays natively (Anthropic, Responses) gets the replay probe in the same action. It sends the call's turn back with the native payload in place, with nothing forced, and asks for result URLs the visible answer did not show. It is `verified` when the answer names one of those without calling the tool, `unsupported` on a 400 naming the replayed content or a new call to the tool, and otherwise `inconclusive`, as is any request that did not carry the payload verbatim. It writes `replay` evidence by the same rules. `replay` is null when no replay ran, including when no result was hidden from the visible answer. The whole probe answers inside the UI's RPC timeout; a replay with under a minute left is not sent and reads `transient`. An unknown tool or a malformed body returns `400 invalid_parameter`; the target is refused exactly as a PUT executor is. Nothing else starts a probe. |
+| GET `/api/models/hosted-tools` | → `{hosted_tools: HostedToolsStatus}` | Models → Tools (`hosted-tools-status.schema.json`): every catalog tool with its switch (absent setting = on), its passive status from real use (`latest_ok`, current `refused[]`, per-pair `verified[]`), for a search tool the saved and effective executor order with every eligible executor candidate and its unit rates, and for `image_generate` the saved and effective default and the available image models. Memory only; nothing is probed. |
+| PUT `/api/models/hosted-tools/<tool>` | `{enabled?: boolean, executor_order?: null \| [source_id], default_model?: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Changes one tool's settings field by field: an absent field is unchanged, `null` resets `executor_order` to automatic or `default_model` to the default. `executor_order` is for search tools and `default_model` for `image_generate`; values are saved as given, never resolved. It applies from the next turn and interrupts nothing. An unknown tool returns `404 hosted_tool_not_found`; an empty or malformed body `400 invalid_parameter`, including a null `enabled`, an id that is not a Source id (`src_…`), or a model id with surrounding whitespace. |
+| POST `/api/models/hosted-tools/<tool>/clear` | `{source_id?, model_id?}` → `{hosted_tools: HostedToolsStatus}` | Clears the tool's refusals (`call` and `replay`): on one Source and model, on one Source (every model), or with `{}` on every Source. `model_id` requires `source_id`; neither is nullable, so a malformed body is refused rather than widened into a broader clear. A Source or model with nothing to clear is a no-op that answers the read. The file is written first: a failed write returns `500 state_write_failed` and changes nothing. A cleared Source is assumed again from its next request. An unknown tool returns `404 hosted_tool_not_found`; any other body `400 invalid_parameter`. |
+| POST `/api/models/sources/<source_id>/evidence/clear` | `{model_id, feature: {kind: "effort", name}}` → `{source: Source}` | Clears one effort refusal of a Source's model, so the next request at that effort may reach it. A missing record is a no-op. An unknown Source returns `404 source_not_found`; a hosted-tool feature or any other body `400 invalid_parameter` (hosted refusals clear through the Tools clear); a failed write `500 state_write_failed` with nothing changed. |
| 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. A committed native Claude authorization may return `state: success` with `application_failed: true`: Source materialization succeeds exactly once from its receipt, while that attempt's runtime-application failure is presented as a warning. Status reads never retry runtime application; current launch readiness remains a separate lifecycle observation. |
| 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`. |
@@ -81,7 +82,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[], clean_api_keys?: boolean}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It checks saved configuration and custody locally, copies API keys without upstream validation, upgrades an existing native subscription Source in place when present, and commits Source/Routes/backend mode atomically. API-key originals are kept unless cleanup was selected. 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` 14 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` 15 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. |
@@ -639,7 +640,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 14,
+ "contract_version": 15,
"source": {
"id": "src_anthkey01",
"kind": "api_key",
@@ -749,7 +750,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c
```json
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [
@@ -885,7 +886,7 @@ API-key success:
```json
{
"ok": true,
- "contract_version": 14,
+ "contract_version": 15,
"source": {
"id": "src_relay9c1x",
"kind": "api_key",
@@ -976,7 +977,7 @@ Status and submit return the same terminal shape:
```json
{
"ok": true,
- "contract_version": 14,
+ "contract_version": 15,
"flow": {
"flow_id": "oaf_claude01",
"client_nonce": "ofn_01j5w8z7p4n6q2rt",
@@ -1049,9 +1050,9 @@ a valid `interrupted` chain.
```json
{
"ok": true,
- "contract_version": 14,
+ "contract_version": 15,
"chain": {
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -1078,7 +1079,7 @@ In Direct mode both chain and probe refuse with:
```json
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"error": "direct_mode",
"detail": "models.hub.direct_mode"
}
@@ -1092,9 +1093,9 @@ A successful probe nests its result:
```json
{
"ok": true,
- "contract_version": 14,
+ "contract_version": 15,
"probe": {
- "contract_version": 14,
+ "contract_version": 15,
"backend": "claude",
"channel": "hub",
"reachable": false,
@@ -1117,7 +1118,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"channel": "native_cli",
"reachable": true,
@@ -1130,7 +1131,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 14,
+ "contract_version": 15,
"backend": "codex",
"channel": "native_cli",
"reachable": false,
@@ -1146,7 +1147,7 @@ No candidate is an API error with a typed model-scoped state:
```json
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
"supply": {
@@ -1337,7 +1338,7 @@ The store retains at most 500 exactly attributed settled turns with its existing
writes. Ambiguous attribution remains excluded; this is not a log of every upstream
request. 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: 14, provenance: TurnProvenance | null}`;
+Success uses exactly `{ok: true, contract_version: 15, provenance: TurnProvenance | null}`;
there is no `success` field or envelope exception.
Local `engine_down` records may also contain `local_error_detail`, an OS-generated
@@ -1431,7 +1432,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"error": "provenance_unavailable",
"detail": "models.provenance.direct_mode"
}
@@ -1440,7 +1441,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"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.json
index f6a246aef..acf623984 100644
--- a/docs/plans/model-hub-contracts/capability-evidence.schema.json
+++ b/docs/plans/model-hub-contracts/capability-evidence.schema.json
@@ -2,12 +2,12 @@
"$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.",
+ "description": "One persisted evidence record per (Source, model, feature, status) in the Model Hub state directory (model-hub-capability-model.md §3.1). Absence is unknown. Passive only: written from real requests, never probed. An unsupported record is routing state with no time limit, read as unknown once its wire stamp differs from the current one or the user clears it; a verified record is display history of a real success and never changes routing.",
"type": "object",
- "required": ["version", "source_id", "model_id", "feature", "status", "basis", "observed_at", "engine", "shape", "source_identity"],
+ "required": ["version", "source_id", "model_id", "feature", "status", "basis", "observed_at", "wire", "source_identity"],
"additionalProperties": false,
"properties": {
- "version": { "const": 1 },
+ "version": { "const": 2 },
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
"model_id": { "type": "string", "minLength": 1 },
"feature": {
@@ -27,22 +27,23 @@
"additionalProperties": false,
"properties": {
"kind": { "const": "hosted_tool" },
- "name": { "enum": ["web_search", "x_search", "image_generation"] },
+ "name": { "enum": ["web_search", "x_search", "image_generate"] },
"aspect": { "enum": ["call", "replay"] }
},
- "if": { "properties": { "name": { "const": "image_generation" } } },
+ "if": { "properties": { "name": { "const": "image_generate" } } },
"then": { "properties": { "aspect": { "const": "call" } } }
}
]
},
"status": { "enum": ["verified", "unsupported"] },
- "basis": { "enum": ["probe", "observed"] },
+ "basis": { "const": "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." },
+ "wire": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$", "description": "The wire the record was observed under: a digest of the engine release, the Avibe release, and the model's rendered fields that the Source identity does not cover (its registered reasoning tiers). With source_identity (vendor, protocol, base URL, credential, credential generation) it covers every Source field the engine renderer reads (model-hub-capability-model.md §3.3). An unsupported record under another stamp reads as unknown." },
"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." }
+ "detail": { "type": "string", "minLength": 1, "maxLength": 64, "description": "unsupported only: HTTP status and upstream machine code, never upstream text." },
+ "mode": { "enum": ["native", "executor", "direct"], "description": "verified only: how the call ran." }
},
- "if": { "properties": { "basis": { "const": "observed" } } },
- "then": { "required": ["detail"], "properties": { "status": { "const": "unsupported" } } }
+ "if": { "properties": { "status": { "const": "unsupported" } } },
+ "then": { "required": ["detail"], "not": { "required": ["mode"] } },
+ "else": { "required": ["mode"], "not": { "required": ["detail"] } }
}
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index 06682d181..c58a8e6aa 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": 14 },
+ "contract_version": { "const": 15 },
"error": {
"enum": [
"source_last_supplier",
@@ -116,7 +116,7 @@
"examples": [
{
"ok": false,
- "contract_version": 14,
+ "contract_version": 15,
"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/hosted-tool-probe-result.schema.json b/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
deleted file mode 100644
index f72967b45..000000000
--- a/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "$schema": "http://json-schema.org/draft-07/schema#",
- "$id": "model-hub/hosted-tool-probe-result.schema.json",
- "title": "HostedToolProbeResult",
- "description": "One user-started hosted-tool probe on exactly one (Source, model). Only verified and unsupported are evidence; inconclusive and transient leave the current record as it was (vibey-hosted-tools.md §3.2).",
- "type": "object",
- "additionalProperties": false,
- "required": ["tool", "source_id", "model_id", "call", "replay"],
- "properties": {
- "tool": {"enum": ["web_search", "x_search", "image_generation"]},
- "source_id": {"type": "string", "minLength": 1},
- "model_id": {"type": "string", "minLength": 1},
- "call": {"$ref": "#/definitions/aspect"},
- "replay": {
- "description": "The replay probe that follows a verified, recorded call: null when none ran (the call did not verify or was not recorded, the tool has no replay aspect, the protocol does not replay natively, or no result URL was hidden from the visible answer). transient with a null error when the probe had too little time left to send it.",
- "oneOf": [{"type": "null"}, {"$ref": "#/definitions/aspect"}]
- }
- },
- "definitions": {
- "aspect": {
- "type": "object",
- "additionalProperties": false,
- "required": ["outcome", "error"],
- "properties": {
- "outcome": {"enum": ["verified", "unsupported", "inconclusive", "transient"]},
- "error": {
- "description": "The Source test's detail key for a request that failed before its response completed; null otherwise.",
- "type": ["string", "null"],
- "minLength": 1
- }
- },
- "allOf": [{
- "if": {"properties": {"outcome": {"enum": ["verified", "unsupported"]}}},
- "then": {"properties": {"error": {"type": "null"}}}
- }]
- }
- }
-}
diff --git a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
index 58149204d..b427d9f34 100644
--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
@@ -2,108 +2,81 @@
"$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.",
+ "description": "The Models → Tools read (vibey-hosted-tools.md §3.3, §8): each tool's settings, saved and effective, and what real use showed. A report only: hop resolution reads config and evidence itself. Saved values are never resolved ones, so a client never writes back an effective value.",
"type": "object",
- "required": ["tools", "reverify"],
+ "required": ["tools"],
"additionalProperties": false,
"properties": {
"tools": {
"type": "array",
"description": "Every catalog tool, in catalog order.",
"items": {
- "type": "object",
- "required": ["name", "enabled", "executor", "bound", "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 }
- }
- }
- ]
- },
- "bound": {
- "description": "The executor a turn would bind now, by the same rule hop resolution uses: the chosen executor if verified, else the first verified candidate in Vibey's Source order; null when none is verified.",
- "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": {
+ "oneOf": [
+ { "$ref": "#/definitions/SearchTool" },
+ { "$ref": "#/definitions/ImageTool" }
+ ]
+ }
+ }
+ },
+ "definitions": {
+ "SourceId": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "Moment": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$" },
+ "Status": {
+ "type": "object",
+ "description": "Passive evidence for the tool. latest_ok is the latest real success (an in-memory projection, current even while file writes are throttled); refused lists the current refusals; verified lists the persisted successes, one per (Source, model), from which Source chips derive.",
+ "required": ["latest_ok", "refused", "verified"],
+ "additionalProperties": false,
+ "properties": {
+ "latest_ok": {
+ "oneOf": [
+ { "type": "null" },
+ {
"type": "object",
- "required": ["source_id", "model_id", "call", "replay", "billing", "price", "probe_estimate"],
+ "required": ["source_id", "model_id", "mode", "at"],
"additionalProperties": false,
"properties": {
- "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "source_id": { "$ref": "#/definitions/SourceId" },
"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" }]
- },
- "billing": { "enum": ["monthly", "metered"], "description": "The Source's billing: monthly shows \"included in subscription\", metered shows the list price \"at API price\"." },
- "price": {
- "description": "The overlay's list price for this tool on this provider, or null when no list price is known (never zero). OpenAI lists no per-image price, so image_generation has none.",
- "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ListPrice" }]
- },
- "probe_estimate": {
- "description": "What probing here is estimated to cost at most before it runs, in the shape of hosted_summary.cost: the call probe (its tool fee plus a nominal token estimate) and, for a tool with a replay aspect on a protocol that replays natively, the replay probe that may follow (tokens only). list, included on a monthly Source, or null when unknown (never zero), which is always so for image_generation (no list price).",
- "oneOf": [
- { "type": "null" },
- {
- "type": "object",
- "required": ["basis", "usd"],
- "additionalProperties": false,
- "properties": { "basis": { "const": "list" }, "usd": { "type": "number", "minimum": 0 } }
- },
- {
- "type": "object",
- "required": ["basis"],
- "additionalProperties": false,
- "properties": { "basis": { "const": "included" } }
- }
- ]
- }
+ "mode": { "enum": ["native", "executor", "direct"] },
+ "at": { "$ref": "#/definitions/Moment" }
}
}
+ ]
+ },
+ "refused": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["source_id", "model_id", "aspect", "at", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "$ref": "#/definitions/SourceId" },
+ "model_id": { "type": "string", "minLength": 1 },
+ "aspect": { "enum": ["call", "replay"] },
+ "at": { "$ref": "#/definitions/Moment" },
+ "reason": { "type": "string", "minLength": 1, "maxLength": 64, "description": "The record's detail: HTTP status and upstream machine code, never provider prose." }
+ }
+ }
+ },
+ "verified": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["source_id", "model_id", "mode", "at"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "$ref": "#/definitions/SourceId" },
+ "model_id": { "type": "string", "minLength": 1 },
+ "mode": { "enum": ["native", "executor", "direct"] },
+ "at": { "$ref": "#/definitions/Moment" }
+ }
}
}
}
},
- "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": {
"ListPrice": {
"type": "object",
+ "description": "An overlay list price for a hosted tool call, with its date and source.",
"required": ["unit", "usd_per_1k", "extra", "as_of", "url"],
"additionalProperties": false,
"properties": {
@@ -121,21 +94,104 @@
}
}
},
- "as_of": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
+ "as_of": { "type": "string", "format": "date" },
"url": { "type": "string", "pattern": "^https://" }
}
},
- "Evidence": {
+ "SearchTool": {
"type": "object",
- "required": ["status", "stale", "basis", "observed_at", "detail", "changes_at"],
+ "required": ["name", "enabled", "status", "executor_order", "effective_order", "executor_candidates"],
"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 },
- "changes_at": { "type": ["string", "null"], "description": "When this record stops reading as it does now: an observed record's expiry or a probe record's re-verify mark; null when nothing is scheduled." }
+ "name": { "enum": ["web_search", "x_search"] },
+ "enabled": { "type": "boolean" },
+ "status": { "$ref": "#/definitions/Status" },
+ "executor_order": {
+ "description": "The saved executor order, or null for automatic. Saved as given: an id that names no Source now is kept and skipped.",
+ "oneOf": [{ "type": "null" }, { "type": "array", "items": { "$ref": "#/definitions/SourceId" } }]
+ },
+ "effective_order": { "type": "array", "items": { "$ref": "#/definitions/SourceId" }, "description": "The order the executor chain would try now." },
+ "executor_candidates": {
+ "type": "array",
+ "description": "Every eligible executor Source for the tool, in effective order, with its vendor's executor model; a Claude subscription never is one.",
+ "items": {
+ "type": "object",
+ "required": ["source_id", "model_id", "billing", "relay", "price"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "$ref": "#/definitions/SourceId" },
+ "model_id": { "type": "string", "minLength": 1 },
+ "billing": { "enum": ["monthly", "metered"] },
+ "relay": { "type": "boolean", "description": "An API-key Source on an endpoint other than its vendor's own: its price is labelled \"at API price\"." },
+ "price": { "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ListPrice" }] }
+ }
+ }
+ }
+ }
+ },
+ "ImageTool": {
+ "type": "object",
+ "required": ["name", "enabled", "status", "default_model", "effective_default", "models", "image_offered_by"],
+ "additionalProperties": false,
+ "properties": {
+ "name": { "const": "image_generate" },
+ "enabled": { "type": "boolean" },
+ "status": { "$ref": "#/definitions/Status" },
+ "default_model": {
+ "description": "The saved default, or null for the catalog default. A saved model that is not available now (removed, or its pair refused) stays saved with available false.",
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["source_id", "model_id", "available"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "type": "string", "minLength": 1 },
+ "model_id": { "type": "string", "minLength": 1 },
+ "available": { "type": "boolean" }
+ }
+ }
+ ]
+ },
+ "effective_default": {
+ "description": "The default a turn would use now: the saved one if available, else the same model id on another Source, else the first available model in catalog order; null when no image model is available.",
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["source_id", "model_id"],
+ "additionalProperties": false,
+ "properties": { "source_id": { "$ref": "#/definitions/SourceId" }, "model_id": { "type": "string", "minLength": 1 } }
+ }
+ ]
+ },
+ "models": {
+ "type": "array",
+ "description": "Exactly the image_generate enum's candidate pairs, the default first; a refused pair is left out.",
+ "items": {
+ "type": "object",
+ "required": ["source_id", "model_id", "description", "price"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "$ref": "#/definitions/SourceId" },
+ "model_id": { "type": "string", "minLength": 1 },
+ "description": { "type": "string", "minLength": 1, "maxLength": 80 },
+ "price": {
+ "description": "One image: the vendor's list price, or an estimate from the image's tokens at the model's output rate; null when neither is known (shown as no unit price), never zero.",
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["usd", "basis"],
+ "additionalProperties": false,
+ "properties": { "usd": { "type": "number", "minimum": 0 }, "basis": { "enum": ["list", "estimated"] } }
+ }
+ ]
+ }
+ }
+ }
+ },
+ "image_offered_by": { "type": "array", "items": { "type": "string", "minLength": 1 }, "description": "The vendors of the user's Sources whose overlay lists image models, for the empty state." }
}
}
}
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index 93c014a8c..d9605d702 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": 14,
+ "contract_version": 15,
"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.json
index fa13cb029..719c6b727 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": 14 },
+ "contract_version": { "const": 15 },
"outcome": {
"enum": [
"observed",
@@ -150,7 +150,7 @@
],
"examples": [
{
- "contract_version": 14,
+ "contract_version": 15,
"outcome": "observed",
"reachable": true,
"authenticated": "authenticated",
@@ -165,7 +165,7 @@
]
},
{
- "contract_version": 14,
+ "contract_version": 15,
"outcome": "authentication_failed",
"reachable": true,
"authenticated": "rejected",
@@ -175,7 +175,7 @@
"model_metadata": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"outcome": "ambiguous",
"reachable": true,
"authenticated": "unknown",
@@ -185,7 +185,7 @@
"model_metadata": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"outcome": "unreachable",
"reachable": false,
"authenticated": "unknown",
@@ -195,7 +195,7 @@
"model_metadata": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"outcome": "adapter_error",
"reachable": null,
"authenticated": "unknown",
@@ -205,7 +205,7 @@
"model_metadata": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"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.json
index 525ef4bf6..57909469c 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": 14 },
+ "contract_version": { "const": 15 },
"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },
"channel": { "enum": ["hub", "native_cli"] },
"reachable": { "type": "boolean" },
@@ -66,10 +66,10 @@
}
],
"examples": [
- { "contract_version": 14, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
- { "contract_version": 14, "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": 14, "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": 14, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
- { "contract_version": 14, "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": 15, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
+ { "contract_version": 15, "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": 15, "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": 15, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
+ { "contract_version": 15, "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.json
index 133b42bb4..133b7167f 100644
--- a/docs/plans/model-hub-contracts/provider-overlay.schema.json
+++ b/docs/plans/model-hub-contracts/provider-overlay.schema.json
@@ -2,7 +2,7 @@
"$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.",
+ "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, the vendor's executor model and its image models. 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",
@@ -11,58 +11,125 @@
},
"PriceComponent": {
"type": "object",
- "required": ["unit", "usd_per_1k"],
+ "required": [
+ "unit",
+ "usd_per_1k"
+ ],
"additionalProperties": false,
"properties": {
- "unit": { "enum": ["call", "search", "post", "profile"] },
- "usd_per_1k": { "type": "number", "minimum": 0 }
+ "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"],
+ "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*)?$" },
+ "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" }
+ "items": {
+ "$ref": "#/definitions/PriceComponent"
+ }
+ }
+ }
+ },
+ "ImagePrice": {
+ "type": "object",
+ "description": "An image model's list price per 1,000 images, with the date and page it was read from.",
+ "required": [
+ "unit",
+ "usd_per_1k",
+ "as_of",
+ "url"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "unit": {
+ "const": "image"
+ },
+ "usd_per_1k": {
+ "$ref": "#/definitions/PriceComponent/properties/usd_per_1k"
+ },
+ "as_of": {
+ "$ref": "#/definitions/Price/properties/as_of"
+ },
+ "url": {
+ "$ref": "#/definitions/Price/properties/url"
}
}
},
"HostedTool": {
"type": "object",
- "required": ["declaration"],
+ "required": [
+ "declaration"
+ ],
"additionalProperties": false,
"properties": {
"declaration": {
"type": "object",
"description": "Sent verbatim as the native tool declaration.",
- "required": ["type"],
+ "required": [
+ "type"
+ ],
"properties": {
- "type": { "$ref": "#/definitions/Token" }
+ "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."
+ "description": "Absent when no list price is known, which is never a price of zero."
},
"include": {
"type": "array",
"description": "Responses include values the tool needs, e.g. web_search_call.action.sources.",
- "items": { "$ref": "#/definitions/Token" },
+ "items": {
+ "$ref": "#/definitions/Token"
+ },
"uniqueItems": true
}
}
},
"ModelFamily": {
"type": "object",
- "required": ["match"],
+ "required": [
+ "match"
+ ],
"additionalProperties": false,
"properties": {
"match": {
@@ -72,41 +139,181 @@
"maxProperties": 1,
"additionalProperties": false,
"properties": {
- "prefix": { "$ref": "#/definitions/Token" },
- "id": { "$ref": "#/definitions/Token" }
+ "prefix": {
+ "$ref": "#/definitions/Token"
+ },
+ "id": {
+ "$ref": "#/definitions/Token"
+ }
}
},
"wire_efforts": {
- "type": ["array", "null"],
+ "type": [
+ "array",
+ "null"
+ ],
"description": "Effort values the provider accepts on the wire. Null or absent defers to models.dev.",
- "items": { "$ref": "#/definitions/Token" },
+ "items": {
+ "$ref": "#/definitions/Token"
+ },
"uniqueItems": true
},
"hosted_tools": {
"type": "object",
- "propertyNames": { "$ref": "source.schema.json#/properties/protocol" },
+ "propertyNames": {
+ "$ref": "source.schema.json#/properties/protocol"
+ },
"additionalProperties": {
"type": "object",
- "propertyNames": { "enum": ["web_search", "x_search", "image_generation"] },
- "additionalProperties": { "$ref": "#/definitions/HostedTool" }
+ "propertyNames": {
+ "enum": [
+ "web_search",
+ "x_search"
+ ]
+ },
+ "additionalProperties": {
+ "$ref": "#/definitions/HostedTool"
+ }
}
}
}
},
"Vendor": {
"type": "object",
- "required": ["models"],
+ "required": [
+ "models"
+ ],
"additionalProperties": false,
"properties": {
"models": {
"type": "array",
"description": "Ordered; the first family that matches a model wins.",
- "items": { "$ref": "#/definitions/ModelFamily" }
+ "items": {
+ "$ref": "#/definitions/ModelFamily"
+ }
+ },
+ "executor_model": {
+ "$ref": "#/definitions/Token",
+ "description": "The vendor's lightweight model that runs proxied search calls on this vendor's Sources (vibey-hosted-tools.md §6). The executor call uses the declaration of the family row this id matches. A vendor without it is never an executor."
+ },
+ "image_models": {
+ "type": "array",
+ "description": "The image models this vendor offers to image_generate, in catalog order. Only models whose route the shipped engine was verified for are listed.",
+ "items": {
+ "$ref": "#/definitions/ImageModel"
+ }
+ }
+ }
+ },
+ "ImageModel": {
+ "type": "object",
+ "required": [
+ "id",
+ "description",
+ "endpoint",
+ "params",
+ "size_forms"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "$ref": "#/definitions/Token"
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 80,
+ "pattern": "^\\S(?:.*\\S)?$",
+ "description": "One short line; it goes into every request's tool block."
+ },
+ "endpoint": {
+ "enum": [
+ "images",
+ "chat_image"
+ ],
+ "description": "images: the engine's /v1/images/generations and /v1/images/edits; chat_image: the chat route with the image response modality."
+ },
+ "params": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "enum": [
+ "images",
+ "n",
+ "size"
+ ]
+ },
+ "description": "Which common image_generate parameters the model takes."
+ },
+ "size_forms": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "enum": [
+ "pixels",
+ "ratio"
+ ]
+ },
+ "description": "Which forms of size the model accepts; non-empty exactly when params lists size."
+ },
+ "prices": {
+ "type": "array",
+ "description": "Per-image list prices, each for the output size and quality it applies to (absent keys match any).",
+ "items": {
+ "type": "object",
+ "required": [
+ "price"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "price": {
+ "$ref": "#/definitions/ImagePrice"
+ },
+ "size": {
+ "$ref": "#/definitions/Token"
+ },
+ "quality": {
+ "$ref": "#/definitions/Token"
+ }
+ }
+ }
+ },
+ "tokens_per_image": {
+ "type": "integer",
+ "minimum": 1,
+ "description": "The documented output tokens of one image; the pricing module values it at the model's output rate as an estimate where no per-image price exists."
+ }
+ },
+ "if": {
+ "properties": {
+ "params": {
+ "contains": {
+ "const": "size"
+ }
+ }
+ }
+ },
+ "then": {
+ "properties": {
+ "size_forms": {
+ "minItems": 1
+ }
+ }
+ },
+ "else": {
+ "properties": {
+ "size_forms": {
+ "maxItems": 0
+ }
}
}
}
},
"type": "object",
- "propertyNames": { "pattern": "^[a-z0-9]+(?:[._-][a-z0-9]+)*$" },
- "additionalProperties": { "$ref": "#/definitions/Vendor" }
+ "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.json
index 0c0eff09b..d5c6a8218 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": 14 },
+ "contract_version": { "const": 15 },
"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": 14,
+ "contract_version": 15,
"host_platform": "darwin-arm64",
"manifest": {
"name": "cliproxyapi",
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 5344c7cbc..a9f24899f 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -451,14 +451,13 @@
"description": "Server-derived, read-only: the reasoning efforts this Source model currently refuses (capability evidence, model-hub-capability-model.md §3.4), the same shape as an AgentChain hop's. Absent when none. Returned on Source reads only; never persisted on the Source record and never accepted in a write.",
"items": {
"type": "object",
- "required": ["effort", "basis", "observed_at", "detail", "changes_at"],
+ "required": ["effort", "basis", "observed_at", "detail"],
"additionalProperties": false,
"properties": {
"effort": { "type": "string", "minLength": 1 },
- "basis": { "enum": ["probe", "observed"] },
+ "basis": { "const": "observed" },
"observed_at": { "type": "string", "format": "date-time" },
- "detail": { "type": ["string", "null"], "maxLength": 64 },
- "changes_at": { "type": ["string", "null"], "format": "date-time" }
+ "detail": { "type": ["string", "null"], "maxLength": 64 }
}
}
}
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index 5b8388c40..103762559 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, 12, 13, 14],
+ "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
"$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": 14,
+ "contract_version": 15,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -503,7 +503,7 @@
"blockers": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -524,7 +524,7 @@
"blockers": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -544,7 +544,7 @@
]
},
{
- "contract_version": 14,
+ "contract_version": 15,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
@@ -564,7 +564,7 @@
"blockers": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"turn_id": "turn_modelmissing01",
"ts": "2026-09-05T17:31:10Z",
"agent": "claude",
@@ -586,7 +586,7 @@
"blockers": []
},
{
- "contract_version": 14,
+ "contract_version": 15,
"turn_id": "turn_01k9x5ca",
"ts": "2026-07-29T07:08:00Z",
"agent": "codex",
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 34846142a..5e7feb7f4 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -133,11 +133,12 @@ The evidence store, its record and its owner are the capability model's §3. v2
- **A positive record carries the observed `mode`** (`native`, `executor` or `direct`) and is never retired by the
wire stamp: it is display-only history, so an upgrade does not hide it. The stamp retires `unsupported` records
only. A positive and a negative record for the same (Source, model, feature) coexist (the store keys by status
- too), so a later refusal never erases the success history the projection is seeded from after a restart.
- - **The latest execution is a projection, not a file write.** Model Hub keeps, per tool, the latest success
- (`{source_id, model_id, mode, at}`) in memory, updated on every success and seeded at startup from the persisted
- positive records. The read's `latest_ok` comes from it, so the status line is current even while file writes are
- throttled.
+ too), so a later refusal never erases the success history kept for a restart.
+ - **Memory is the one source of success history.** Every success updates its (Source, model, tool) record in
+ memory at once; the file takes it at most hourly per key and seeds memory at startup. `latest_ok` is the newest
+ of those records whose Source still has the identity it ran under, compared by time, so the status line is
+ current while file writes are throttled, and a Source that changes identity hands the line to the newest other
+ success rather than to an older file copy. There is no separate per-tool projection to drift from the records.
- Positive evidence never changes routing. It feeds the "最近一次 … 正常" lines (§8) and nothing else.
- A `google` hop has no native hosted tools, and the Chat route Vibey uses gives no hosted item to observe.
- **Negative (`unsupported`) is routing state.** When the file write fails, the narrow rule still updates the
@@ -168,15 +169,15 @@ The evidence store, its record and its owner are the capability model's §3. v2
efforts alike (capability model §3.2), has no time limit. It stays until
one of these clears it:
- the user clears it in Models → Tools, for one (Source, tool) or for every Source of a tool (§8.1);
- - its wire stamp no longer matches, which happens on its own when the Source's config or the engine release
- changes.
-
- Every record carries the wire stamp it was observed under, the engine release, the Avibe release (which covers
- the bundled overlay's declarations and the adapters' request shape), and a digest of the Source's rendered engine
- entry (credentials and the model list excluded), and a record whose stamp differs from the current one reads as
- unknown. The stamp is computed when the engine config is rendered (`sync_sources`) and
- held in memory per Source; evidence reads and writes take it from memory and never render on a request path, as
- `engine_stamp()` is never called on one. So a refusal learned under one engine or one rendered config cannot survive a
+ - its Source identity or wire stamp no longer matches, which happens on its own when the Source's config, the engine
+ release or the Avibe release changes.
+
+ With `source_identity`, every record carries the wire stamp it was observed under: the engine release, the Avibe
+ release (which covers the bundled overlay's declarations, the adapters' request shape and vendor-wide engine
+ flags), and the model's rendered fields the identity does not cover. A record whose identity or stamp differs from
+ the current one reads as unknown. Capability model §3.3 lists every renderer input and what covers it. The stamp is
+ computed from the config held in memory, never from the engine state on a request path, as `engine_stamp()` is
+ never called on one. So a refusal learned under one engine or one rendered config cannot survive a
change that could reverse it, such as the dependency lane's `is-compat` flip for xAI (#2620), which changes what
xAI receives for replayed reasoning. A change on the provider's side that the stamp cannot see (a relay that starts
supporting a tool) waits for the user's clear. A Source identity change drops the Source's evidence as before.
@@ -213,6 +214,10 @@ The evidence store, its record and its owner are the capability model's §3. v2
fields it knows. So an rc-era section keeps each tool's `enabled`, and a user's explicit opt-out survives the
upgrade; its `image_generation` key and v1's `executor` field are ignored. This is one generic loader rule, not
rc-specific code.
+ - A broken section (not an object) or entry (a value of the wrong type) turns its tools **off** with a warning:
+ hosted tools reach third parties and cost money, so damage never turns one on. Sources and Agents still load
+ (the persisted-shape rule in `AGENTS.md`). `executor_order` holds Source ids (`src_…`), and `default_model`
+ names one.
- A settings change applies from the next turn, as every runtime config change does.
- **API.** Saved and effective values are separate fields, and the UI never writes back an effective value: v1's
toggle echoed the resolved executor and so froze "automatic" into a saved choice.
@@ -224,9 +229,10 @@ The evidence store, its record and its owner are the capability model's §3. v2
upstream machine code, never provider prose); `verified[]` is `[{source_id, model_id, mode, at}]`, the persisted
positive records, one per pair, from which the Source chips derive (hosted evidence lives on this read, which
the clears answer; the Source read keeps effort evidence);
- - `latest_ok` is the in-memory latest-execution projection (§3.2), not the newest file record;
+ - `latest_ok` is the newest identity-valid success in memory (§3.2), not the newest file record;
- search tools: `executor_order` (saved, null when automatic), `effective_order` (as the gateway would try now),
- and `executor_candidates: [{source_id, billing, relay, price}]` in effective order (`relay` true for a Source on a
+ and `executor_candidates: [{source_id, model_id, billing, relay, price}]` in effective order (`model_id` the
+ vendor's executor model; `price` the overlay's list price with its units, or null) (`relay` true for a Source on a
non-official endpoint, labelled "at API price"), every eligible executor Source (a Claude
subscription never is) with its per-call price, so the order can be edited over the full list;
- `image_generate`: `default_model` (saved, null when default; a saved model no longer available, or whose pair
@@ -322,7 +328,8 @@ failover, and is refused unpinned (C-6 item 7). What changes is what happens aft
and native hosted payloads, since the refusal does not say which one failed. Once per (turn, identity); no
evidence is written (§3.2).
- **The cost is one cold prompt prefix.** Dropping a native declaration changes the tools block, so the resend and
- the next turns start a new cache prefix: once per (Source, tool), when the refusal is first learned, and again only
+ the next turns start a new cache prefix: once per (Source, model, tool), since evidence is per model (another
+ model of the same Source may run the tool), when the refusal is first learned, and again only
after the record is cleared (by the user or a stamp change) and the tool is tried natively once more. The upstream is not called twice
for nothing: a refusal before output costs no output tokens.
- **The gateway never rewrites hosted content.** Vibey renders every request from its canonical records; the gateway
@@ -489,8 +496,9 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `conver
returned, and the partial call is still metered on its Source. A completed response that never ran the tool
(the model chose not to; Anthropic is asked in the message alone) ends the chain with a `failed` record: it is
a model choice, not a Source failure, and moving on would double the cost. Any other outcome ends the chain.
- 5. With no candidate, or every candidate failed, the call returns a `failed` record naming what to add ("add an
- xAI Source to use X search").
+ 5. With no candidate, the call returns a `failed` record naming what to add ("add an xAI Source to use X search").
+ With candidates that were all tried and failed, it returns the last failure's reason and names the Sources
+ tried, so the user sees that retrying, or those Sources, is the issue.
- **One deadline for the whole chain**, the tool's call timeout (180 s for search), not one per candidate.
- Each candidate tried is metered on its own Source. The result's `execution` names the Source whose response the
record came from (the last one tried when all failed), with that attempt's `executor_billing` and `cost`; earlier
@@ -606,7 +614,9 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
offered and the UI never needs an "unverified" tag.
- **Authorized by the turn's enum.** The gateway resolves the Source from the turn's frozen `image_generate` enum
(§3.4): a model outside it is 409 `tool_not_enabled`, and the chosen (Source, model) is admitted on the final
- snapshot (`runs_on` and identity). So a caller cannot bill an image model or Source the turn was not offered.
+ snapshot (`runs_on`, identity, and no current refusal: a pair refused earlier in the turn fails locally with
+ `image_model_unavailable` while the declared enum stays frozen). So a caller cannot bill an image model or Source
+ the turn was not offered.
- **Bounds.** The endpoint's 1 MiB request bound becomes per tool: `image_generate` allows its reference images,
at most 4, each within `read`'s inline limit, plus 1 MiB; the size check stays before parsing and the JSON parse
stays off the loop. `n` is at most 4, and decoded bytes are capped per image and per call as the executor caps
@@ -634,10 +644,11 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
- en: "Tools Vibey can use in a conversation. Searches send the query to the vendor that runs them; if one fails,
the query may be retried with another of your Sources. Image prompts go to the image model's vendor. On metered
Sources each call is billed."
- - zh: "Vibey 在对话中可使用的工具。搜索会把查询发给执行它的厂商,失败时可能改由你的其他供应商重试;图片提示词会发给图片模型的厂商。按量计费的供应商每次调用都会计费。"
+ - zh: "Vibey 在对话中可使用的工具。搜索会把查询发给执行它的厂商,失败时可能改由你的其他供应商重试;图片提示词会发给图片模型的厂商。按量付费的供应商每次调用都会计费。" ("按量付费" is the Models vocabulary for metered billing.)
- **One status line per tool, from the read's `status` (§3.3), and only after something happened:**
- "最近一次由 <Source> 执行 · 正常 · 10-15" from `latest_ok`. It shows a date, not a time: positive records are
- written at most hourly (§3.2);
+ written at most hourly (§3.2). A call line that carries "已改用" stands in for it, since it already says where
+ the tool runs now;
- refusals come from `refused[]` grouped by aspect and then by `source_id` (the read stays per record), each group
with its newest `at` and its refused models, since evidence is per (Source, model) and the same Source may run
the tool on another model. Call refusals and replay refusals each get their own line under the rules below; a
@@ -647,7 +658,10 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
",已改用 <Source>" appended when that newest `at` is older than `latest_ok` and `latest_ok` is on another
Source, and has a "清除" action for that (Source, tool);
- **two or more Sources refused** (owner-approved mockup, 2026-10-15): the status line names the Sources
- ("A、B 不支持"), and the per-Source "清除" actions and "全部清除" sit in the card's **Advanced** section;
+ ("A、B 不支持", with ",已改用 <Source>" under the same rule taken over every group), and the clears sit in the
+ card's **Advanced** section, in a "各供应商状态" list: one row per (Source, model) with a record, a refusal over
+ a success as on the chips (§8.2), each refusal row with "清除" for that pair (`{source_id, model_id}`), and
+ "全部清除" for the tool (`{}`);
- the replay line reads "<Source> 不支持回放历史结果" (or "A、B 不支持回放历史结果"), since those Sources still run
the tool, and clears the same way;
- every clear uses the `clear` endpoint (§3.3). A cleared Source is tried natively again from its next request; if
@@ -656,10 +670,14 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
- **Search cards** show an optional **Advanced** section (which also holds the clear actions when two or more
Sources refused) with the executor order over `executor_candidates`: up/down
buttons (keyboard- and screen-reader-accessible, the route chain editor's pattern), each row with its Source's
- per-call price ("at API price" for a relay), collapsed and fully automatic until touched, with "Reset to
- automatic" (a `null` PUT). The price shows per row because it depends on who runs the search.
+ executor model and its unit rates as the overlay lists them ("$5 / 1k posts + $10 / 1k profiles", "at API price"
+ for a relay), never a single per-call figure where the count is unknown before the call, collapsed and fully automatic until touched, with "Reset to
+ automatic" (a `null` PUT). The price shows per row because it depends on who runs the search. A move
+ rearranges the shown executors within the saved order: an id the saved order names but the read does not show (a
+ refused or absent Source) keeps its place, and a shown executor the order lacks follows it.
- **The image card** lists the available image models with their one-line descriptions and a per-image price
- (owner-approved mockup): the vendor's list price where it has one (Grok Imagine "$0.02"); an estimate from token
+ (owner-approved mockup): the vendor's unqualified list price where it has one (Grok Imagine "$0.02"; a price for
+ one size or quality is not shown as every image's); an estimate from token
pricing, marked "≈", where the image's tokens are known: the pricing module values the overlay's
`tokens_per_image` at the model's output token rate (Nano Banana "≈$0.067"); "暂无单价" / "no unit price" where
neither is (gpt-image-2, which OpenAI prices per image token at a varying count). It has a default-model picker over `default_model` / `effective_default`; a saved default that is no longer available
@@ -675,10 +693,13 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no
Each model row on a Source's detail panel shows only passive state, with the detail popover (time, basis, reason).
There is no "via proxy" chip: proxying is the tool's business, not the Source's.
- "网页搜索 · 正常 · 10-15", "图片生成 · 正常": a positive chip, with no action;
-- "X 搜索 · 不支持", "图片生成 · 不支持", "网页搜索 · 不支持回放", "ultra · 不支持": a refusal chip, whose popover has
- "清除" (owner-approved mockup, 2026-10-15). A hosted-tool refusal chip clears both aspects of that tool for that
- model, through the Tools `clear` endpoint with its `source_id` and `model_id` (§3.3); an effort refusal through the Source evidence clear (capability model §5). After a clear the
- Sources and the hosted-tools read are both read again.
+- "X 搜索 · 不支持", "图片生成 · 不支持", "网页搜索 · 不支持回放", "ultra · 不支持": a refusal chip, which carries
+ "清除" as its own trailing segment (owner-approved mockup, 2026-10-15); its popover states the facts (time,
+ reason, how long it stays, the last success) and a hint, and holds no action. A hosted-tool refusal chip clears
+ both aspects of that tool for that model, through the Tools `clear` endpoint with its `source_id` and `model_id`
+ (§3.3); an effort refusal through the Source evidence clear (capability model §5). Each clear answers the read
+ that owns its evidence, so nothing else is read again: hosted evidence lives only on the hosted-tools read, which
+ the hosted clear answers, and effort evidence only on the Source, which the effort clear answers.
A model row shows one chip per feature: when a positive and a negative record coexist (§3.2), the refusal chip
wins, because it is routing state, and its popover may still name the last success ("曾于 10-15 正常"). A call
@@ -738,8 +759,9 @@ under the freeze protocol (`model-hub-contracts/README.md`).
"assumed" | "unsupported"}` for search tools (§3.4), and `image_generate: {models[{source_id, model_id,
description, params, size_forms}], default}`; `mode` and
`executor` are removed. `declaration` and `include` are present exactly when `native` is `assumed`.
-- Admission of a pinned request reads negative evidence only: a declared native tool needs `runs_on` and no current
- negative `call` evidence; a replayed item needs no current negative `replay` evidence.
+- Admission of a pinned request reads negative evidence only, through the hop's own facts (`hosted_tool_facts`): a
+ declared native tool needs `native` assumed and the overlay's declaration type; a replayed item needs `replay`
+ assumed, which a current `call` refusal withdraws as well as a `replay` one.
- The `pin_unavailable` envelope gains `reason` (§3.5).
- The executor body is `{"arguments"}` only; the gateway resolves the chain from the live turn (§6). The endpoint
keeps turn ownership; it authorizes each call against the turn's frozen tool set and, for `image_generate`, its
@@ -751,14 +773,15 @@ under the freeze protocol (`model-hub-contracts/README.md`).
`unsupported`; `shape` is removed and `engine` becomes `wire`, the stamp of §3.2; `feature.name` is `web_search`
| `x_search` | `image_generate`, and `image_generate` has `call` only.
- `hosted-tools-status.schema.json` is rewritten for §3.3's read: per tool `enabled` and `status {latest_ok,
- refused[]}`; search tools `executor_order`, `effective_order`, `executor_candidates[]`; `image_generate`
+ refused[], verified[]}`; search tools `executor_order`, `effective_order`, `executor_candidates[]`; `image_generate`
`default_model`, `effective_default`, `models[]`, `image_offered_by[]`. `reverify`, `executor`, `bound` and
`candidates[]` (with `call`, `replay`, `probe_estimate`) go. The PUT body is per field (§3.3).
- `hosted-tool-probe-result.schema.json` is deleted, with its `api-response.schema.json` branch and `api.md` row.
- `refused_efforts[].changes_at` (`agent-chain.schema.json`, `source.schema.json`) loses its meaning, since nothing
expires by age: it is removed with its UI expiry hint (`capability.expiryProbe` and the observed-expiry copy); the
hosted-tools read already drops it (§3.3).
-- `api.md` gains `POST /api/models/hosted-tools/<tool>/clear` (`{source_id?}` → the read, §3.3) and
+- `api.md` gains `POST /api/models/hosted-tools/<tool>/clear` (`{source_id?, model_id?}`, `model_id` only with
+ `source_id`, → the read, §3.3) and
`POST /api/models/sources/<source_id>/evidence/clear` (`{model_id, feature}` with an effort feature → the Source,
for an effort refusal; capability model §5), each with its `api-response.schema.json` branch.
- `provider-overlay.schema.json` gains `executor_model` per vendor and `image_models[]`.
@@ -778,7 +801,7 @@ under the freeze protocol (`model-hub-contracts/README.md`).
| Model Hub | `core/handlers/model_hub/hosted_probe.py`; `ModelHubService.probe_hosted_tool`, `_record_probe_evidence`, `_probe_estimate`, `_probe_rejection`, `_probe_aspect`; the RPC and UI-server routes for `POST /api/models/hosted-tools/<tool>/probe`; `MODEL_HUB_RPC_TIMEOUT_SECONDS`' probe dependency (it moves back to `vibe/model_hub_client.py`); `HOSTED_PROBE_SHAPE` and every `shape` parameter; the evidence `probe` basis and probe staleness; `engine_stamp()`'s `hosted_wire` branch (#2623); the per-turn executor binding and `_executor`; `UserTestCall`'s probe-only callers |
| Gateway | `stream_wire`'s `response.image_generation_call.partial_image` model-output envelope; the executor's native image path (`ResponsesStreamReader(partial_images=…)`, the 32 MiB image line cap, the image event and byte budget, `_image_result`, the `_IMAGE_*` constants, the 300 s image `call_timeout`), replaced by what the images endpoint needs; the OpenAI `image_generation` overlay declaration (#2580's JPEG q90 becomes the images-endpoint request parameters); `executor` in the proxy body; `executor_request`'s image branch (its `include`/`partial_images` read of the overlay image declaration); the `hosted_executor_bindings` / `turn_hosted_executors` plumbing, replaced by the turn's frozen `hosted_tools` (§6); the `hosted_tools_status` candidates and bound-executor projection. `_own_turn_call` stays. Kept: `disable-image-generation: passthrough`; `hosted_admission`'s "image calls are never replayed" rule until no transcript can carry a native image call; #2616's per-turn identity binding and #2586's turn id. |
| Vibey | the native `image_generation` declaration, its parsing (`responses_hosted_tool`'s `image_generation_call` mapping, `image=`/`image_error=` in `responses_hosted_block`), `_ImageBudget`, `_saved_image`, `_PARTIAL_IMAGE_EVENT`, `IMAGE_STREAM_LINE_BYTES`, the large-event JSON offload, `drive_sse_stream`'s `max_line_size` and `iter_sse_events`' offload (every stream returns to 8 MiB); `ModelRequest.tool_choice` and `_common.forced_tool`; `registry.build_wire_request` (its tests move to each adapter's `wire_request`); the adapters' probe-only `media_sink` parameter and the `media_sink` argument of `registry_providers(media_loader=…, media_sink=…)`; `HostedTool`'s `executor` field and its `executor` body; the agent's `_with_hosted_images` / `_emit_orphan_images` path for native images (`agent.py`), kept for `image_generate` results. `HostedRecord.images`, `HostedImage`, `generate_action` and the `generate` action stay, on `ToolResultMessage.hosted` only. |
-| UI | `ProbeAnswerNote.tsx` (with `ReplayNote`); in `ToolsTab.tsx` `ProbeCell`, the executor picker and its notes, the `needsCheck`/`needsExecutor` states, the "unchecked" chip and the probe column; in `HostedCapabilityChips.tsx` the recheck action, the recheck-only keyboard path (every chip keeps its keyboard path into the detail), and the reverify, engineUpgraded and unsupportedAged states; `useEstimateLabel.ts`; the `probeHostedTool` wiring in `SettingsModelsPage.tsx`, whose Sources re-read after a probe moves to after a clear (the Source chips show the same refusals); in `useHostedTools` `probe`, `probing`, `lostProbeOutcome`, `recordedOutcome` and `PROBE_NOT_RECORDED` (the serialized writes, identity fencing and re-read after Source mutations stay); in `hostedTools.ts` `ProbeTarget`, `probeKey`, `probeUnanswered`, `verifiedCandidates`, `sameExecutor` and the `aged`/`engineUpgraded` branches of `evidenceChip`; `modelsApi.probeHostedTool`; the types `HostedToolProbeResult`, `HostedProbeAspect`, `HostedCostEstimate`, `probe_estimate`, `HostedToolCandidate`, `bound`, and `executor` in `HostedToolPut`. Rebuilt on the new read rather than only trimmed: `modelCapabilities` and the Tools-tab rows on `status`; `cost.imageTokens` ("no per-image price yet") by per-image prices; `capability.chip.viaProxy` and `explain.viaProxy` go with the "via proxy" chip. Check-all is removed by the UI lane's pending PR. |
+| UI | `ProbeAnswerNote.tsx` (with `ReplayNote`); in `ToolsTab.tsx` `ProbeCell`, the executor picker and its notes, the `needsCheck`/`needsExecutor` states, the "unchecked" chip and the probe column; in `HostedCapabilityChips.tsx` the recheck action, the recheck-only keyboard path (every chip keeps its keyboard path into the detail), and the reverify, engineUpgraded and unsupportedAged states; `useEstimateLabel.ts`; the `probeHostedTool` wiring in `SettingsModelsPage.tsx` and its Sources re-read after a probe (no clear needs one: §8.2); in `useHostedTools` `probe`, `probing`, `lostProbeOutcome`, `recordedOutcome` and `PROBE_NOT_RECORDED` (the serialized writes, identity fencing and re-read after Source mutations stay); in `hostedTools.ts` `ProbeTarget`, `probeKey`, `probeUnanswered`, `verifiedCandidates`, `sameExecutor` and the `aged`/`engineUpgraded` branches of `evidenceChip`; `modelsApi.probeHostedTool`; the types `HostedToolProbeResult`, `HostedProbeAspect`, `HostedCostEstimate`, `probe_estimate`, `HostedToolCandidate`, `bound`, and `executor` in `HostedToolPut`. Rebuilt on the new read rather than only trimmed: `modelCapabilities` and the Tools-tab rows on `status`; `cost.imageTokens` ("no per-image price yet") by per-image prices; `capability.chip.viaProxy` and `explain.viaProxy` go with the "via proxy" chip. Check-all is removed by the UI lane's pending PR. |
| i18n (`settings.models`) | `tools.probe.*`; `tools.state.needsCheck` and `needsExecutor`; `tools.executor.*`; `tools.chip.unchecked`, `reverify`, `engineUpgraded`, `unsupportedAged`; `tools.reverify.*`; `capability.recheck`, `recheckCost`; `capability.chip.*` and `capability.explain.*` for reverify, engineUpgraded, viaProxy, viaProxyAged and unsupportedAged; `capability.expiryProbe`; `tools.col.*` and `tools.chip.native`/`unsupported`/`executor` (the candidate table goes). Rewritten: `tools.subtitle` (§8.1), `tools.empty` and `tools.noNative` against the new read; `tools.footnote` keeps its relay and subscription sentences. |
| Tests and scenarios | `tests/test_model_hub_hosted_probe.py`; the probe and executor-binding cases in `test_model_hub_hosted_tools_resolution.py`, `test_model_hub_hosted_executor.py`, `test_model_hub_hosted_pinning.py` and `test_model_hub_evidence_rules.py`; the native image cases in the Responses adapter tests; UI `ToolsTab.test` MH-HOSTED-UI-013 and 019, the executor cases of 001 and the probe parts of 003 and 018, `useHostedTools.test` 013 and parts of 007, `hostedTools.test` 013, `SourceDetailPanel.test` 013 and 017, `SettingsModelsPage.render` 016; catalog rows MH-HOSTED-007 (probe), UI-004 (the engine-upgraded and aged header), UI-013, UI-016 and UI-019 retire; UI-002 shrinks to the passive states; UI-018's "locked until verified" becomes "on by default, nothing locks"; UI-001's write contract becomes the per-field PUT |
| Contracts | as §10 |
@@ -849,7 +872,7 @@ and no real credentials.
1. **Silent drops are invisible.** A Source that accepts a native declaration but never runs the tool looks like a
model that chose not to search, and one that accepts a replayed payload but drops it loses the results' page
content. Passive learning cannot see either. The status line simply never shows that Source executing.
-2. **The first refusal costs one request and one cold prefix** per (Source, tool), and again after the record is
+2. **The first refusal costs one request and one cold prefix** per (Source, model, tool), and again after the record is
cleared (§3.5).
3. **A refusal stays until cleared.** A relay that later starts supporting a tool or an effort keeps getting the
proxy function, or keeps being skipped at that effort, until the user clears the refusal, or its config or the
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index 714544939..f2e364650 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": 14,
+ "contract_version": 15,
"error": "feature_disabled",
}
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index 0f3fca087..dbc771f04 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 MockLLMUpstream
pytestmark = pytest.mark.e2e_model_hub
-CONTRACT_VERSION = 14
+CONTRACT_VERSION = 15
MENU_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.yaml
index 7d621d277..6ad4a29c9 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -52,7 +52,6 @@ capabilities:
- 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_hosted_probe.py
- tests/test_model_hub_capability_evidence.py
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 1eec39642..a1f2f5d72 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -8,7 +8,6 @@ capability:
- tests/test_model_hub_hosted_pinning.py
- tests/test_model_hub_hosted_tools_resolution.py
- tests/test_model_hub_hosted_tools_config.py
- - tests/test_model_hub_hosted_probe.py
- tests/test_model_hub_capability_evidence.py
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
@@ -167,47 +166,62 @@ scenarios:
layer: contract
test: 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
+ name: A Vibey hop's hosted tools come from the overlay's priors and current refusals, with no probe; proxied search runs on an executor chain and image_generate names its model from a deterministic enum
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
+ - tests/test_model_hub_hosted_tools_resolution.py::test_a_hops_facts_come_from_priors_and_refusals
+ - tests/test_model_hub_hosted_tools_resolution.py::test_the_executor_chain_follows_the_users_order_then_vibeys
+ - tests/test_model_hub_hosted_tools_resolution.py::test_the_image_enum_is_deterministic_with_the_default_first
+ - tests/test_model_hub_hosted_tools_resolution.py::test_resolution_states_v2_facts_in_todays_hop_shape
- id: MH-HOSTED-002
- name: A broken hosted-tools config entry turns off only its tool, without the whole-section Model Hub reset
+ name: Absent hosted-tools config means every tool is on; an rc-era section keeps each tool's enabled, and a broken section or entry turns only its tools off 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
+ test: tests/test_model_hub_hosted_tools_config.py::test_a_broken_hosted_tool_entry_turns_off_only_its_tool
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
+ - tests/test_model_hub_hosted_tools_config.py::test_released_configs_load_with_every_tool_on_and_stay_without_the_section
+ - tests/test_model_hub_hosted_tools_config.py::test_hosted_tool_settings_round_trip_in_canonical_order
- id: MH-HOSTED-003
- name: Capability evidence resolves for routing; hosted-tool evidence from another engine or probe shape is unknown
+ name: A refusal is routing state with no time limit that applies only under its Source identity and wire stamp; a success is display history that never replaces it; a clear is persisted before it takes effect
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_hosted_evidence_is_stamped_with_the_engines_hosted_wire
+ test: tests/test_model_hub_capability_evidence.py::test_a_refusal_holds_until_the_wire_or_the_source_changes
+ related_tests:
+ - tests/test_model_hub_capability_evidence.py::test_a_success_never_replaces_a_refusal_and_never_routes
+ - tests/test_model_hub_capability_evidence.py::test_successes_reach_memory_at_once_and_the_file_at_most_hourly
+ - tests/test_model_hub_capability_evidence.py::test_the_newest_success_is_kept_whatever_order_settlements_land_in
+ - tests/test_model_hub_capability_evidence.py::test_the_newest_refusal_is_kept_whatever_order_settlements_land_in
+ - tests/test_model_hub_capability_evidence.py::test_a_refusal_holds_in_memory_when_its_write_fails
+ - tests/test_model_hub_capability_evidence.py::test_a_clear_is_persisted_before_it_takes_effect
+ - tests/test_model_hub_capability_evidence.py::test_a_changed_source_identity_is_pruned_at_the_next_write
- tests/test_model_hub_capability_evidence.py::test_a_released_sources_identity_digest_is_unchanged
+ - tests/test_model_hub_capability_evidence.py::test_persisted_records_match_the_schema_and_rc_era_ones_are_pruned
- tests/test_model_hub_unverified.py::test_a_verified_reauthentication_never_returns_the_source_to_its_earlier_identity
- - tests/test_model_hub_capability_evidence.py::test_persisted_records_match_the_schema_and_unreadable_ones_are_unknown
+ - tests/test_model_hub_hosted_tools_config.py::test_a_clear_removes_only_the_refusals_it_names
+ - tests/test_model_hub_hosted_tools_config.py::test_a_clear_that_cannot_be_saved_changes_nothing
- 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
+ name: The Tools API reads each tool's saved and effective settings and what real use showed, and writes one field of one tool 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
+ test: tests/test_model_hub_hosted_tools_config.py::test_the_tools_api_writes_one_field_of_one_tool_at_a_time
+ related_tests:
+ - tests/test_model_hub_hosted_tools_config.py::test_an_image_models_card_price_is_only_an_unqualified_list_price
+ - tests/test_model_hub_hosted_tools_resolution.py::test_a_relay_is_any_endpoint_but_the_vendors_own_by_the_engines_endpoint_identity
+ - tests/test_model_hub_hosted_tools_resolution.py::test_the_tools_read_states_saved_and_effective_values_and_what_real_use_showed
+ - tests/test_model_hub_hosted_tools_resolution.py::test_a_put_changes_only_the_fields_it_names
+ - tests/test_model_hub_hosted_tools_resolution.py::test_a_put_refuses_what_the_contract_forbids
+ - tests/test_model_hub_hosted_tools_resolution.py::test_the_latest_success_is_the_newest_in_time_not_in_text
+ - tests/test_model_hub_hosted_tools_resolution.py::test_the_latest_success_is_the_newest_one_whose_source_is_still_the_same
- id: MH-HOSTED-005
- name: The bundled provider overlay resolves hosted-tool declarations, includes and prices; a broken vendor entry disables only that vendor
+ name: The bundled provider overlay resolves search-tool declarations, includes and prices, each vendor's executor model and its image models; a broken vendor entry disables only that vendor
status: covered
kind: compatibility
layer: contract
@@ -215,6 +229,8 @@ scenarios:
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
+ - tests/test_provider_overlay.py::test_an_image_model_entry_is_read_in_a_stable_form
+ - tests/test_provider_overlay.py::test_each_vendors_executor_model_runs_every_search_tool_the_vendor_offers
- id: MH-HOSTED-UI-008
name: The execution-process group draws a native and a proxied hosted call as one card, with how it ran, its known cost and its sources or image
status: covered
@@ -322,32 +338,6 @@ scenarios:
- tests/test_model_hub_reasoning_tiers.py::test_the_hop_declares_exactly_its_models_levels
- tests/test_model_hub_reasoning_tiers.py::test_rows_saved_by_3_2_0_are_derived_again_once_at_startup
- tests/test_model_hub_evidence_rules.py::test_the_picker_menu_states_which_efforts_routing_refuses_in_menu_values
- - id: MH-HOSTED-007
- name: A user-started probe sends Vibey's native request pinned to the probed Source, follows a verified call with the replay probe, and records only a result, a refusal naming the tool or its replayed content, or a new call
- status: covered
- kind: contract
- layer: contract
- test: tests/test_model_hub_hosted_probe.py::test_a_call_probe_sends_the_production_request_and_records_only_what_it_shows
- related_tests:
- - tests/test_model_hub_hosted_probe.py::test_a_probe_runs_only_on_a_target_the_tool_can_run_on
- - tests/test_model_hub_hosted_probe.py::test_each_candidate_states_what_probing_it_would_cost
- - tests/test_model_hub_hosted_probe.py::test_each_request_the_adapter_sends_is_its_own_pinned_call
- - tests/test_model_hub_hosted_probe.py::test_a_probe_that_verifies_its_source_records_evidence_for_the_source_as_it_now_is
- - tests/test_model_hub_hosted_probe.py::test_a_probe_records_no_evidence_for_a_source_reauthenticated_mid_probe
- - tests/test_model_hub_hosted_probe.py::test_the_probe_reads_its_calls_in_the_order_the_adapter_sent_them
- - tests/test_model_hub_hosted_probe.py::test_the_probe_asks_for_no_more_output_than_a_turn_on_its_hop_would
- - tests/test_model_hub_hosted_probe.py::test_an_api_key_source_is_probed_on_a_passthrough_model_it_does_not_list
- - tests/test_model_hub_hosted_probe.py::test_a_probe_that_times_out_before_its_handle_is_still_metered
- - tests/test_model_hub_hosted_probe.py::test_a_deadline_mid_stream_ends_the_probe_as_transient
- - tests/test_model_hub_hosted_probe.py::test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_open
- - tests/test_model_hub_hosted_probe.py::test_an_image_probe_verifies_only_an_image_vibey_could_keep
- - tests/test_model_hub_hosted_probe.py::test_a_verified_call_is_followed_by_the_replay_probe
- - tests/test_model_hub_hosted_probe.py::test_a_replay_sends_the_results_only_in_their_native_payload
- - tests/test_model_hub_hosted_probe.py::test_a_replay_goes_only_to_the_source_identity_the_call_was_recorded_for
- - tests/test_model_hub_hosted_probe.py::test_a_re_probe_restores_replay_a_narrow_rule_demoted
- - tests/test_model_hub_hosted_probe.py::test_a_replay_answer_counts_only_when_it_completed_and_names_a_hidden_result
- - tests/test_model_hub_hosted_probe.py::test_a_replay_answer_names_a_result_by_its_exact_url
- - tests/test_model_hub_hosted_probe.py::test_a_result_the_answer_shows_in_any_reading_is_not_hidden
- id: MH-HOSTED-VIBEY-002
name: Every native hosted item becomes one hosted call with a provider-neutral action and its record; citations stay on the text that cites them; the response's counters and reported cost go to its summary
status: covered
@@ -416,64 +406,56 @@ scenarios:
- tests/test_vibey_agent.py::test_a_proxied_image_that_was_not_saved_is_a_failed_call_with_its_code
- tests/test_agent_transcript.py::test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans
- id: MH-HOSTED-UI-001
- name: A Tools-tab toggle or executor pick writes the tool's whole setting with an executor the server accepts; the picker offers only verified pairs
+ name: A Tools-tab control writes only the field it changes, and a tool's controls hold while its write is out
status: covered
kind: contract
layer: unit
test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: a toggle replaces the whole setting and keeps the saved executor'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: writes a saved executor back only while the server would still accept it'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: the executor picker offers only verified pairs, and a pick keeps the toggle'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: a saved executor that is no longer verified stays visible as itself'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: keeps a saved executor visible as itself when nothing is verified any more'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: holds a tool''s controls while its write is in flight'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: a switch writes only whether the tool is on'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: holds a tool''s controls while its write is out, and leaves other tools free'
- id: MH-HOSTED-UI-002
- name: Every hosted-tool evidence shape maps to the chip it owes the user, including wire-stale records that route as unknown
+ name: 'A tool''s status lines come from real use only: nothing before first use, the latest run by date, refusals grouped by aspect and Source, and where the tool runs now only after a later success elsewhere'
status: covered
kind: observation
layer: unit
test:
- - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: gives every evidence shape the chip it owes the user'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-002: says nothing about a tool before its first use'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-002: names who ran the tool last, with the date only'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: groups refusals by aspect and Source, with each group''s models and newest time'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: leaves a Source that refused the call out of the replay line, so it counts once'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: says where the tool runs now only after a later success on another Source'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: says where the tool runs now only after no success since'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: says where the tool runs now only after the success is on the refusing Source'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: says where the tool runs now only after no success at all'
- id: MH-HOSTED-UI-003
- name: The Tools tab states a cost only where one is known; an image is never priced and unknown is never shown as zero
+ name: The Tools tab states a cost only where one is known; a subscription is included, and unknown is never shown as zero
status: covered
kind: observation
layer: unit
test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: states a cost only where one is known, and never prices an image'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: the image cost copy is the orchestrator-decided Chinese line'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: lets the locale compose a price with its extras'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: says a check''s cost is unknown before it runs, when no estimate is known'
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-003: says a re-check''s cost is unknown when no estimate is known'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: prices each executor where a price is known, and never shows unknown as zero'
- 'ui/src/components/settings/models/format.test.ts::MH-HOSTED-UI-003: keeps the first significant digits of a per-call price, and never shows a nonzero price as zero'
- - id: MH-HOSTED-UI-004
- name: The Tools tab says how many checks an engine upgrade made stale, and nothing when none did
- status: covered
- kind: observation
- layer: unit
- test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-004: says how many checks an engine upgrade made stale, and nothing when none did'
- id: MH-HOSTED-UI-005
- name: The hosted-tools report stays unread until the Tools tab opens, then re-reads on every open
+ name: The hosted-tools report stays unread until the Tools tab opens, re-reads on every open, and again after a committed Source change
status: covered
kind: observation
layer: unit
test:
- 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-005: leaves the hosted-tools report unread until its tab opens, then re-reads on every open'
+ - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-005: reads the hosted-tools report again after a committed Source change, since a Source change can drop its evidence'
- id: MH-HOSTED-UI-006
- name: A Source model shows one chip per tool with evidence; a refused tool reads via proxy only while the server binds one for it, and unchecked draws nothing
+ name: A Source model shows one chip per feature with a record, a refusal over a success, and an unused model draws nothing
status: covered
kind: observation
layer: unit
test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-006: names the Sources that have no native pair for a tool'
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: draws evidence per model, and says "via proxy" only while a proxy is bound for the tool'
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: draws a chip for each reasoning effort the Source refused, even with no tool evidence'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: draws one chip per feature with a record, a refusal over a success, and nothing for an unused model'
- 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: says when the capability read failed instead of drawing a Source with no evidence'
- 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: adds no capability column when no model has evidence'
- - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-006: gives a Source model one capability per tool with evidence, in catalog order'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-006: gives each pair one record, a refusal over a success and a call refusal over a replay one'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-006: gives a Source model one capability per tool with a record, in catalog order'
- id: MH-HOSTED-UI-007
- name: Hosted-tool writes run one at a time and a read never overlaps one, so the screen holds the newest committed state
+ name: Hosted-tool writes and clears run one at a time and a read never overlaps one, so the screen holds the newest committed state
status: covered
kind: concurrency
layer: unit
@@ -483,56 +465,52 @@ scenarios:
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: drops a read that was already out when a write started'
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: re-reads after the newest write fails, because a lost answer may have committed'
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: re-reads when the open Source changes, since an edit can drop its evidence'
- - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps the status a probe answered with when the read after it fails'
- - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: lands the status read for a lost probe answer, even when the read after it fails'
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: shows no status of the previous Source identity while the new identity''s read fails'
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps a tool pending until the read reconciling its lost write lands'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps a tool pending while the read reconciling its lost write fails, until a read lands'
- 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: drops a write answer asked under another Source identity'
- - id: MH-HOSTED-UI-013
- name: A hosted-tool check runs only on the user's ask, one pair at a time, with its estimated cost shown first, and an answer that is not evidence reads as not verified with a retry
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps a tool pending until every write queued for it has settled'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: queues a clear behind a write like any write, so its answer lands last'
+ - id: MH-HOSTED-UI-018
+ name: Every hosted tool is on by default under its capability group, and nothing locks its switch
status: covered
kind: contract
layer: unit
test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: checks one row with its cost on the button, and says when the answer was not evidence'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: offers a check one pair at a time, never all pairs at once'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: says why a failed check failed, and never shows the server''s key as text'
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-013: checks a tool again from its chip, with the cost on the action, and answers there when the check is not evidence'
- - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-013: reads the record before calling a probe unanswered when its answer was lost'
- - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-013: reads a verdict the status does not carry as not verified, with why'
- - id: MH-HOSTED-UI-016
- name: A hosted-tool check is a real call on exactly one Source, so the Models page reads its Sources again after one, and a Source the probe verified shows as verified
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: shows every tool on by default under its capability, and never locks a switch'
+ - id: MH-HOSTED-UI-017
+ name: A Source's capability chip is usable without a mouse. Its spoken name is the locale's composition of the label, explanation and facts, and every chip opens its detail from the keyboard
status: covered
kind: contract
layer: unit
test:
- - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-016: reads the hosted-tools report again after a committed Source change, since its models decide which pairs could run a tool'
- - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-016: reads the Sources again after a check, since a probe can verify its Source'
- - id: MH-HOSTED-UI-018
- name: The Tools tab never enables a tool that cannot run. It stays off until the server binds an executor, says whether a check or an executor pick is missing, and an enabled tool with nothing verified says its calls fail
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: names the record time, the reason, how long it stays, and the last success'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: opens any chip''s detail from the keyboard, a success''s included'
+ - id: MH-HOSTED-UI-020
+ name: Every refusal can be cleared where it is named. One refusing Source clears on its status line; with two or more the clears and Clear all sit in Advanced; a Source chip clears its own model; an effort chip clears through the Source evidence clear
status: covered
kind: contract
layer: unit
test:
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: cannot turn a tool on until a pair is verified to run it, but can always turn it off'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: keeps a tool off while the server binds no executor for it, and says to choose one when a verified pair exists'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: claims routing only while the tool is on, and shows an off tool''s executor as a saved preference'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: keeps an image tool off until a check verifies one of its pairs, and offers that check'
- - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: says an enabled tool with nothing verified fails its calls, instead of naming a proxy'
- - id: MH-HOSTED-UI-017
- name: A Source's capability chip is usable without a mouse. Its spoken name is the locale's composition of the label, explanation and facts, it announces the detail it opens, and Enter moves focus to the detail's paid re-check
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-020: one refusing Source: its line names the models and where the tool runs now, and clears that Source'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-020: two refusing Sources: the line names them, and the clears and Clear all sit in Advanced'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-020: a replay refusal has its own line, and a Source that refused the call is not in it'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-020: an image refusal reads and clears like a search refusal, and two move into Advanced'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-020: clears a tool refusal for its own model only'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-020: clears a refused effort and shows the Source the clear answered'
+ - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-020: clears a refusal from its Source chip and shows the status the clear answered'
+ - id: MH-HOSTED-UI-021
+ name: A search tool's executor order lists every eligible executor in effective order; a move rearranges the shown executors within the saved order and keeps hidden ones, Reset saves automatic, and a move is announced and followed by focus only once the server order shows it
status: covered
kind: contract
layer: unit
test:
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: names the record time, how it was learned, the reason, and until when it holds'
- - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: moves keyboard focus into the detail on Enter, so its paid re-check can be reached'
- - id: MH-HOSTED-UI-019
- name: A check's replay step reads as its own result. A replay that ran and did not verify asks for another try (or says the Source does not support it), and no replay says nothing; neither reads as the call failing
- status: covered
- kind: observation
- layer: unit
- test: ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-019
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-021: lists the executors in effective order, and a move saves the whole shown order'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-021: a move keeps a saved executor the read does not show'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-021: moves only the shown executors within the saved order, keeping hidden ones in place'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-021: a customized order offers Reset, which saves automatic'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-021: announces a move and moves focus only once the server order shows it, and drops one that did not land'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-021: keeps focus on the moved row once the answer lands, on its other arrow at an end'
- id: MH-VIBEY-007
name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source exists
status: covered
@@ -556,6 +534,7 @@ scenarios:
related_tests:
- tests/test_model_hub_hosted_pinning.py::test_the_portable_resend_fails_over_and_the_turn_settles_on_it
- tests/test_model_hub_hosted_pinning.py::test_unpinned_hosted_content_is_refused_before_anything_runs
+ - tests/test_model_hub_hosted_pinning.py::test_a_replay_is_admitted_exactly_where_the_hops_facts_assume_it
- id: MH-HOSTED-GATEWAY-003
name: Hosted declarations are recognized by any vendor's type, and only replayed items outside the in-flight response need replay evidence
status: covered
@@ -2475,7 +2454,6 @@ scenarios:
test: tests/test_model_hub_hosted_executor.py::test_a_proxied_search_runs_one_native_request_and_answers_its_canonical_record
related_tests:
- tests/test_model_hub_hosted_executor.py::test_an_anthropic_executor_is_buffered_and_keeps_the_providers_results_and_cited_text
- - tests/test_model_hub_hosted_executor.py::test_a_proxied_image_returns_its_bytes_once_for_vibey_to_save
- tests/test_model_hub_hosted_executor.py::test_an_excerpt_is_the_answer_text_its_citation_belongs_to
- tests/test_model_hub_hosted_executor.py::test_a_proxied_call_carries_the_pricing_modules_cost
- id: MH-HOSTED-GATEWAY-005
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index e154f9c65..f4a21d497 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) == 288
+ assert len(endpoints) == 289
assert ("GET", "/api/sessions/main") in endpoints
assert http_authorization_policy("POST", "/api/vault/requests/{request_id}/approve-delete").minimum_role == "editor"
for method in ("PUT", "DELETE"):
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 4c9ae0d56..731b58dfa 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 == 1
assert store.config.enabled is True
assert runtime["enabled"] is True
- assert runtime["contract_version"] == 14
+ assert runtime["contract_version"] == 15
assert 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": 14, "status": {"health": "ok"}}
+ return {"contract_version": 15, "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": 14, "status": {"health": "not_started"}}
+ return {"contract_version": 15, "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": 14, "status": {"health": "installing"}}
+ return {"contract_version": 15, "status": {"health": "installing"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1390,7 +1390,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypat
def rpc(operation, payload=None):
calls.append((operation, payload))
return {
- "contract_version": 14,
+ "contract_version": 15,
"changed": True,
"status": {"health": "not_started", "verified": True},
}
@@ -4810,7 +4810,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):
assert response.status_code == 200
assert response.get_json() == {
"ok": True,
- "contract_version": 14,
+ "contract_version": 15,
"agent": {
"backend": "codex",
"mode": "hub",
@@ -9678,7 +9678,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t
assert accepted.status_code == 200
runtime = accepted.get_json()["runtime"]
assert adapter.start_calls == 1
- assert runtime["contract_version"] == 14
+ assert runtime["contract_version"] == 15
_assert_valid("runtime-dependency.schema.json", runtime)
diff --git a/tests/test_model_hub_capability_evidence.py b/tests/test_model_hub_capability_evidence.py
index f6bd5d1e9..838e0083a 100644
--- a/tests/test_model_hub_capability_evidence.py
+++ b/tests/test_model_hub_capability_evidence.py
@@ -1,12 +1,14 @@
-"""Capability evidence store (``model-hub-capability-model.md`` §3, jsH stale rule).
+"""Capability evidence store (``model-hub-capability-model.md`` §3; ``vibey-hosted-tools.md`` §3.2).
-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.
+Evidence is passive: a refusal is routing state with no time limit, a success is
+display history. These tests pin how each is kept, read and cleared at the
+store, the owning boundary.
"""
from __future__ import annotations
import json
+import logging
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -17,17 +19,17 @@ from referencing import Registry, Resource
from config.v2_config import ModelHubModelConfig, ModelHubSourceConfig, ModelHubSourceStateConfig
from core.handlers.model_hub.capability_evidence import (
- UNKNOWN_ENGINE_STAMP,
CapabilityEvidenceStore,
EvidenceFeature,
EvidenceRecord,
identity_digest,
- resolve,
+ wire_stamp,
)
CONTRACTS = Path(__file__).parents[1] / "docs/plans/model-hub-contracts"
-NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
+NOW = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)
ENGINE = "model-hub-engine-v8.0.23-3"
+AVIBE = "3.2.1"
def _source(source_id: str = "src_xai00001", **changes) -> ModelHubSourceConfig:
@@ -40,23 +42,41 @@ def _source(source_id: str = "src_xai00001", **changes) -> ModelHubSourceConfig:
supply_channel="hub",
billing="metered",
state=ModelHubSourceStateConfig(status="standby"),
- models=[ModelHubModelConfig(id="grok-4.6", provenance="discovered")],
+ models=[ModelHubModelConfig(id="grok-4.6", provenance="discovered", reasoning_efforts=["low", "high"])],
credential_ref=f"cred_{source_id}",
)
return replace(source, **changes)
-def _record(source: ModelHubSourceConfig, feature: EvidenceFeature, **changes) -> EvidenceRecord:
+def _wire(source: ModelHubSourceConfig, *, engine: str = ENGINE, avibe: str = AVIBE) -> str:
+ return wire_stamp(engine=engine, avibe=avibe, source=source, model_id="grok-4.6")
+
+
+def _refusal(source: ModelHubSourceConfig, feature: EvidenceFeature, **changes) -> EvidenceRecord:
+ fields = dict(
+ source_id=source.id,
+ model_id="grok-4.6",
+ feature=feature,
+ status="unsupported",
+ observed_at=NOW,
+ wire=_wire(source),
+ source_identity=identity_digest(source),
+ detail="400 invalid_request_error",
+ )
+ fields.update(changes)
+ return EvidenceRecord(**fields)
+
+
+def _success(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,
+ wire=_wire(source),
source_identity=identity_digest(source),
+ mode="native",
)
fields.update(changes)
return EvidenceRecord(**fields)
@@ -65,63 +85,185 @@ def _record(source: ModelHubSourceConfig, feature: EvidenceFeature, **changes) -
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),
- ("unknown-engine-never-vouches", CALL, {"engine": "unknown-engine"}, "unknown-engine", 1, 0 * DAYS, "unknown", "wire"),
-]
- "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)
- # When the reading changes on its own: an observed record expires, a fresh probe record ages.
- if view.status == "unknown" and view.stale is None:
- assert view.changes_at is None
- elif record.basis == "observed":
- assert view.changes_at == record.observed_at + timedelta(days=7)
- else:
- assert view.changes_at == (record.observed_at + timedelta(days=30) if stale is None else None)
+def _store(tmp_path) -> CapabilityEvidenceStore:
+ return CapabilityEvidenceStore(tmp_path / "model_hub_capability_evidence.json")
@pytest.mark.parametrize(
- "manifest,stamp",
+ "case,current,applies",
[
- # A byte-identical engine upgrade carries the oldest such release forward: evidence stays current.
- ({"hosted_wire": "model-hub-engine-v8.0.23-3", "asset_release_tag": "model-hub-engine-v8.0.28-1"}, "model-hub-engine-v8.0.23-3"),
- # A manifest from before the field: its asset release, the value the release gate first carries forward.
- ({"asset_release_tag": "model-hub-engine-v8.0.23-3"}, "model-hub-engine-v8.0.23-3"),
- # A missing or malformed field never fails: the asset release stands in.
- ({"hosted_wire": "", "asset_release_tag": "model-hub-engine-v8.0.28-1"}, "model-hub-engine-v8.0.28-1"),
- ({"hosted_wire": 7, "asset_release_tag": "model-hub-engine-v8.0.28-1"}, "model-hub-engine-v8.0.28-1"),
- ({}, UNKNOWN_ENGINE_STAMP),
+ ("same-wire-a-year-later", lambda source: (source, _wire(source)), True),
+ ("engine-upgrade", lambda source: (source, _wire(source, engine="model-hub-engine-v8.0.28-1")), False),
+ ("avibe-release", lambda source: (source, _wire(source, avibe="3.2.2")), False),
+ (
+ "model-tiers-edited",
+ lambda source: (
+ (edited := replace(source, models=[replace(source.models[0], reasoning_efforts=["low", "high", "max"])])),
+ _wire(edited),
+ ),
+ False,
+ ),
+ (
+ "credential-rotated",
+ lambda source: ((rotated := replace(source, credential_ref="cred_rotated")), _wire(rotated)),
+ False,
+ ),
+ (
+ "base-url-edited",
+ lambda source: ((moved := replace(source, base_url="https://relay.example/v1")), _wire(moved)),
+ False,
+ ),
],
)
-def test_hosted_evidence_is_stamped_with_the_engines_hosted_wire(tmp_path, monkeypatch, manifest, stamp):
- """MH-HOSTED-003: evidence goes stale when the hosted wire changes, not on every engine release."""
- from core.handlers.model_hub.hosted_tools import engine_stamp
+def test_a_refusal_holds_until_the_wire_or_the_source_changes(tmp_path, case, current, applies):
+ """MH-HOSTED-003: a refusal has no time limit; it stops applying when the Source's config, the engine release, the
+ Avibe release or the model's rendered tiers change (owner rule: a Source config change resets it)."""
+ source = _source()
+ store = _store(tmp_path)
+ for feature in (CALL, ULTRA):
+ store.write_refusal(_refusal(source, feature), live=[source])
+ now_source, wire = current(source)
+ for feature in (CALL, ULTRA):
+ assert (store.refusal(now_source, "grok-4.6", feature, wire=wire) is not None) is applies
+
+
+def test_a_success_never_replaces_a_refusal_and_never_routes(tmp_path):
+ """MH-HOSTED-003: a success that settles after a concurrent refusal must not erase it; both are kept."""
+ source = _source()
+ store = _store(tmp_path)
+ store.write_refusal(_refusal(source, CALL), live=[source])
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(seconds=1)), live=[source], now=NOW)
+ assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
+ assert {record.status for record in store.records()} == {"verified", "unsupported"}
+
+
+def test_successes_reach_memory_at_once_and_the_file_at_most_hourly(tmp_path, monkeypatch):
+ """MH-HOSTED-003: every success is read at once while file writes are throttled per key, and a restart keeps what
+ reached the file."""
+ from core.handlers.model_hub import capability_evidence
+
+ path = tmp_path / "model_hub_capability_evidence.json"
+ source, other = _source(), _source("src_xai00002")
+ live = [source, other]
+ store = CapabilityEvidenceStore(path)
+ writes = []
+ persist = capability_evidence.write_state_document
+ monkeypatch.setattr(capability_evidence, "write_state_document", lambda *args: (writes.append(1), persist(*args)))
+
+ def seen(store, source):
+ return store.get(source.id, "grok-4.6", CALL, "verified").observed_at
+
+ store.note_success(_success(source, CALL), live=live, now=NOW)
+ store.note_success(_success(other, CALL, observed_at=NOW + timedelta(minutes=5)), live=live, now=NOW + timedelta(minutes=5))
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(minutes=10)), live=live, now=NOW + timedelta(minutes=10))
+ assert len(writes) == 2
+ assert (seen(store, source), seen(store, other)) == (NOW + timedelta(minutes=10), NOW + timedelta(minutes=5))
+ assert seen(CapabilityEvidenceStore(path), source) == NOW
+
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(hours=2)), live=live, now=NOW + timedelta(hours=2))
+ assert len(writes) == 3
+ assert seen(CapabilityEvidenceStore(path), source) == NOW + timedelta(hours=2)
+
+ # A new identity's first success is written at once: the file's copy belonged to the old one.
+ rotated = replace(source, credential_ref="cred_rotated")
+ at = NOW + timedelta(hours=2, minutes=1)
+ store.note_success(
+ _success(rotated, CALL, observed_at=at, source_identity=identity_digest(rotated), wire=_wire(rotated)),
+ live=[rotated, other], now=at,
+ )
+ assert len(writes) == 4
+ assert seen(CapabilityEvidenceStore(path), rotated) == at
+
- path = tmp_path / "manifest.json"
- path.write_text(json.dumps(manifest), encoding="utf-8")
- monkeypatch.setenv("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", str(path))
- assert engine_stamp() == stamp
+def test_the_newest_success_is_kept_whatever_order_settlements_land_in(tmp_path):
+ """MH-HOSTED-003: two successes of one key race to the lock; the older landing second does not regress it."""
+ path = tmp_path / "model_hub_capability_evidence.json"
+ source = _source()
+ store = CapabilityEvidenceStore(path)
+ later = NOW + timedelta(seconds=2)
+ store.note_success(_success(source, CALL, observed_at=later), live=[source], now=later)
+ store.note_success(_success(source, CALL), live=[source], now=later)
+ assert store.get(source.id, "grok-4.6", CALL, "verified").observed_at == later
+ assert CapabilityEvidenceStore(path).get(source.id, "grok-4.6", CALL, "verified").observed_at == later
+
+
+def test_the_newest_refusal_is_kept_whatever_order_settlements_land_in(tmp_path):
+ """MH-HOSTED-003: one ordering rule for every write; an older refusal landing second keeps the newer one."""
+ source = _source()
+ store = _store(tmp_path)
+ later = NOW + timedelta(seconds=2)
+ store.write_refusal(_refusal(source, CALL, observed_at=later, detail="400 newer"), live=[source])
+ store.write_refusal(_refusal(source, CALL, detail="400 older"), live=[source])
+ kept = store.refusal(source, "grok-4.6", CALL, wire=_wire(source))
+ assert (kept.observed_at, kept.detail) == (later, "400 newer")
+ # Learned under another engine, the older-in-time record still replaces it: the stored one no longer applies.
+ moved = _wire(source, engine="model-hub-engine-v8.0.28-1")
+ store.write_refusal(_refusal(source, CALL, wire=moved), live=[source])
+ assert store.refusal(source, "grok-4.6", CALL, wire=moved) is not None
+
+
+def test_a_refusal_holds_in_memory_when_its_write_fails(tmp_path, monkeypatch, caplog):
+ """MH-HOSTED-003: a refusal is routing state; the re-render that follows must not declare the feature again."""
+ from core.handlers.model_hub import capability_evidence
+
+ source = _source()
+ store = _store(tmp_path)
+
+ def full_disk(*_args):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(capability_evidence, "write_state_document", full_disk)
+ with caplog.at_level(logging.WARNING):
+ store.write_refusal(_refusal(source, CALL), live=[source])
+ assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
+ assert "holds until restart" in caplog.text
+
+
+def test_a_clear_is_persisted_before_it_takes_effect(tmp_path, monkeypatch):
+ """MH-HOSTED-003: a clear that cannot be written changes nothing, so it never comes back after a restart; one that
+ can removes only the refusals it names, never a success."""
+ from core.handlers.model_hub import capability_evidence
+
+ path = tmp_path / "model_hub_capability_evidence.json"
+ source = _source()
+ store = CapabilityEvidenceStore(path)
+ store.write_refusal(_refusal(source, CALL), live=[source])
+ store.write_refusal(_refusal(source, ULTRA), live=[source])
+ store.note_success(_success(source, CALL), live=[source], now=NOW)
+ persist = capability_evidence.write_state_document
+
+ def full_disk(*_args):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(capability_evidence, "write_state_document", full_disk)
+ with pytest.raises(OSError):
+ store.clear(lambda record: record.feature == CALL, live=[source])
+ assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
+
+ monkeypatch.setattr(capability_evidence, "write_state_document", persist)
+ assert store.clear(lambda record: record.feature == CALL, live=[source]) == 1
+ assert store.clear(lambda record: record.feature == CALL, live=[source]) == 0
+ reloaded = CapabilityEvidenceStore(path)
+ assert reloaded.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is None
+ assert reloaded.refusal(source, "grok-4.6", ULTRA, wire=_wire(source)) is not None
+ assert reloaded.get(source.id, "grok-4.6", CALL, "verified") is not None
+
+
+def test_the_bound_evicts_display_history_before_any_refusal(tmp_path):
+ """MH-HOSTED-003: a refusal holds until a clear or a change; the record bound never re-enables a feature."""
+ source = _source()
+ store = CapabilityEvidenceStore(tmp_path / "model_hub_capability_evidence.json", max_records=3)
+ store.write_refusal(_refusal(source, CALL, observed_at=NOW - timedelta(days=400)), live=[source])
+ for index, tool in enumerate(("web_search", "x_search", "image_generate")):
+ feature = EvidenceFeature.hosted(tool, "call")
+ store.note_success(_success(source, feature, observed_at=NOW + timedelta(hours=index)), live=[source], now=NOW)
+ store.write_refusal(_refusal(source, ULTRA), live=[source])
+
+ assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
+ assert store.refusal(source, "grok-4.6", ULTRA, wire=_wire(source)) is not None
+ assert [record.feature.name for record in store.records() if record.status == "verified"] == ["image_generate"]
@pytest.mark.parametrize(
@@ -133,89 +275,84 @@ def test_hosted_evidence_is_stamped_with_the_engines_hosted_wire(tmp_path, monke
ids=["verified", "pending"],
)
def test_a_released_sources_identity_digest_is_unchanged(marker, digest):
- """MH-HOSTED-003: evidence a released build recorded still follows the Source it loads. The digests are the ones
- released builds computed, whose identity held the verification marker; a pending Source's marker seeds its
- generation, so a reauthentication it was pending on never collides with the identity before it."""
- released = _source().to_payload()
+ """MH-HOSTED-003: evidence follows the Source a released build saved. The digests are the ones released builds
+ computed, whose identity held the verification marker; a pending Source's marker seeds its generation."""
+ released = replace(_source(), models=[ModelHubModelConfig(id="grok-4.6", provenance="discovered")]).to_payload()
if marker is not None:
released["verification_pending"] = marker
assert "credential_generation" not in released
assert identity_digest(ModelHubSourceConfig.from_payload(released)) == digest
-def test_a_changed_source_identity_reads_as_unknown_and_is_pruned(tmp_path):
- store = CapabilityEvidenceStore(tmp_path / "model_hub_capability_evidence.json")
+def test_a_changed_source_identity_is_pruned_at_the_next_write(tmp_path):
+ store = _store(tmp_path)
keep, rekeyed = _source("src_keep0001"), _source("src_swap0001")
- store.write(_record(keep, CALL), live=[keep, rekeyed])
- store.write(_record(rekeyed, CALL), live=[keep, rekeyed])
+ store.write_refusal(_refusal(keep, CALL), live=[keep, rekeyed])
+ store.write_refusal(_refusal(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])
+ store.write_refusal(_refusal(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])
+ store.write_refusal(_refusal(rekeyed, CALL), live=[keep, replaced])
-def test_persisted_records_match_the_schema_and_unreadable_ones_are_unknown(tmp_path):
+def test_persisted_records_match_the_schema_and_rc_era_ones_are_pruned(tmp_path):
+ """MH-HOSTED-003: an rc build's probe records (version 1) do not load; nothing migrates them."""
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]
- )
+ store.write_refusal(_refusal(source, ULTRA), live=[source])
+ store.note_success(_success(source, CALL), live=[source], now=NOW)
schema = json.loads((CONTRACTS / "capability-evidence.schema.json").read_text())
- validator = Draft7Validator(
- schema,
- registry=Registry().with_resources(
- [(schema["$id"], Resource.from_contents(schema))]
- ),
- )
+ validator = Draft7Validator(schema, registry=Registry().with_resources([(schema["$id"], Resource.from_contents(schema))]))
written = json.loads(path.read_text())
+ assert len(written) == 2
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))
+ rc_era = {
+ "version": 1, "source_id": source.id, "model_id": "grok-4.6",
+ "feature": {"kind": "hosted_tool", "name": "x_search", "aspect": "call"}, "status": "verified",
+ "basis": "probe", "observed_at": "2026-10-14T00:00:00Z", "engine": ENGINE, "shape": 1,
+ "source_identity": identity_digest(source),
+ }
+ path.write_text(json.dumps([*written, rc_era, {**written[0], "status": "maybe"}]))
assert len(CapabilityEvidenceStore(path).records()) == 2
- assert not validator.is_valid(written[2]) and not validator.is_valid(written[3])
+ assert not validator.is_valid(rc_era)
@pytest.mark.parametrize(
- "changes",
+ "build",
[
- {"basis": "observed"},
- {"basis": "observed", "status": "verified", "detail": "400 x"},
- {"detail": "x" * 65},
- {"observed_at": datetime(2026, 10, 13)},
- {"shape": -1},
- {"source_identity": ""},
- {"observed_at": datetime(9999, 12, 31, tzinfo=timezone.utc)},
- ],
- ids=[
- "observed-without-detail", "observed-positive", "long-detail", "naive-time", "negative-shape", "no-identity",
- "expiry-out-of-range",
+ lambda: _refusal(_source(), CALL, detail=None),
+ lambda: _refusal(_source(), CALL, mode="native"),
+ lambda: _success(_source(), CALL, mode=None),
+ lambda: _success(_source(), CALL, detail="400 x"),
+ lambda: _refusal(_source(), CALL, detail="x" * 65),
+ lambda: _refusal(_source(), CALL, observed_at=datetime(2026, 10, 15)),
+ lambda: _refusal(_source(), CALL, source_identity=""),
],
+ ids=["refusal-without-detail", "refusal-with-mode", "success-without-mode", "success-with-detail", "long-detail",
+ "naive-time", "no-identity"],
)
-def test_a_record_refuses_what_the_contract_forbids(changes):
+def test_a_record_refuses_what_the_contract_forbids(build):
with pytest.raises(ValueError):
- _record(_source(), CALL, **changes)
+ build()
-def test_image_generation_has_no_replay_evidence():
+def test_image_generate_has_no_replay_evidence():
+ with pytest.raises(ValueError):
+ EvidenceFeature.hosted("image_generate", "replay")
with pytest.raises(ValueError):
- EvidenceFeature.hosted("image_generation", "replay")
+ EvidenceFeature.hosted("image_generation", "call")
def test_lookups_after_construction_never_touch_the_disk(tmp_path, monkeypatch):
"""MH-HOSTED-003: the store reads its file when built at startup; no lookup or write reads it again."""
path = tmp_path / "model_hub_capability_evidence.json"
source = _source()
- CapabilityEvidenceStore(path).write(_record(source, CALL), live=[source])
+ CapabilityEvidenceStore(path).write_refusal(_refusal(source, CALL), live=[source])
store = CapabilityEvidenceStore(path)
assert len(store.records()) == 1
@@ -235,9 +372,9 @@ def test_lookups_after_construction_never_touch_the_disk(tmp_path, monkeypatch):
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 store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
+ store.write_refusal(_refusal(source, REPLAY), live=[source])
+ assert store.refusal(source, "grok-4.6", REPLAY, wire=_wire(source)) is not None
assert touched == []
@@ -250,7 +387,7 @@ def test_a_read_never_waits_for_a_write_on_a_slow_disk(tmp_path, monkeypatch):
path = tmp_path / "model_hub_capability_evidence.json"
source = _source()
store = CapabilityEvidenceStore(path)
- store.write(_record(source, CALL), live=[source])
+ store.write_refusal(_refusal(source, CALL), live=[source])
on_disk = threading.Event()
release = threading.Event()
@@ -262,18 +399,18 @@ def test_a_read_never_waits_for_a_write_on_a_slow_disk(tmp_path, monkeypatch):
persist(target, payload)
monkeypatch.setattr(capability_evidence, "write_state_document", slow_disk)
- writer = threading.Thread(target=store.write, args=(_record(source, REPLAY),), kwargs={"live": [source]})
+ writer = threading.Thread(target=store.write_refusal, args=(_refusal(source, REPLAY),), kwargs={"live": [source]})
writer.start()
try:
assert on_disk.wait(5)
read = []
reader = threading.Thread(
- target=lambda: read.append(store.view(source, "grok-4.6", CALL, engine=ENGINE, shape=1, now=NOW).status)
+ target=lambda: read.append(store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None)
)
reader.start()
reader.join(1)
- assert read == ["verified"]
+ assert read == [True]
finally:
release.set()
writer.join(5)
- assert store.view(source, "grok-4.6", REPLAY, engine=ENGINE, shape=1, now=NOW).status == "verified"
+ assert store.refusal(source, "grok-4.6", REPLAY, wire=_wire(source)) is not None
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index a71f1124f..185881d71 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"] == 14
+ assert schema["properties"]["contract_version"]["const"] == 15
assert 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": 14,
+ "contract_version": 15,
"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": 14,
+ "contract_version": 15,
"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": 14,
+ "contract_version": 15,
"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"] == 14
+ assert registry["contract_version"] == 15
ids = [entry["id"] for entry in registry["entries"]]
assert ids
assert 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, 12, 13, 14],
- "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
+ "values": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+ "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
} 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": 14,
+ "contract_version": 15,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": None,
diff --git a/tests/test_model_hub_declared_tools.py b/tests/test_model_hub_declared_tools.py
index 98a4b66b8..8be8c04c0 100644
--- a/tests/test_model_hub_declared_tools.py
+++ b/tests/test_model_hub_declared_tools.py
@@ -21,8 +21,6 @@ import aiohttp
import pytest
from aiohttp import web
-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.turn_gateway import ModelHubTurnGateway
from modules.agents.model_hub import ModelHubRuntimeRouter
from tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _service, _source
@@ -140,17 +138,7 @@ async def test_every_caller_reaches_the_engine_with_exactly_its_declared_tools(
_wire(service, tmp_path, root, {configured.id: {"plan_type": "plus"}} if subscription else {})
pin = {}
if backend == "vibey" and declared:
- source = service.store.config.sources[0]
- service.capability_evidence.write(
- EvidenceRecord(
- source_id=source.id, model_id="gpt-6-astra",
- feature=EvidenceFeature.hosted("image_generation", "call"), status="verified", basis="probe",
- observed_at=service.now(), engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(source),
- ),
- live=service.store.config.sources,
- )
- pin = {"x-avibe-pin-source": source.id}
+ pin = {"x-avibe-pin-source": service.store.config.sources[0].id}
gateway = ModelHubTurnGateway(service)
try:
if backend == "vibey":
diff --git a/tests/test_model_hub_evidence_rules.py b/tests/test_model_hub_evidence_rules.py
index 6db7b0f19..2c50038be 100644
--- a/tests/test_model_hub_evidence_rules.py
+++ b/tests/test_model_hub_evidence_rules.py
@@ -9,7 +9,6 @@ refused effort gets instead of another provider 400.
from __future__ import annotations
import json
-from datetime import timedelta
import pytest
from aiohttp import web
@@ -116,7 +115,7 @@ async def test_an_upstream_400_teaches_only_the_feature_it_names(
return
[record] = records
assert (record.source_id, record.model_id, record.feature) == ("src_evidence1", "shared-model", feature)
- assert (record.status, record.basis, record.detail) == ("unsupported", "observed", detail)
+ assert (record.status, record.detail) == ("unsupported", detail)
@pytest.mark.asyncio
@@ -160,7 +159,6 @@ async def test_a_refused_effort_skips_its_hop_instead_of_another_provider_400(tm
"basis": "observed",
"observed_at": record.payload()["observed_at"],
"detail": "400 invalid_request_error",
- "changes_at": (record.observed_at + timedelta(days=7)).isoformat().replace("+00:00", "Z"),
}
chain = service.agent_chain("codex", models["codex"])
_assert_valid("agent-chain.schema.json", chain)
@@ -241,7 +239,6 @@ async def test_a_refused_effort_still_waits_for_a_capable_hop_that_is_cooling_do
from datetime import timedelta
from core.handlers.model_hub.capability_evidence import EvidenceRecord, identity_digest
- from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp
from tests.test_model_hub_l3 import NOW, _canonicalize_fixed_test_routes, _service
refusing = _source("src_refuses01", "Refuses ultra")
@@ -250,16 +247,14 @@ async def test_a_refused_effort_still_waits_for_a_capable_hop_that_is_cooling_do
)
service = _service(tmp_path, sources=[refusing, cooling])
model = _canonicalize_fixed_test_routes(service)["codex"]
- service.capability_evidence.write(
+ service.capability_evidence.write_refusal(
EvidenceRecord(
source_id=refusing.id,
model_id="shared-model",
feature=EvidenceFeature.effort("ultra"),
status="unsupported",
- basis="observed",
observed_at=service.now(),
- engine=engine_stamp(),
- shape=HOSTED_PROBE_SHAPE,
+ wire=service.hosted_evidence().wire_for(refusing, "shared-model"),
source_identity=identity_digest(refusing),
detail="400 invalid_request_error",
),
@@ -335,7 +330,6 @@ async def test_a_refusing_runnable_hop_never_makes_recovery_spin(tmp_path):
from core.handlers.model_hub.adapter import RawOutcomeKind
from core.handlers.model_hub.capability_evidence import EvidenceRecord, identity_digest
- from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE
from tests.test_model_hub_l3 import NOW, _canonicalize_fixed_test_routes, _outcome
from tests.test_model_hub_retry_policy import clock_service
@@ -347,16 +341,14 @@ async def test_a_refusing_runnable_hop_never_makes_recovery_spin(tmp_path):
outcomes=[_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=cooling.id)],
)
model = _canonicalize_fixed_test_routes(service)["codex"]
- service.capability_evidence.write(
+ service.capability_evidence.write_refusal(
EvidenceRecord(
source_id=refusing.id,
model_id="shared-model",
feature=EvidenceFeature.effort("ultra"),
status="unsupported",
- basis="observed",
observed_at=service.now(),
- engine=service.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
+ wire=service.hosted_evidence().wire_for(refusing, "shared-model"),
source_identity=identity_digest(refusing),
detail="400 invalid_request_error",
),
@@ -426,7 +418,6 @@ def test_the_picker_menu_states_which_efforts_routing_refuses_in_menu_values(tmp
some refuse, in the values the menu offers, mapped to each hop's wire token by Vibey's own adapters."""
from config.v2_config import ModelHubBackendModelConfig
from core.handlers.model_hub.capability_evidence import EvidenceRecord, identity_digest
- from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE
from tests.test_model_hub_vibey_consumer import _vibey_service
sources = [_source(source_id, source_id, vendor=protocol.split("_")[0], protocol=protocol, model_id=model)
@@ -437,16 +428,14 @@ def test_the_picker_menu_states_which_efforts_routing_refuses_in_menu_values(tmp
by_id = {source.id: source for source in live}
for source_id, token in refused:
source = by_id[source_id]
- service.capability_evidence.write(
+ service.capability_evidence.write_refusal(
EvidenceRecord(
source_id=source_id,
model_id=source.models[0].id,
feature=EvidenceFeature.effort(token),
status="unsupported",
- basis="observed",
observed_at=service.now(),
- engine=service.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
+ wire=service.hosted_evidence().wire_for(source, source.models[0].id),
source_identity=identity_digest(source),
detail="400 invalid_request_error",
),
diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.py
index 004bba796..89797fdc6 100644
--- a/tests/test_model_hub_hosted_executor.py
+++ b/tests/test_model_hub_hosted_executor.py
@@ -10,24 +10,20 @@ answer must be the canonical record and execution, in the C-1 encoding of
from __future__ import annotations
import asyncio
-import base64
import gzip
import json
-import threading
from dataclasses import replace
from datetime import timedelta
import aiohttp
import pytest
-from config.v2_config import ModelHubHostedToolConfig, ModelHubRouteHopConfig
+from config.v2_config import ModelHubHostedToolConfig
from core.agent_core.messages import HostedCost, message_from_dict
-from core.handlers.model_hub import hosted_executor as executor_module
from core.handlers.model_hub import service as service_module
from core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKind
-from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest
from core.handlers.model_hub.hosted_executor import ResponsesReadout, anthropic_result, excerpt, responses_result
-from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp
+from core.handlers.model_hub import hosted_tools as hosted_tools_module
from core.handlers.model_hub.pricing import PriceTable
from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
@@ -107,24 +103,27 @@ def _sources(*extra):
return [xai, openai, anthropic, *extra]
+# The vendors' executor models these tests run with, in place of the bundled overlay's (vibey-hosted-tools.md §6).
+_EXECUTOR_MODELS: dict[str, str] = {}
+
+
[email protected](autouse=True)
+def _executor_models(monkeypatch):
+ _EXECUTOR_MODELS.clear()
+ monkeypatch.setattr(hosted_tools_module, "provider_executor_model", _EXECUTOR_MODELS.get)
+
+
def _bind(service, tool, executor):
- """Turn the tool on with this executor verified, so the turn's resolution binds it."""
+ """Turn the tool on with this Source first in its executor chain, on this executor model; None for no chain."""
config = service.store.config
config.hosted_tools[tool] = ModelHubHostedToolConfig(
- enabled=True, executor=ModelHubRouteHopConfig(*executor) if executor else None,
+ enabled=True, executor_order=(executor[0],) if executor else None,
)
if executor is None:
return
source = next(item for item in config.sources if item.id == executor[0])
- service.capability_evidence.write(
- EvidenceRecord(
- source_id=source.id, model_id=executor[1], feature=EvidenceFeature.hosted(tool, "call"),
- status="verified", basis="probe", observed_at=service.now(), engine=engine_stamp(),
- shape=HOSTED_PROBE_SHAPE, source_identity=identity_digest(source),
- ),
- live=config.sources,
- )
+ _EXECUTOR_MODELS[source.vendor] = executor[1]
async def _call(service, tool, body, *, token=None, after_launch=None, language="en"):
@@ -327,54 +326,6 @@ async def test_a_proxied_call_carries_the_pricing_modules_cost(tmp_path, tool, e
assert _hosted_result(tool, answer).execution.cost == (HostedCost(**cost) if cost else None)
-async def test_a_proxied_image_returns_its_bytes_once_for_vibey_to_save(tmp_path, monkeypatch):
- """MH-HOSTED-GATEWAY-004: the image comes back once, with the resolved prompt, size and quality.
-
- The final image is over Vibey's default 8 MiB SSE line, so the image stream's
- 32 MiB line cap is what accepts it. Partials are previews and are dropped;
- the duplicate in ``response.completed`` is not returned.
- """
-
- image = b"\x89PNG\r\n\x1a\n" + bytes(range(256)) * (7 * 1024 * 4)
- encoded = base64.b64encode(image).decode()
- assert len(encoded) > 9 * 1024 * 1024
- call = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",
- "quality": "low", "size": "1536x1024", "revised_prompt": "A small red paper boat", "result": encoded}
- partial = _event({"type": "response.image_generation_call.partial_image", "partial_image_index": 0,
- "partial_image_b64": base64.b64encode(b"preview").decode()})
- frames = _responses(call)
- service = _vibey_service(tmp_path, _sources(), handles=[
- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), (frames[0], partial, *frames[1:])),
- ])
- _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))
- encoding_threads = []
- dumps = json.dumps
-
- def recorded(value, *args, **kwargs):
- if isinstance(value, dict) and "images" in value:
- encoding_threads.append(threading.current_thread())
- return dumps(value, *args, **kwargs)
-
- monkeypatch.setattr(json, "dumps", recorded)
- status, answer = await _call(service, "image_generation", {
- "arguments": {"prompt": "a small red paper boat", "size": "1024x1024"},
- "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},
- })
- assert status == 200
- # Megabytes of base64 are never encoded on the controller loop.
- assert encoding_threads and threading.main_thread() not in encoding_threads
- sent = service.adapter.requests[0]
- assert sent["tools"] == [{
- "type": "image_generation", "partial_images": 2, "output_format": "jpeg", "output_compression": 90,
- "size": "1024x1024",
- }]
- assert sent["tool_choice"] == {"type": "image_generation"}
- assert "reasoning" not in sent
- assert answer["record"] == {"status": "completed", "sources": []}
- assert answer["generation"] == {"revised_prompt": "A small red paper boat", "size": "1536x1024", "quality": "low"}
- assert [(item["mime"], base64.b64decode(item["data"])) for item in answer["images"]] == [("image/png", image)]
- _hosted_result("image_generation", answer)
FAILED_WITH_PARTIAL = {**WEB_CALL, "status": "failed"}
@@ -472,65 +423,8 @@ async def test_only_the_executor_the_live_turn_bound_may_run(tmp_path, case):
assert service.adapter.invocations == []
[email protected](("case", "call", "error"), [
- ("unreadable_base64", {"result": "not base64!"}, "could not be used"),
- ("one_of_two_calls_failed", None, "image_generation call failed"),
- ("too_many_images", None, "larger than allowed"),
- ("partials_over_the_byte_budget", None, "larger than allowed"),
-])
-async def test_an_image_the_executor_cannot_vouch_for_is_a_failed_record(tmp_path, monkeypatch, case, call, error):
- """MH-HOSTED-GATEWAY-005: an undecodable image, more image events, or more image bytes than allowed fail.
- Partials count toward the decoded-byte budget though they are never returned.
- """
- if case == "partials_over_the_byte_budget":
- monkeypatch.setattr(executor_module, "_IMAGES_TOTAL_MAX_BYTES", 64)
-
- final = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",
- "result": base64.b64encode(b"\x89PNG fixture").decode(), **(call or {})}
- partial = _event({"type": "response.image_generation_call.partial_image", "partial_image_index": 0,
- "partial_image_b64": base64.b64encode(b"preview" * 8).decode()})
- frames = _responses(final) if case != "one_of_two_calls_failed" else _responses(
- {"type": "image_generation_call", "id": "ig_0", "status": "failed"}, final,
- )
- # Two partials were asked for; six are more than the final and the margin allow.
- stream = (frames[0], *([partial] * (6 if case == "too_many_images" else 1)), *frames[1:])
- service = _vibey_service(tmp_path, _sources(), handles=[
- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), stream),
- ])
- _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))
- status, answer = await _call(service, "image_generation", {
- "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},
- })
- assert status == 200
- assert answer["record"]["status"] == "failed" and error in answer["record"]["error"]
- assert "images" not in answer and "execution" in answer
-
-
-async def test_an_image_response_that_stopped_before_its_image_is_incomplete(tmp_path):
- """MH-HOSTED-GATEWAY-005: completion is the allow-list for images too; an early stop is incomplete, not failed."""
-
- frames = (
- _event({"type": "response.output_item.done", "item": {
- "type": "image_generation_call", "id": "ig_1", "status": "generating",
- }}),
- _event({"type": "response.incomplete", "response": {
- "id": "resp_1", "status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"},
- }}),
- )
- service = _vibey_service(tmp_path, _sources(), handles=[
- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), frames),
- ])
- _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))
- status, answer = await _call(service, "image_generation", {
- "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},
- })
- assert status == 200
- assert answer["record"]["status"] == "incomplete" and "max_output_tokens" in answer["record"]["error"]
- assert "images" not in answer
@pytest.mark.asyncio
@@ -728,6 +622,7 @@ async def test_a_turn_keeps_its_hosted_binding_until_the_next_turn(tmp_path):
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_CALL, WEB_ANSWER)),
])
_bind(service, "web_search", (XAI, "grok-4.6"))
+ service.store.config.hosted_tools["x_search"] = ModelHubHostedToolConfig(enabled=False)
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
@@ -769,28 +664,6 @@ async def test_a_proxy_call_body_is_bounded(tmp_path):
assert service.adapter.invocations == []
-async def test_items_only_the_terminal_response_carries_are_kept(tmp_path):
- """MH-HOSTED-GATEWAY-004: a relay that streams some items but not others still yields the terminal list's."""
-
- reasoning = {"type": "reasoning", "id": "rs_1", "summary": []}
- image = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",
- "result": base64.b64encode(b"\x89PNG fixture").decode(), "revised_prompt": "a boat"}
- frames = (
- _event({"type": "response.output_item.done", "item": reasoning}),
- _event({"type": "response.completed", "response": {
- "id": "resp_1", "status": "completed", "output": [reasoning, image]}}),
- )
- service = _vibey_service(tmp_path, _sources(), handles=[
- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), frames),
- ])
- _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))
- status, answer = await _call(service, "image_generation", {
- "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},
- })
- assert status == 200
- assert answer["record"]["status"] == "completed"
- assert [base64.b64decode(item["data"]) for item in answer["images"]] == [b"\x89PNG fixture"]
@pytest.mark.asyncio
diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.py
index 955e35ad0..7aa2da3d1 100644
--- a/tests/test_model_hub_hosted_pinning.py
+++ b/tests/test_model_hub_hosted_pinning.py
@@ -26,8 +26,9 @@ from core.handlers.model_hub.adapter import RawOutcomeKind, UpstreamRejection
from core.handlers.model_hub.capability_evidence import (
CapabilityEvidenceStore, EvidenceFeature, EvidenceRecord, identity_digest,
)
-from core.handlers.model_hub.hosted_admission import admits, hosted_content
-from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp
+from core.handlers.model_hub.hosted_admission import HostedContent, admits, hosted_content
+from core.handlers.model_hub.capability_evidence import wire_stamp
+from core.handlers.model_hub.hosted_tools import HostedEvidence
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT
from modules.agents.model_hub import ModelHubRuntimeRouter
@@ -51,12 +52,17 @@ def _sources(*, primary_status="standby", primary_model="grok-4.6"):
return primary, fallback
-def _verify(service, source, model_id, tool, aspect, *, engine=None):
- service.capability_evidence.write(
+def _refuse(service, source, model_id, tool, aspect, *, engine=None):
+ """A refusal a narrow rule wrote; ``engine`` names the release it was learned under (this one by default)."""
+
+ service.capability_evidence.write_refusal(
EvidenceRecord(
source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted(tool, aspect),
- status="verified", basis="probe", observed_at=service.now(), engine=engine or engine_stamp(),
- shape=HOSTED_PROBE_SHAPE, source_identity=identity_digest(source),
+ status="unsupported", observed_at=service.now(),
+ wire=wire_stamp(
+ engine=engine or service.engine_stamp, avibe=service.avibe_release, source=source, model_id=model_id,
+ ),
+ source_identity=identity_digest(source), detail="400 invalid_request_error",
),
live=service.store.config.sources,
)
@@ -87,9 +93,11 @@ def _native(hop, *, history=()):
("source_that_neither_launched_nor_served", 409, []),
("failure_before_output", 409, ["src_primary01"]),
("request_rejected", 400, ["src_primary01"]),
- ("no_call_evidence", 409, []),
+ # Nothing is probed: a tool the overlay offers is assumed until a real request refuses it.
+ ("no_evidence_is_assumed", 200, ["src_primary01"]),
+ ("current_refusal", 409, []),
("overlay_no_longer_offers_the_tool", 409, []),
- ("evidence_from_another_engine", 409, []),
+ ("refusal_from_another_engine_no_longer_applies", 200, ["src_primary01"]),
("source_cooling_down", 409, []),
("source_not_on_route", 409, []),
# Admission reads the snapshot the call is made on, after the engine is prepared.
@@ -116,26 +124,16 @@ async def test_a_pinned_request_is_served_only_by_its_source_or_handed_back(
outcome, LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=fallback.id), (b"{}",)),
])
service.recovery.window_seconds = 120
- if case == "source_that_neither_launched_nor_served":
- # Evidence is not enough: nothing this turn was rendered for that Source.
- _verify(service, fallback, "gpt-6-astra", "web_search", "call")
- elif case != "no_call_evidence":
- engine = "model-hub-engine-previous" if case == "evidence_from_another_engine" else None
- _verify(service, primary, primary_model, "x_search", "call", engine=engine)
+ if case == "current_refusal":
+ _refuse(service, primary, primary_model, "x_search", "call")
+ elif case == "refusal_from_another_engine_no_longer_applies":
+ _refuse(service, primary, primary_model, "x_search", "call", engine="model-hub-engine-previous")
if case == "evidence_demoted_while_the_engine_is_prepared":
prepare = service._prepare_engine_for_demand
async def demoting(*args, **kwargs):
await prepare(*args, **kwargs)
- service.capability_evidence.write(
- EvidenceRecord(
- source_id=primary.id, model_id=primary_model, feature=EvidenceFeature.hosted("x_search", "call"),
- status="unsupported", basis="observed", observed_at=service.now(), engine=engine_stamp(),
- shape=HOSTED_PROBE_SHAPE, source_identity=identity_digest(primary),
- detail="400 invalid_request_error",
- ),
- live=service.store.config.sources,
- )
+ _refuse(service, primary, primary_model, "x_search", "call")
service._prepare_engine_for_demand = demoting
scanning_threads = []
@@ -198,8 +196,6 @@ async def test_a_pin_names_the_exact_hop_it_was_rendered_for(tmp_path, case):
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
])
- for model_id in ("grok-4.6", "grok-4.7"):
- _verify(service, primary, model_id, "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
@@ -257,7 +253,6 @@ async def test_a_continuation_stays_on_the_identity_its_response_was_served_unde
service = _vibey_service(tmp_path, [primary, fallback], handles=[
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)) for _ in statuses
])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
answers = []
@@ -268,7 +263,6 @@ async def test_a_continuation_stays_on_the_identity_its_response_was_served_unde
if case == "credential_rotated_and_reverified":
live = service.store.config.sources[0]
live.credential_ref = "cred_rotated0001"
- _verify(service, live, "grok-4.6", "x_search", "call")
# Client tool results after the model's X search: the in-flight response carries its native item.
continuation = {
"model": hop["runtime_model"], "stream": False,
@@ -295,14 +289,12 @@ async def test_a_pinned_request_rendered_for_the_launch_identity_is_handed_back_
service = _vibey_service(tmp_path, [primary, fallback], handles=[
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
hop = await router.resolve_hop("menu-alias", process_scope="vibey:rotated", turn_id="turn-rotated")
live = service.store.config.sources[0]
live.credential_ref = "cred_rotated0001"
- _verify(service, live, "grok-4.6", "x_search", "call")
answer = await _post(hop, _native(hop, history=[SIGNED_REASONING]), pin=primary.id)
finally:
await gateway.close()
@@ -322,7 +314,6 @@ async def test_overlapping_first_pinned_requests_bind_one_identity(tmp_path):
service = _vibey_service(tmp_path, [primary, fallback], handles=[
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)) for _ in range(2)
])
- _verify(service, primary, "grok-4.6", "x_search", "call")
admitted, release = asyncio.Event(), asyncio.Event()
invoke = service.adapter.invoke
@@ -342,7 +333,6 @@ async def test_overlapping_first_pinned_requests_bind_one_identity(tmp_path):
await asyncio.wait_for(admitted.wait(), timeout=5)
live = service.store.config.sources[0]
live.credential_ref = "cred_rotated0001"
- _verify(service, live, "grok-4.6", "x_search", "call")
assert await _post(hop, _native(hop), pin=primary.id) == (409, PIN_UNAVAILABLE)
release.set()
assert (await asyncio.wait_for(first, timeout=5))[0] == 200
@@ -361,7 +351,6 @@ async def test_the_portable_resend_fails_over_and_the_turn_settles_on_it(tmp_pat
InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error")),
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=fallback.id), (b"{}",)),
])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
turn_id = "turn-resend"
@@ -397,7 +386,6 @@ async def test_an_ambiguous_pinned_failure_is_no_health_evidence_so_the_resend_m
InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=200, code="unrecognized_fixture")),
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
@@ -426,9 +414,6 @@ async def test_unpinned_hosted_content_is_refused_before_anything_runs(tmp_path,
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
])
# Evidence everywhere does not make unpinned content admissible.
- _verify(service, primary, "grok-4.6", "web_search", "call")
- _verify(service, primary, "grok-4.6", "web_search", "replay")
- _verify(service, fallback, "gpt-6-astra", "web_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
@@ -453,7 +438,6 @@ async def test_a_handed_back_refusal_does_not_end_the_turn(tmp_path):
rejection=UpstreamRejection(status=400, code="invalid_request_error", unsupported_tool_type="x_search"),
)
service = _vibey_service(tmp_path, [primary], handles=[InvokeHandle(refusal)])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
turn_id = "turn-withdraw"
@@ -508,7 +492,6 @@ async def test_a_refusal_naming_the_pinned_hosted_content_is_handed_back_and_lea
unsupported_tool_type="x_search"),
)
service = _vibey_service(tmp_path, [primary, fallback], handles=[InvokeHandle(refusal)])
- _verify(service, primary, "grok-4.6", "x_search", "call")
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
@@ -517,11 +500,8 @@ async def test_a_refusal_naming_the_pinned_hosted_content_is_handed_back_and_lea
finally:
await gateway.close()
assert [entry[0] for entry in service.adapter.invocations] == [primary.id]
- learned = service.capability_evidence.view(
- primary, "grok-4.6", EvidenceFeature.hosted("x_search", "call"),
- engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE, now=service.now(),
- )
- assert (learned.status, learned.record.basis) == ("unsupported", "observed")
+ learned = service.hosted_evidence().refusal(primary, "grok-4.6", EvidenceFeature.hosted("x_search", "call"))
+ assert learned is not None and learned.detail.startswith("400")
# Responses and Anthropic histories: (case, protocol, history, pinned, the tools needing replay evidence).
@@ -622,29 +602,44 @@ def test_admission_runs_a_tool_only_where_hop_resolution_would(tmp_path, case, k
if listed != "listed":
source.models = [ModelHubModelConfig(id=model_id if listed == "retired" else "gpt-6-other",
provenance="discovered", retired=listed == "retired" or None)]
- evidence = CapabilityEvidenceStore(tmp_path / "evidence.json")
- evidence.write(
- EvidenceRecord(
- source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted("web_search", "call"),
- status="verified", basis="probe", observed_at=NOW, engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(source),
- ),
- live=[source],
- )
+ evidence = HostedEvidence(CapabilityEvidenceStore(tmp_path / "evidence.json"), "engine", "avibe")
content = hosted_content({"tools": [{"type": "web_search"}]}, "openai_responses", pinned=True)
- assert admits(
- content, source=source, model_id=model_id, spec_for=hosted_tool_spec, evidence=evidence,
- engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE, now=NOW,
- ) is admitted
+ assert admits(content, source=source, model_id=model_id, spec_for=hosted_tool_spec, evidence=evidence) is admitted
+
+
[email protected](("refused", "admitted"), [
+ ((), True),
+ (("replay",), False),
+ # A call refusal withdraws replay too, as the hop's facts state; a concurrent refusal must not be outrun.
+ (("call",), False),
+])
+def test_a_replay_is_admitted_exactly_where_the_hops_facts_assume_it(tmp_path, refused, admitted):
+ """MH-HOSTED-GATEWAY-002: admission and hop resolution read one rule, so they never disagree about a replay."""
+
+ source = _source("src_xai000001", "xAI", vendor="xai", model_id="grok-4.6")
+ store = CapabilityEvidenceStore(tmp_path / "evidence.json")
+ evidence = HostedEvidence(store, "engine", "avibe")
+ for aspect in refused:
+ store.write_refusal(
+ EvidenceRecord(
+ source_id=source.id, model_id="grok-4.6", feature=EvidenceFeature.hosted("web_search", aspect),
+ status="unsupported", observed_at=NOW, wire=evidence.wire_for(source, "grok-4.6"),
+ source_identity=identity_digest(source), detail="400 invalid_request_error",
+ ),
+ live=[source],
+ )
+ content = HostedContent(replays=frozenset({"web_search"}))
+ assert admits(content, source=source, model_id="grok-4.6", spec_for=hosted_tool_spec, evidence=evidence) is admitted
def test_declarations_are_recognized_by_every_vendors_type():
"""MH-HOSTED-GATEWAY-003: a declaration counts whichever vendor offers it, never a function."""
+ # No chat request declares a hosted image tool any more, so its type is no declaration.
tools = [{"type": "x_search"}, {"type": "web_search"}, {"type": "image_generation", "partial_images": 2},
PORTABLE_X_SEARCH, {"type": "web_search_20250305", "name": "web_search"}]
assert hosted_content({"tools": tools}, "openai_responses", pinned=True).calls == frozenset(
- {("x_search", "x_search"), ("web_search", "web_search"), ("image_generation", "image_generation")}
+ {("x_search", "x_search"), ("web_search", "web_search")}
)
assert hosted_content({"tools": tools}, "anthropic", pinned=True).calls == frozenset(
{("web_search", "web_search_20250305")}
diff --git a/tests/test_model_hub_hosted_probe.py b/tests/test_model_hub_hosted_probe.py
deleted file mode 100644
index 5ab960132..000000000
--- a/tests/test_model_hub_hosted_probe.py
+++ /dev/null
@@ -1,951 +0,0 @@
-"""The hosted-tool probes (``vibey-hosted-tools.md`` §3.2, capability model §3.3). Scenario MH-HOSTED-007.
-
-The real engine client invokes a loopback upstream that plays each provider's answer, and Vibey's own adapter
-reads the response, so a probe recognizes a result only as the hosted call a real turn would keep. Only
-``verified`` and ``unsupported`` are evidence; every other outcome leaves the record that was there.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import base64
-import json
-from dataclasses import replace
-from datetime import timedelta
-from typing import Any
-
-import pytest
-from aiohttp import web
-
-from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest
-from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE
-from core.handlers.model_hub.service import ModelHubError
-from tests.test_model_hub_l3 import _assert_valid, _source
-from tests.test_model_hub_retry_lifecycle import configured_service, loopback_engine
-from vibe.backend_model_catalog import hosted_tool_spec
-
-XAI = _source("src_probe0001", "xAI 密钥", vendor="xai", protocol="openai_responses", model_id="grok-4.6")
-ANTHROPIC = _source("src_probe0002", "Anthropic 中转", vendor="anthropic", protocol="anthropic", model_id="claude-sonnet-4-6")
-CALL = EvidenceFeature.hosted("web_search", "call")
-REPLAY = EvidenceFeature.hosted("web_search", "replay")
-
-
-def _records(service, feature) -> list:
- return [record for record in service.capability_evidence.records() if record.feature == feature]
-
-
-def _sse(*events: dict[str, Any]) -> str:
- # Both providers name every event, as the engine's stream observer expects.
- return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events)
-
-
-# A result the call returned that its visible answer never shows: only the replayed native payload holds it.
-HIDDEN = "https://avibe.bot/docs/hosted-tools"
-SEARCH = {
- "id": "ws_1",
- "type": "web_search_call",
- "status": "completed",
- "action": {
- "type": "search",
- "query": "Avibe local-first agent OS",
- "sources": [{"type": "url", "url": "https://avibe.bot/"}, {"type": "url", "url": HIDDEN}],
- },
-}
-ANSWER = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "https://avibe.bot/", "annotations": []}]}
-
-
-def _responses(*items: dict[str, Any]) -> str:
- events: list[dict[str, Any]] = [{"type": "response.created", "response": {"status": "in_progress"}}]
- for index, item in enumerate(items):
- events.append({"type": "response.output_item.added", "output_index": index, "item": {**item, "status": "in_progress"}})
- if item["type"] == "message":
- events.append({"type": "response.output_text.delta", "output_index": index, "delta": item["content"][0]["text"]})
- events.append({"type": "response.output_item.done", "output_index": index, "item": item})
- usage = {"input_tokens": 900, "output_tokens": 40, "server_side_tool_usage_details": {"web_search_calls": len(items) - 1}}
- events.append({"type": "response.completed", "response": {"status": "completed", "usage": usage}})
- return _sse(*events)
-
-
-ANTHROPIC_SEARCH = _sse(
- {"type": "message_start", "message": {"usage": {"input_tokens": 900}}},
- {"type": "content_block_start", "index": 0, "content_block": {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {}}},
- {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": '{"query": "Avibe"}'}},
- {"type": "content_block_stop", "index": 0},
- {
- "type": "content_block_start",
- "index": 1,
- "content_block": {
- "type": "web_search_tool_result",
- "tool_use_id": "srvtoolu_1",
- "content": [
- {"type": "web_search_result", "title": "Avibe", "url": "https://avibe.bot/", "encrypted_content": "opaque"},
- {"type": "web_search_result", "title": "Hosted tools", "url": HIDDEN, "encrypted_content": "opaque"},
- ],
- },
- },
- {"type": "content_block_stop", "index": 1},
- {"type": "content_block_start", "index": 2, "content_block": {"type": "text", "text": ""}},
- {"type": "content_block_delta", "index": 2, "delta": {"type": "text_delta", "text": "https://avibe.bot/"}},
- {"type": "content_block_stop", "index": 2},
- {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 40, "server_tool_use": {"web_search_requests": 1}}},
- {"type": "message_stop"},
-)
-def _anthropic_text(text: str) -> str:
- return _sse(
- {"type": "message_start", "message": {"usage": {"input_tokens": 1200}}},
- {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
- {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}},
- {"type": "content_block_stop", "index": 0},
- {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 12}},
- {"type": "message_stop"},
- )
-
-
-def _responses_text(text: str) -> str:
- return _responses({"id": "msg_2", "type": "message", "content": [{"type": "output_text", "text": text, "annotations": []}]})
-
-
-REFUSAL = _sse(
- {"type": "response.created", "response": {"status": "in_progress"}},
- {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_3", "type": "message", "status": "in_progress", "content": []}},
- {"type": "response.refusal.delta", "output_index": 0, "delta": f"I won't repeat {HIDDEN}."},
- {
- "type": "response.output_item.done",
- "output_index": 0,
- "item": {"id": "msg_3", "type": "message", "status": "completed", "content": [{"type": "refusal", "refusal": f"I won't repeat {HIDDEN}."}]},
- },
- {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 900, "output_tokens": 9}}},
-)
-
-
-def _replay_reply(protocol: str, request: dict) -> str:
- """A model answering the replay probe from what it was sent: it can name the result only the native payload
- holds when that payload came back, and nothing more otherwise."""
-
- text = HIDDEN if HIDDEN in json.dumps(request) else "I can't tell without searching again."
- return _anthropic_text(text) if protocol == "anthropic" else _responses_text(text)
-
-
-
-
-def _stream(body: str) -> web.Response:
- return web.Response(body=body.encode(), content_type="text/event-stream")
-
-
-# Output, then a server error in the stream: the call cannot be retried as a turn, but a probe can run again.
-FAILED_AFTER_OUTPUT = _sse(
- {"type": "response.created", "response": {"status": "in_progress"}},
- {"type": "response.output_item.added", "output_index": 0, "item": {**ANSWER, "status": "in_progress"}},
- {"type": "response.output_text.delta", "output_index": 0, "delta": "https://"},
- {
- "type": "response.failed",
- "response": {"status": "failed", "error": {"code": "server_error", "message": "The server had an error."}},
- },
-)
-TOOL_REFUSED = {"error": {"message": "Unsupported tool type: web_search", "type": "invalid_request_error"}}
-CHOICE_REFUSED = {"error": {"message": "tool_choice 'required' is not supported", "type": "invalid_request_error", "param": "tool_choice"}}
-OVERLOADED = {"error": {"message": "The servers are overloaded", "type": "overloaded_error"}}
-
-CASES = [
- # (case, Source, upstream status, upstream body, outcome, the record afterwards: written status or None for
- # kept, whether the response failed to complete)
- ("responses-result", XAI, 200, _responses(SEARCH, ANSWER), "verified", "verified", False),
- ("anthropic-result", ANTHROPIC, 200, ANTHROPIC_SEARCH, "verified", "verified", False),
- ("no-tool-item", XAI, 200, _responses(ANSWER), "inconclusive", None, False),
- ("tool-type-refused", XAI, 400, TOOL_REFUSED, "unsupported", "unsupported", True),
- ("another-400", XAI, 400, CHOICE_REFUSED, "inconclusive", None, True),
- ("overloaded", XAI, 503, OVERLOADED, "transient", None, True),
- ("failed-after-output", XAI, 200, FAILED_AFTER_OUTPUT, "transient", None, True),
-]
-
-
- "source,status,body,outcome,written,failed", [case[1:] for case in CASES], ids=[case[0] for case in CASES]
-)
-async def test_a_call_probe_sends_the_production_request_and_records_only_what_it_shows(
- tmp_path, source, status, body, outcome, written, failed
-):
- """MH-HOSTED-007: the probe is Vibey's native request on exactly the probed Source, forced except on Anthropic;
- only a result or a refusal naming the tool is evidence, and anything else keeps the earlier record."""
- service, clock, _models = configured_service(tmp_path, sources=[source])
- model_id = source.models[0].id
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- if len(sent) > 1:
- return _stream(_replay_reply(source.protocol, sent[-1]))
- if isinstance(body, str):
- return web.Response(status=status, body=body.encode(), content_type="text/event-stream")
- return web.json_response(body, status=status)
-
- async with loopback_engine(tmp_path, service, respond):
- # A real refusal learned a day ago, for the Source as the engine now holds its credential.
- [live] = service.store.load().sources
- prior = EvidenceRecord(
- source_id=source.id,
- model_id=model_id,
- feature=CALL,
- status="unsupported",
- basis="observed",
- observed_at=clock.now() - timedelta(days=1),
- engine=service.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(live),
- detail="400 invalid_request_error",
- )
- service.capability_evidence.write(prior, live=[live])
- result = await service.probe_hosted_tool("web_search", {"source_id": source.id, "model_id": model_id})
-
- request = sent[0]
- declaration = hosted_tool_spec(source.vendor, source.protocol, model_id, "web_search").declaration
- assert request["tools"] == [declaration]
- assert "news article published today" in json.dumps(request, ensure_ascii=False)
- assert "reasoning" not in request and "output_config" not in request
- if source.protocol == "anthropic":
- assert "tool_choice" not in request
- else:
- assert request["tool_choice"] == "required"
-
- probe = result["probe"]
- _assert_valid("hosted-tool-probe-result.schema.json", probe)
- assert (probe["tool"], probe["source_id"], probe["model_id"]) == ("web_search", source.id, model_id)
- assert probe["call"]["outcome"] == outcome
- # Only a verified call is followed by the replay probe; its answer here names the first result without searching.
- assert len(sent) == (2 if written == "verified" else 1)
- assert probe["replay"] == ({"outcome": "verified", "error": None} if written == "verified" else None)
- # A response that failed says why, as the Source test does; a refusal naming the tool is the answer itself.
- assert (probe["call"]["error"] is not None) == (failed and outcome != "unsupported")
-
- [record] = _records(service, CALL)
- assert len(_records(service, REPLAY)) == (1 if written == "verified" else 0)
- if written is None:
- assert record == prior
- else:
- assert (record.status, record.basis, record.engine, record.shape) == (
- written, "probe", service.engine_stamp, HOSTED_PROBE_SHAPE
- )
- assert record.detail == ("400 invalid_request_error" if written == "unsupported" else None)
- assert record.observed_at > prior.observed_at
- # The response carries the Tools tab as it reads now.
- [candidate] = next(tool for tool in result["hosted_tools"]["tools"] if tool["name"] == "web_search")["candidates"]
- assert candidate["call"]["status"] == (written or "unsupported")
-
-
-async def test_a_probe_runs_only_on_a_target_the_tool_can_run_on(tmp_path):
- """MH-HOSTED-007: a refused target never reaches the upstream, so it costs nothing."""
- subscription = replace(ANTHROPIC, id="src_probe0003", kind="subscription", billing="monthly")
- google = _source("src_probe0004", "Gemini", vendor="google", protocol="google", model_id="gemini-3-pro")
- retired = _source("src_probe0007", "xAI retired", vendor="xai", protocol="openai_responses", model_id="grok-4.5")
- retired.models[0].retired = True
- chatgpt = replace(
- _source("src_probe0008", "ChatGPT", vendor="openai", protocol="openai_responses", model_id="gpt-6-sol"),
- kind="subscription",
- billing="monthly",
- )
- service, _clock, _models = configured_service(tmp_path, sources=[XAI, subscription, google, retired, chatgpt])
- sent = []
-
- async def invoke(*args, **kwargs):
- sent.append(args)
- raise AssertionError("a refused probe reached the upstream")
-
- service.adapter.invoke = invoke
- for tool, target, code, status in [
- # xAI's overlay declares no image tool, so there is nothing to probe.
- ("image_generation", {"source_id": XAI.id, "model_id": "grok-4.6"}, "invalid_parameter", 400),
- ("code_interpreter", {"source_id": XAI.id, "model_id": "grok-4.6"}, "invalid_parameter", 400),
- ("web_search", {"source_id": XAI.id}, "invalid_parameter", 400),
- ("web_search", {"source_id": XAI.id, "model_id": ["grok-4.6"]}, "invalid_parameter", 400),
- ("web_search", {"source_id": 7, "model_id": "grok-4.6"}, "invalid_parameter", 400),
- ("web_search", {"source_id": XAI.id, "model_id": " "}, "invalid_parameter", 400),
- ("web_search", {"source_id": "src_gone0001", "model_id": "grok-4.6"}, "source_not_found", 404),
- ("web_search", {"source_id": XAI.id, "model_id": "grok-3"}, "invalid_parameter", 400),
- # Anthropic restricts OAuth credentials to its own apps.
- ("web_search", {"source_id": subscription.id, "model_id": "claude-sonnet-4-6"}, "invalid_parameter", 400),
- # Vibey reaches a google Source through a translation, never natively.
- ("web_search", {"source_id": google.id, "model_id": "gemini-3-pro"}, "invalid_parameter", 400),
- # A model discovery retired stays listed as a tombstone, and a tombstone never supplies work.
- ("web_search", {"source_id": retired.id, "model_id": "grok-4.5"}, "invalid_parameter", 400),
- # A subscription serves only its listed models; an API-key Source would serve this one as a passthrough.
- ("web_search", {"source_id": chatgpt.id, "model_id": "gpt-6-astra"}, "invalid_parameter", 400),
- ]:
- with pytest.raises(ModelHubError) as refused:
- await service.probe_hosted_tool(tool, target)
- assert (refused.value.code, refused.value.status) == (code, status), (tool, target)
-
- assert sent == []
- assert service.capability_evidence.records() == []
- # The same rule decides where the Tools tab lists the tool and what a turn binds as its executor, so even
- # verified evidence never makes a tombstone either.
- service.capability_evidence.write(
- EvidenceRecord(
- source_id=retired.id,
- model_id="grok-4.5",
- feature=CALL,
- status="verified",
- basis="probe",
- observed_at=service.now(),
- engine=service.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(retired),
- ),
- live=service.store.load().sources,
- )
- status = service.hosted_tools_status()["hosted_tools"]
- web_search = next(tool for tool in status["tools"] if tool["name"] == "web_search")
- assert [candidate["source_id"] for candidate in web_search["candidates"]] == [XAI.id, chatgpt.id]
- assert web_search["bound"] is None
- # Nor does the tombstone's record ask for a re-verify the Tools tab has no candidate for.
- service.engine_stamp = "model-hub-engine-next"
- assert service.hosted_tools_status()["hosted_tools"]["reverify"] == {"engine_upgraded": 0, "aged": 0}
-
-
-def test_each_candidate_states_what_probing_it_would_cost(tmp_path):
- """MH-HOSTED-007: the Tools read prices a probe before it runs, the call and the replay that may follow it: at
- list price on a metered Source, included on a monthly one, and unknown (never zero) when the model has no token
- price."""
- from core.handlers.model_hub.usage import UsageWriter
- from tests.test_model_hub_pricing import _table
-
- monthly = replace(XAI, id="src_probe0005", display_name="xAI monthly", billing="monthly", credential_ref="cred_src_probe0005")
- unpriced = _source("src_probe0006", "xAI unlisted", vendor="xai", protocol="openai_responses", model_id="grok-4-unlisted")
- service, _clock, _models = configured_service(tmp_path, sources=[XAI, monthly, unpriced])
- # grok-4.6 at $2 / $6 per million tokens; xAI lists web search at $5 per 1k calls and X search at $5 per 1k posts.
- service.usage_writer = UsageWriter(service.usage, price_table=_table)
-
- status = service.hosted_tools_status()["hosted_tools"]
-
- _assert_valid("hosted-tools-status.schema.json", status)
- estimates = {
- (tool["name"], candidate["source_id"]): candidate["probe_estimate"]
- for tool in status["tools"]
- for candidate in tool["candidates"]
- }
- tokens = 8000 * 2 / 1e6 + 500 * 6 / 1e6
- # The replay sends the call's turn back and asks one question, using no tool, so it has no tool fee.
- replay = 12000 * 2 / 1e6 + 300 * 6 / 1e6
- assert estimates[("web_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 5 / 1000 + replay)}
- assert estimates[("x_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 10 * 5 / 1000 + replay)}
- assert estimates[("web_search", monthly.id)] == {"basis": "included"}
- assert estimates[("web_search", unpriced.id)] is None
-
-
- "refusal",
- [
- "cache_control.ttl: Extra inputs are not permitted",
- # A refusal that also names the tool type speaks only for the request it refused: the resend's result decides.
- "Unsupported tool type: web_search_20250305; cache_control.ttl: Extra inputs are not permitted",
- ],
- ids=["ttl", "ttl-and-tool-type"],
-)
-async def test_each_request_the_adapter_sends_is_its_own_pinned_call(tmp_path, monkeypatch, refusal):
- """MH-HOSTED-007: the probe runs Vibey's adapter unchanged. A relay that refuses Anthropic's one-hour cache
- lifetime gets the adapter's resend, as a real turn would, and each request is one call on the probed Source."""
- from core.agent_core.ai import anthropic as anthropic_adapter
-
- monkeypatch.setattr(anthropic_adapter, "_TTL_REJECTED_ROUTES", set())
- service, _clock, _models = configured_service(tmp_path, sources=[ANTHROPIC])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- if len(sent) > 2:
- return _stream(_replay_reply("anthropic", sent[-1]))
- if '"ttl": "1h"' in json.dumps(sent[-1]):
- return web.json_response(
- {"type": "error", "error": {"type": "invalid_request_error", "message": refusal}},
- status=400,
- )
- return web.Response(body=ANTHROPIC_SEARCH.encode(), content_type="text/event-stream")
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool(
- "web_search", {"source_id": ANTHROPIC.id, "model_id": "claude-sonnet-4-6"}
- )
-
- first, resent, _replay = sent
- assert '"ttl": "1h"' in json.dumps(first) and '"ttl": "1h"' not in json.dumps(resent)
- assert first["tools"] == resent["tools"]
- assert result["probe"]["call"] == {"outcome": "verified", "error": None}
- [record] = _records(service, CALL)
- assert (record.source_id, record.status, record.basis) == (ANTHROPIC.id, "verified", "probe")
-
-
-async def test_a_probe_that_verifies_its_source_records_evidence_for_the_source_as_it_now_is(tmp_path):
- """MH-HOSTED-007: a new Source's first successful call retires its pending verification, which changes no
- identity; the probe's record follows the Source as it reads after that call."""
- marker = "vp_" + "0" * 32
- pending = replace(XAI, verification_pending=marker, credential_generation=marker)
- service, _clock, _models = configured_service(tmp_path, sources=[pending])
-
- async def respond(_request):
- return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- [live] = service.store.load().sources
- assert live.verification_pending is None
- assert result["probe"]["call"]["outcome"] == "verified"
- [record] = _records(service, CALL)
- assert record.source_identity == identity_digest(live)
- [candidate] = next(tool for tool in result["hosted_tools"]["tools"] if tool["name"] == "web_search")["candidates"]
- assert candidate["call"]["status"] == "verified"
-
-
[email protected]("verified_after", [False, True], ids=["pending", "then-verified-by-another-call"])
-async def test_a_probe_records_no_evidence_for_a_source_reauthenticated_mid_probe(tmp_path, verified_after):
- """MH-HOSTED-007: a reauthentication that lands mid-probe (same credential ref, a new credential generation)
- leaves the old grant's result without a record, also once another call has verified the new grant."""
- from core.handlers.model_hub.service import ModelHubService
-
- first = "vp_" + "1" * 32
- service, _clock, _models = configured_service(
- tmp_path, sources=[replace(XAI, verification_pending=first, credential_generation=first)],
- )
-
- async def respond(_request):
- config = service.store.load()
- ModelHubService._mark_source_unverified(config.sources[0])
- service.store.save(config)
- if verified_after:
- config = service.store.load()
- config.sources[0].verification_pending = None
- service.store.save(config)
- return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert result["probe"]["call"]["outcome"] == "verified"
- assert service.store.load().sources[0].credential_generation not in (None, first)
- assert service.capability_evidence.records() == []
-
-
-async def test_the_probe_reads_its_calls_in_the_order_the_adapter_sent_them():
- """MH-HOSTED-007: a resend can settle before the request it replaces; the probe still reads the resend last."""
- import httpx
-
- from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
- from core.handlers.model_hub.hosted_probe import PinnedCallTransport
- from core.handlers.model_hub.service import UserTestCall
-
- first_may_settle = asyncio.Event()
-
- class Handle:
- stream = None
-
- async def call(body, read):
- await read(Handle())
- if body["n"] == 1:
- await first_may_settle.wait()
- else:
- first_may_settle.set()
- status = 400 if body["n"] == 1 else 503
- outcome = RawCallOutcome(RawOutcomeKind.HTTP_ERROR, status, None, None, False, "grok-4.6", XAI.id)
- return UserTestCall(XAI, outcome, 0)
-
- transport = PinnedCallTransport(call)
- async with httpx.AsyncClient(transport=transport) as client:
- first = asyncio.create_task(client.post("http://probe.invalid/", json={"n": 1}))
- await asyncio.sleep(0)
- await client.post("http://probe.invalid/", json={"n": 2})
- await first
- await transport.settle()
-
- assert [call.body["n"] for call in transport.calls] == [1, 2]
-
-
-async def test_the_probe_asks_for_no_more_output_than_a_turn_on_its_hop_would(tmp_path):
- """MH-HOSTED-007: a Vibey turn asks for its menu model's output budget; a relay model that declares a small
- output maximum is probed within it, so the probe is not refused where real turns succeed."""
- from config.v2_config import ModelHubBackendModelConfig, ModelHubRouteConfig, ModelHubRouteHopConfig
-
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- vibey = service.store.config.agents["vibey"]
- vibey.models = [ModelHubBackendModelConfig(id="relay-grok", context_window=128000, max_output_tokens=1024)]
- vibey.sources.order = [XAI.id]
- vibey.routes["relay-grok"] = ModelHubRouteConfig((ModelHubRouteHopConfig(XAI.id, "grok-4.6"),))
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- # The replay probe that follows asks for the same output.
- assert [request["max_output_tokens"] for request in sent] == [1024, 1024]
- assert result["probe"]["call"]["outcome"] == "verified"
-
-
-async def test_an_api_key_source_is_probed_on_a_passthrough_model_it_does_not_list(tmp_path):
- """MH-HOSTED-007: an API-key Source serves models discovery never listed, so such a hop can be probed and become
- native like any other; the Tools tab lists only what discovery found."""
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
-
- async with loopback_engine(tmp_path, service, respond):
- # A padded id is the model routing knows: the probe sends and records the canonical one.
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": " grok-4.7 "})
-
- request = sent[0]
- # The engine addresses a passthrough model through the Source's credential.
- assert request["model"].rsplit("/", 1)[-1] == "grok-4.7"
- assert result["probe"]["call"]["outcome"] == "verified"
- [record] = _records(service, CALL)
- assert (record.source_id, record.model_id, record.status) == (XAI.id, "grok-4.7", "verified")
- # The Tools tab lists only what discovery found, so it never counts a re-verify it has no candidate for.
- service.engine_stamp = "model-hub-engine-next"
- assert service.hosted_tools_status()["hosted_tools"]["reverify"] == {"engine_upgraded": 0, "aged": 0}
-
-
-async def test_a_probe_that_times_out_before_its_handle_is_still_metered(tmp_path, monkeypatch):
- """MH-HOSTED-007: a probe that times out after the engine observed billed wire facts, but before the call handed
- back its handle, still reaches the usage ledger: the provider billed it."""
- from core.handlers.model_hub import service as service_module
- from core.handlers.model_hub.adapter import InvokeCancelledError
- from core.handlers.model_hub.stream_wire import ProtocolSSEState
- from tests.test_model_hub_l3 import _usage_of
-
- monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 0.05)
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- observed = ProtocolSSEState("openai_responses")
- observed.observe(
- _sse({"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 1200, "output_tokens": 3}}}).encode()
- )
-
- async def stalls_after_admission(source_id, model_id, request, stream, origin, *, on_admitted=None):
- on_admitted()
- try:
- await asyncio.sleep(60)
- except asyncio.CancelledError:
- raise InvokeCancelledError(observed) from None
-
- service.adapter.invoke = stalls_after_admission
- service._engine_synced = True
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert result["probe"]["call"]["outcome"] == "transient"
- assert _usage_of(service, XAI.id)
-
-
-async def test_a_deadline_mid_stream_ends_the_probe_as_transient(tmp_path, monkeypatch):
- """MH-HOSTED-007: only the call's own task reads its stream, so a deadline that fires while the adapter waits
- for the next chunk ends the stream for the adapter and settles the call; the probe reports a transient failure."""
- from core.handlers.model_hub import service as service_module
-
- monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 0.5)
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
-
- async def respond(request):
- response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
- await response.prepare(request)
- await response.write(
- _sse(
- {"type": "response.created", "response": {"status": "in_progress"}},
- {"type": "response.output_item.added", "output_index": 0, "item": {**ANSWER, "status": "in_progress"}},
- {"type": "response.output_text.delta", "output_index": 0, "delta": "https://"},
- ).encode()
- )
- await asyncio.sleep(30)
- return response
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert result["probe"]["call"]["outcome"] == "transient"
- assert service.capability_evidence.records() == []
-
-
-async def test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_open(tmp_path, monkeypatch):
- """MH-HOSTED-007: once the adapter has the terminal event it closes the response, as production does, so the call
- settles as the success it was instead of waiting out the deadline with the body still open."""
- from core.handlers.model_hub import service as service_module
-
- monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 5)
- service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI, verification_pending="vp_" + "5" * 32)])
-
- async def respond(request):
- response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
- await response.prepare(request)
- await response.write(_responses(SEARCH, ANSWER).encode())
- await asyncio.sleep(30)
- return response
-
- async with loopback_engine(tmp_path, service, respond):
- started = asyncio.get_running_loop().time()
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
- elapsed = asyncio.get_running_loop().time() - started
-
- assert elapsed < 5
- assert result["probe"]["call"]["outcome"] == "verified"
- assert service.store.load().sources[0].verification_pending is None
- [record] = _records(service, CALL)
- assert record.status == "verified"
-
-
-PNG = (
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
-)
-
-
- "result,outcome",
- [
- (PNG, "verified"),
- ("bm90IGFuIGltYWdl", "inconclusive"),
- # A BMP is an image, but not one a turn's sink keeps, so it proves nothing a turn could use.
- (base64.b64encode(b"BM" + bytes(52)).decode(), "inconclusive"),
- ],
- ids=["image", "not-an-image", "bmp"],
-)
-async def test_an_image_probe_verifies_only_an_image_vibey_could_keep(tmp_path, result, outcome):
- """MH-HOSTED-007: the image call probe reads the generated image through Vibey's own parsing, which keeps it
- only when it is an image; a probe keeps no file, and an image has no replay."""
- openai = _source("src_probe0009", "OpenAI 密钥", vendor="openai", protocol="openai_responses", model_id="gpt-6-astra")
- service, _clock, _models = configured_service(tmp_path, sources=[openai])
- sent = []
- image_call = {
- "id": "ig_1",
- "type": "image_generation_call",
- "status": "completed",
- "result": result,
- "revised_prompt": "A blue circle on a white background",
- "size": "1024x1024",
- }
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(image_call))
-
- async with loopback_engine(tmp_path, service, respond):
- result_payload = await service.probe_hosted_tool("image_generation", {"source_id": openai.id, "model_id": "gpt-6-astra"})
-
- [request] = sent
- declaration = hosted_tool_spec("openai", "openai_responses", "gpt-6-astra", "image_generation").declaration
- assert request["tools"] == [declaration] and request["tool_choice"] == "required"
- probe = result_payload["probe"]
- _assert_valid("hosted-tool-probe-result.schema.json", probe)
- assert (probe["call"]["outcome"], probe["replay"]) == (outcome, None)
- records = _records(service, EvidenceFeature.hosted("image_generation", "call"))
- assert [record.status for record in records] == (["verified"] if outcome == "verified" else [])
-
-
-REPLAY_CASES = [
- # (case, Source, the call's response, the replay's response or status and body, replay outcome, record)
- ("names-a-result", XAI, _responses(SEARCH, ANSWER), "answer-from-payload", "verified", "verified"),
- ("anthropic-names-a-result", ANTHROPIC, ANTHROPIC_SEARCH, "answer-from-payload", "verified", "verified"),
- # Restating the answer it already gave proves nothing: that text came back in the visible transcript.
- ("restates-the-visible-answer", XAI, _responses(SEARCH, ANSWER), _responses_text("https://avibe.bot/"), "inconclusive", None),
- # A URL that only starts like the hidden result is a different URL, and so is one with another fragment.
- ("names-a-longer-url", XAI, _responses(SEARCH, ANSWER), _responses_text(HIDDEN + "-old"), "inconclusive", None),
- ("names-another-fragment", XAI, _responses(SEARCH, ANSWER), _responses_text(HIDDEN + "#other"), "inconclusive", None),
- # Linked text names the result as surely as the URL written out.
- ("cites-the-result", XAI, _responses(SEARCH, ANSWER), _responses({
- "id": "msg_2",
- "type": "message",
- "content": [{
- "type": "output_text",
- "text": "The hosted tools docs.",
- "annotations": [{"type": "url_citation", "url": HIDDEN, "start_index": 4, "end_index": 21, "title": "docs"}],
- }],
- }), "verified", "verified"),
- # A refusal is inconclusive, even one that quotes the result.
- ("refuses-quoting-the-result", XAI, _responses(SEARCH, ANSWER), REFUSAL, "inconclusive", None),
- # The way a sentence ends a URL does not change it.
- ("names-it-in-a-sentence", XAI, _responses(SEARCH, ANSWER), _responses_text(f"The other one was {HIDDEN}."), "verified", "verified"),
- # Searching again instead of using the results it holds is what a dropped replay looks like.
- ("searches-again", XAI, _responses(SEARCH, ANSWER), _responses(SEARCH, ANSWER), "unsupported", "unsupported"),
- ("names-no-result", XAI, _responses(SEARCH, ANSWER), _responses_text("I can't tell."), "inconclusive", None),
- (
- "anthropic-refuses-the-replayed-result",
- ANTHROPIC,
- ANTHROPIC_SEARCH,
- (400, {"type": "error", "error": {"type": "invalid_request_error", "message": "Invalid encrypted_content in search_result block"}}),
- "unsupported",
- "unsupported",
- ),
-]
-
-
- "source,first,second,outcome,written", [case[1:] for case in REPLAY_CASES], ids=[case[0] for case in REPLAY_CASES]
-)
-async def test_a_verified_call_is_followed_by_the_replay_probe(tmp_path, source, first, second, outcome, written):
- """MH-HOSTED-007 (§3.2, §12 item 23): the replay probe sends the call's turn back with its native payload in
- place, asks for a result it returned, and records only a named result, a new call or a refusal of the payload."""
- service, _clock, _models = configured_service(tmp_path, sources=[source])
- model_id = source.models[0].id
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- if len(sent) == 1:
- return _stream(first)
- if isinstance(second, tuple):
- return web.json_response(second[1], status=second[0])
- if second == "answer-from-payload":
- return _stream(_replay_reply(source.protocol, sent[-1]))
- return _stream(second)
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": source.id, "model_id": model_id})
-
- call, replay = sent
- # The native declaration is still present, nothing is forced, and the call's own items go back verbatim.
- assert replay["tools"] == call["tools"] and "tool_choice" not in replay
- # Its instructions ask for an answer from the results it holds, never for the call the question rules out.
- system = "instructions" if source.protocol == "openai_responses" else "system"
- assert replay[system] != call[system] and "without using any tool" in json.dumps(replay[system])
- native = SEARCH if source.protocol == "openai_responses" else {"type": "web_search_tool_result"}
- assert json.dumps(native["type"]) in json.dumps(replay)
- assert "other results you found" in json.dumps(replay)
- assert HIDDEN in json.dumps(replay)
- probe = result["probe"]
- _assert_valid("hosted-tool-probe-result.schema.json", probe)
- assert probe["call"]["outcome"] == "verified"
- assert probe["replay"]["outcome"] == outcome
- # Every reply here completed (or named the payload in a refusal): the verdict is read from it, not from a failure.
- assert probe["replay"]["error"] is None
- assert [record.status for record in _records(service, REPLAY)] == ([written] if written else [])
-
-
-async def test_a_replay_sends_the_results_only_in_their_native_payload(tmp_path):
- """MH-HOSTED-007: the call's reasoning, readable or encrypted, can restate a result; it never goes back with the
- replay, so a Source that drops the payload has nowhere else to read the result from."""
- reasoning = {
- "id": "rs_1",
- "type": "reasoning",
- "summary": [{"type": "summary_text", "text": f"The results were https://avibe.bot/ and {HIDDEN}."}],
- "encrypted_content": "opaque-reasoning",
- }
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(reasoning, SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
-
- async with loopback_engine(tmp_path, service, respond):
- await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- replay = sent[1]
- elsewhere = [item for item in replay["input"] if item.get("type") != "web_search_call"]
- assert any(item.get("type") == "web_search_call" for item in replay["input"])
- assert HIDDEN not in json.dumps(elsewhere) and "reasoning" not in json.dumps(elsewhere)
-
-
-async def test_no_replay_runs_when_the_visible_answer_shows_every_result(tmp_path):
- """MH-HOSTED-007: a replay is proved only by a result the visible answer does not show; with none, no replay is
- spent, and the replay stays unknown, so turns replay synthetically."""
- single = {**SEARCH, "action": {**SEARCH["action"], "sources": [{"type": "url", "url": "https://avibe.bot/"}]}}
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(single, ANSWER))
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert len(sent) == 1
- assert (result["probe"]["call"]["outcome"], result["probe"]["replay"]) == ("verified", None)
- assert _records(service, REPLAY) == []
-
-
-async def test_a_replay_the_probe_has_no_time_left_for_reports_try_again(tmp_path, monkeypatch):
- """MH-HOSTED-007: the whole probe answers inside the UI's RPC wait; a replay that could not finish in what is left
- is not sent, and reads as a transient failure to try again."""
- from core.handlers.model_hub import service as service_module
-
- monkeypatch.setattr(service_module, "PROBE_BUDGET_SECONDS", 30.0)
- service, _clock, _models = configured_service(tmp_path, sources=[XAI])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(SEARCH, ANSWER))
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert len(sent) == 1
- assert result["probe"]["replay"] == {"outcome": "transient", "error": None}
- assert _records(service, REPLAY) == []
-
-
-async def test_a_replay_goes_only_to_the_source_identity_the_call_was_recorded_for(tmp_path, monkeypatch):
- """MH-HOSTED-007: the replay carries the call's provider-native payload, so a Source whose endpoint or credential
- changed after the call never receives it; the call's result stands and no replay is reported."""
- from core.handlers.model_hub import service as service_module
-
- # The fixture store keeps the Source object it is given, and this test edits it.
- service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI)])
- sent = []
- build_replay = service_module.hosted_replay_request
-
- def replaced_endpoint_first(*args, **kwargs):
- config = service.store.load()
- config.sources[0].base_url = "https://relay.invalid/v1"
- service.store.save(config)
- return build_replay(*args, **kwargs)
-
- monkeypatch.setattr(service_module, "hosted_replay_request", replaced_endpoint_first)
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
-
- async with loopback_engine(tmp_path, service, respond):
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert len(sent) == 1
- assert (result["probe"]["call"]["outcome"], result["probe"]["replay"]) == ("verified", None)
- assert [record.status for record in _records(service, CALL)] == ["verified"]
- assert _records(service, REPLAY) == []
-
-
- "stop_reason,text,outcome",
- [
- ("stop", HIDDEN, "verified"),
- ("safety", HIDDEN, "inconclusive"),
- ("refusal", HIDDEN, "inconclusive"),
- # Provider text that is not a well-formed URL compares as written and never fails the probe.
- ("stop", "https://[invalid", "inconclusive"),
- ],
-)
-def test_a_replay_answer_counts_only_when_it_completed_and_names_a_hidden_result(stop_reason, text, outcome):
- """MH-HOSTED-007: a blocked or refused answer proves nothing, whatever it quotes, and a malformed URL is just text."""
- assert _replay_verdict(text, {HIDDEN, "https://[also-invalid"}, stop_reason=stop_reason) == outcome
-
-
-WIKI = "https://en.wikipedia.org/wiki/Search_(computing)"
-
-
- "asked,text,outcome",
- [
- # Prose and Markdown around a URL do not change it.
- (HIDDEN, f"See [the docs]({HIDDEN}).", "verified"),
- (HIDDEN, f"**{HIDDEN}**", "verified"),
- (WIKI, f"It is {WIKI}.", "verified"),
- (WIKI, f"(see {WIKI})", "verified"),
- # A result's own URL is exact: an answer without the punctuation it ends in names another URL.
- (HIDDEN + "!", f"It is {HIDDEN}, I think.", "inconclusive"),
- (HIDDEN + "!", f"It is {HIDDEN}!.", "verified"),
- (WIKI, "https://en.wikipedia.org/wiki/Search_", "inconclusive"),
- # Only the scheme and host are case-insensitive; a trailing slash or another user name is another URL.
- ("https://Example.COM/result", "HTTPS://example.com/result", "verified"),
- ("https://Alice:[email protected]/result", "https://alice:[email protected]/result", "inconclusive"),
- (HIDDEN, f"It is {HIDDEN}/", "inconclusive"),
- ],
-)
-def test_a_replay_answer_names_a_result_by_its_exact_url(asked, text, outcome):
- """MH-HOSTED-007: only where prose ends a written URL is ambiguous; the result's URL is never trimmed."""
- assert _replay_verdict(text, {asked}) == outcome
-
-
-def test_a_result_the_answer_shows_in_any_reading_is_not_hidden():
- """MH-HOSTED-007: a shown result taken for hidden could verify a replay that only restated the visible answer."""
- from core.agent_core.messages import (
- AssistantMessage, HostedAction, HostedNative, HostedRecord, HostedSource, HostedSummary, HostedToolBlock, Origin,
- TextBlock,
- )
- from core.handlers.model_hub.hosted_probe import hidden_result_urls
-
- call = HostedToolBlock(
- id="ws_1",
- tool="web_search",
- action=HostedAction(type="search", queries=("avibe",)),
- record=HostedRecord(status="completed", sources=(HostedSource(url=HIDDEN + "."), HostedSource(url=WIKI))),
- native=HostedNative(source_id=XAI.id, payload=({"type": "web_search_call", "id": "ws_1"},)),
- )
- for text, hidden in [
- (f"Read {HIDDEN}", {WIKI}),
- (f"Read {WIKI}.", {HIDDEN + "."}),
- (f"Read {WIKI}/", {HIDDEN + "."}),
- ("Read none", {HIDDEN + ".", WIKI}),
- ]:
- answer = AssistantMessage(
- content=(call, TextBlock(text=text)),
- origin=Origin("xai", "openai_responses", "grok-4.6"),
- stop_reason="stop",
- hosted_summary=HostedSummary(),
- )
- assert hidden_result_urls(answer) == hidden
-
-
-def _replay_verdict(text, asked, *, stop_reason="stop"):
- from core.agent_core.ai.provider import Done
- from core.agent_core.messages import AssistantMessage, Origin, TextBlock
- from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
- from core.handlers.model_hub.hosted_probe import replay_outcome
-
- answer = AssistantMessage(
- content=(TextBlock(text=text),), origin=Origin("xai", "openai_responses", "grok-4.6"), stop_reason=stop_reason,
- )
- ok = RawCallOutcome(RawOutcomeKind.SUCCESS, 200, None, None, True, "grok-4.6", XAI.id)
- return replay_outcome("web_search", Done(answer), ok, None, asked=frozenset(asked), carried=True)
-
-
-async def test_a_re_probe_restores_replay_a_narrow_rule_demoted(tmp_path):
- """MH-HOSTED-007: a 400 on a replayed payload teaches 'replay unsupported' for this Source, also when the payload
- was minted under an identity it had before (a wrong attribution: it refuses a foreign blob, not replay). That
- record expires on its own and never outlives a user's re-probe, which replaces it."""
- service, clock, _models = configured_service(tmp_path, sources=[XAI])
- sent = []
-
- async def respond(request):
- sent.append(await request.json())
- return _stream(_responses(SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
-
- async with loopback_engine(tmp_path, service, respond):
- [live] = service.store.load().sources
- service.capability_evidence.write(
- EvidenceRecord(
- source_id=XAI.id,
- model_id="grok-4.6",
- feature=REPLAY,
- status="unsupported",
- basis="observed",
- observed_at=clock.now(),
- engine=service.engine_stamp,
- shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(live),
- detail="400 invalid_request_error",
- ),
- live=[live],
- )
- result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
-
- assert result["probe"]["replay"]["outcome"] == "verified"
- [record] = _records(service, REPLAY)
- assert (record.status, record.basis) == ("verified", "probe")
diff --git a/tests/test_model_hub_hosted_tools_config.py b/tests/test_model_hub_hosted_tools_config.py
index 69a22665b..d3a207022 100644
--- a/tests/test_model_hub_hosted_tools_config.py
+++ b/tests/test_model_hub_hosted_tools_config.py
@@ -1,21 +1,27 @@
-"""V2 ``model_hub.hosted_tools`` (``vibey-hosted-tools.md`` §3.3, §12 item 8).
+"""V2 ``model_hub.hosted_tools`` (``vibey-hosted-tools.md`` §3.3, §12).
-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.
+Hosted tools are an optional feature inside the Model Hub section. Absence
+means every tool is on, an rc-era section keeps each tool's ``enabled``, and a
+broken entry takes only its own defaults: 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 config.v2_config import (
+ ModelHubConfig,
+ ModelHubHostedToolConfig,
+ ModelHubImageModelChoice,
+ V2Config,
+)
+from core.handlers.model_hub.capability_evidence import EvidenceFeature
+from core.handlers.model_hub.hosted_tools import enabled_tools
from core.services.settings import default_config
from vibe import api
@@ -33,6 +39,7 @@ SOURCE = {
"created_at": "2026-10-13T00:00:00Z",
"credential_ref": "cred_src_xai00001",
}
+ALL_TOOLS = ("web_search", "x_search", "image_generate")
def _section(hosted_tools) -> dict:
@@ -42,65 +49,79 @@ def _section(hosted_tools) -> dict:
return section
-def test_released_configs_load_with_every_tool_off_and_stay_without_the_section():
+def test_released_configs_load_with_every_tool_on_and_stay_without_the_section():
+ """MH-HOSTED-002: an upgrade from 3.2.0 turns every tool on without writing a section (owner decision)."""
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 enabled_tools(config) == ALL_TOOLS
assert "hosted_tools" not in config.to_payload()
-def test_hosted_tool_toggles_round_trip_in_canonical_order():
+def test_hosted_tool_settings_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"}},
+ "image_generate": {"enabled": True, "default_model": {"source_id": "src_xai00001", "model_id": "grok-imagine-image"}},
+ "x_search": {"enabled": False},
+ "web_search": {"enabled": True, "executor_order": ["src_gone0001", "src_xai00001"]},
}
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),
+ "web_search": ModelHubHostedToolConfig(True, ("src_gone0001", "src_xai00001")),
+ "x_search": ModelHubHostedToolConfig(False),
+ "image_generate": ModelHubHostedToolConfig(
+ True, default_image=ModelHubImageModelChoice("src_xai00001", "grok-imagine-image"),
+ ),
}
- assert list(config.to_payload()["hosted_tools"]) == ["web_search", "x_search"]
+ assert list(config.to_payload()["hosted_tools"]) == list(ALL_TOOLS)
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)
+# (case, raw section, tools that survive as (enabled, executor_order, default_model), whether a warning is logged)
+OFF = (False, None, None)
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),
+ # Damage never turns a cost-bearing tool on: a broken section or entry is off (AGENTS persisted-shape rule).
+ ("not-an-object", ["web_search"], dict.fromkeys(ALL_TOOLS, OFF), True),
+ # Present but null is damage, not absence.
+ ("null-section", None, dict.fromkeys(ALL_TOOLS, OFF), True),
+ # An rc build's section: its keys and fields are unknown to v2, but each tool's opt-out survives.
(
- "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,
+ "rc-era-section",
+ {
+ "web_search": {"enabled": False, "executor": {"source_id": "src_xai00001", "model_id": "grok-4.6"}},
+ "image_generation": {"enabled": False, "executor": None},
+ },
+ {"web_search": OFF},
+ True,
),
+ ("unknown-tool", {"code_interpreter": {"enabled": False}, "x_search": {"enabled": False}}, {"x_search": OFF}, True),
+ ("field-of-another-tool", {"image_generate": {"enabled": False, "executor_order": ["src_xai00001"]}}, {"image_generate": OFF}, True),
+ ("non-boolean-enabled", {"web_search": {"enabled": "yes"}}, {"web_search": OFF}, True),
+ ("repeated-order", {"web_search": {"executor_order": ["src_xai00001", "src_xai00001"]}}, {"web_search": OFF}, True),
+ ("order-not-a-source-id", {"web_search": {"executor_order": [" src_xai00001"]}}, {"web_search": OFF}, True),
+ ("bad-default-shape", {"image_generate": {"default_model": {"source_id": "src_xai00001"}}}, {"image_generate": OFF}, True),
+ ("default-not-encodable", {"image_generate": {"default_model": {"source_id": "src_xai00001", "model_id": "x\ud800"}}}, {"image_generate": OFF}, True),
+ # Saved values are never resolved: an order naming a Source that is gone is kept and skipped when read.
+ ("order-source-gone", {"web_search": {"executor_order": ["src_gone0001"]}}, {"web_search": (True, ("src_gone0001",), None)}, False),
+ ("entry-not-an-object", {"x_search": None}, {"x_search": OFF}, True),
]
@pytest.mark.parametrize("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."""
+def test_a_broken_hosted_tool_entry_turns_off_only_its_tool(raw, expected, warns, caplog):
+ """MH-HOSTED-002: a broken entry turns its tool off and an unknown field is ignored; Sources and Agents 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 {
+ tool: (entry.enabled, entry.executor_order, entry.default_image) 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})
+ payload["model_hub"] = _section({"web_search": {"enabled": 1}, "x_search": {"enabled": False}})
config_path = tmp_path / "config.json"
original = json.dumps(payload)
config_path.write_text(original, encoding="utf-8")
@@ -109,17 +130,11 @@ def test_disk_load_with_a_broken_hosted_tools_section_keeps_model_hub(monkeypatc
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 enabled_tools(loaded.model_hub) == ("image_generate",)
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 _validate_status(status):
from jsonschema import Draft7Validator
@@ -130,67 +145,191 @@ def _validate_status(status):
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)
+ store.config = ModelHubConfig.from_payload({"sources": [SOURCE]})
return service, store
@pytest.mark.asyncio
-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."""
+async def test_the_tools_api_writes_one_field_of_one_tool_at_a_time(tmp_path):
+ """MH-HOSTED-004: a write changes only the fields it names; 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")
- ]
- # The cost hint: the overlay's dated list price and the Source's billing, never a computed zero.
- assert x_search["bound"] is None
- assert x_search["candidates"][0]["billing"] == "metered"
- assert x_search["candidates"][0]["price"] == {
+ _validate_status(status)
+ by_name = {tool["name"]: tool for tool in status["tools"]}
+ assert list(by_name) == list(ALL_TOOLS) and all(tool["enabled"] for tool in status["tools"])
+ # The executor runs on the vendor's lightweight model, priced by the overlay's dated list price.
+ (candidate,) = by_name["x_search"]["executor_candidates"]
+ assert (candidate["source_id"], candidate["model_id"], candidate["billing"], candidate["relay"]) == (
+ "src_xai00001", "grok-4.20-0309-non-reasoning", "metered", False,
+ )
+ assert candidate["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",
}
- _validate_status(status)
- 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})
+ await service.set_hosted_tool("x_search", {"executor_order": ["src_xai00001"]})
+ written = await service.set_hosted_tool("x_search", {"enabled": False})
after = store.config.to_payload()
- assert after.pop("hosted_tools") == {"x_search": {"enabled": True, "executor": executor}}
+ assert after.pop("hosted_tools") == {"x_search": {"enabled": False, "executor_order": ["src_xai00001"]}}
assert after == before
- assert next(tool for tool in written["hosted_tools"]["tools"] if tool["name"] == "x_search")["executor"] == executor
+ _validate_status(written["hosted_tools"])
+ await service.set_hosted_tool("x_search", {"executor_order": None})
+ assert store.config.to_payload()["hosted_tools"] == {"x_search": {"enabled": False}}
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),
+ ("image_generation", {"enabled": True}, "hosted_tool_not_found", 404),
+ ("web_search", {}, "invalid_parameter", 400),
+ ("web_search", {"default_model": None}, "invalid_parameter", 400),
+ ("web_search", {"enabled": True, "executor": None}, "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}}
+ assert store.config.to_payload()["hosted_tools"] == {"x_search": {"enabled": False}}
+
+
+def _refuse(service, source, model_id, feature):
+ from core.handlers.model_hub.capability_evidence import EvidenceRecord, identity_digest
+
+ evidence = service.hosted_evidence()
+ service.capability_evidence.write_refusal(
+ EvidenceRecord(
+ source_id=source.id, model_id=model_id, feature=feature, status="unsupported",
+ observed_at=service.now(), wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source), detail="400 invalid_request_error",
+ ),
+ live=[source],
+ )
+
+
+async def test_a_clear_removes_only_the_refusals_it_names(tmp_path):
+ """MH-HOSTED-003: the user clears a refusal; it is gone at once and the next request tries the feature again."""
+ from core.handlers.model_hub.service import ModelHubError
+
+ service, store = _api_service(tmp_path)
+ (source,) = store.config.sources
+ executor = "grok-4.20-0309-non-reasoning"
+ for model_id in ("grok-4.6", executor):
+ _refuse(service, source, model_id, EvidenceFeature.hosted("x_search", "call"))
+ _refuse(service, source, "grok-4.6", EvidenceFeature.hosted("web_search", "replay"))
+ _refuse(service, source, "grok-4.6", EvidenceFeature.effort("max"))
+
+ def refused(tool):
+ status = service.hosted_tools_status()["hosted_tools"]
+ tool = next(item for item in status["tools"] if item["name"] == tool)
+ return sorted((item["model_id"], item["aspect"]) for item in tool["status"]["refused"])
+
+ assert refused("x_search") == [("grok-4.20-0309-non-reasoning", "call"), ("grok-4.6", "call")]
+ cleared = await service.clear_hosted_refusals("x_search", {"source_id": source.id, "model_id": executor})
+ _validate_status(cleared["hosted_tools"])
+ assert refused("x_search") == [("grok-4.6", "call")]
+ await service.clear_hosted_refusals("x_search", {})
+ assert refused("x_search") == [] and refused("web_search") == [("grok-4.6", "replay")]
+
+ answer = await service.clear_source_evidence(source.id, {"model_id": "grok-4.6", "feature": {"kind": "effort", "name": "max"}})
+ assert answer["source"]["id"] == source.id
+ assert not service.hosted_evidence().unsupported(source, "grok-4.6", EvidenceFeature.effort("max"))
+ assert refused("web_search") == [("grok-4.6", "replay")]
+
+ for call, code, status_code in [
+ (service.clear_hosted_refusals("image_generation", {}), "hosted_tool_not_found", 404),
+ # Nothing is nullable: a malformed body is refused, never widened into a broader clear.
+ (service.clear_hosted_refusals("x_search", {"source_id": None}), "invalid_parameter", 400),
+ (service.clear_hosted_refusals("x_search", {"source_id": source.id, "model_id": None}), "invalid_parameter", 400),
+ (service.clear_hosted_refusals("x_search", {"source_id": source.id, "model_id": " grok-4.6"}), "invalid_parameter", 400),
+ (service.clear_source_evidence(source.id, {"model_id": "grok-4.6 ", "feature": {"kind": "effort", "name": "max"}}), "invalid_parameter", 400),
+ # The feature is exactly the shape the evidence writes: an effort has no aspect, not even a null one.
+ (service.clear_source_evidence(source.id, {"model_id": "grok-4.6", "feature": {"kind": "effort", "name": "max", "aspect": None}}), "invalid_parameter", 400),
+ (service.clear_hosted_refusals("x_search", {"model_id": executor}), "invalid_parameter", 400),
+ (service.clear_hosted_refusals("x_search", {"source_id": ""}), "invalid_parameter", 400),
+ (service.clear_source_evidence("src_gone0001", {"model_id": "grok-4.6", "feature": {"kind": "effort", "name": "max"}}), "source_not_found", 404),
+ (service.clear_source_evidence(source.id, {"model_id": "grok-4.6", "feature": {"kind": "hosted_tool", "name": "x_search", "aspect": "call"}}), "invalid_parameter", 400),
+ ]:
+ with pytest.raises(ModelHubError) as refusal:
+ await call
+ assert (refusal.value.code, refusal.value.status) == (code, status_code)
+
+
+async def test_a_clear_that_cannot_be_saved_changes_nothing(tmp_path, monkeypatch):
+ """MH-HOSTED-003: a failed write answers 500 and the refusal still holds, so nothing reappears after a restart."""
+ from core.handlers.model_hub import capability_evidence
+ from core.handlers.model_hub.service import ModelHubError
+
+ service, store = _api_service(tmp_path)
+ (source,) = store.config.sources
+ feature = EvidenceFeature.hosted("x_search", "call")
+ _refuse(service, source, "grok-4.6", feature)
+
+ def full_disk(*_args):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(capability_evidence, "write_state_document", full_disk)
+ with pytest.raises(ModelHubError) as refusal:
+ await service.clear_hosted_refusals("x_search", {})
+ assert (refusal.value.code, refusal.value.status) == ("state_write_failed", 500)
+ assert service.hosted_evidence().unsupported(source, "grok-4.6", feature)
+
+
+async def test_a_clear_waits_for_a_source_change_in_flight(tmp_path):
+ """MH-HOSTED-003: a clear runs after a concurrent Source change commits, so it keeps evidence under the identity
+ the config now holds and answers the Source as it now is."""
+ import asyncio
+ from dataclasses import replace
+
+ service, store = _api_service(tmp_path)
+ (source,) = store.config.sources
+ _refuse(service, source, "grok-4.6", EvidenceFeature.effort("max"))
+ body = {"model_id": "grok-4.6", "feature": {"kind": "effort", "name": "max"}}
+
+ async with service._mutation_lock:
+ clearing = asyncio.create_task(service.clear_source_evidence(source.id, body))
+ await asyncio.sleep(0.05)
+ assert not clearing.done()
+ store.config.sources = [replace(source, display_name="xAI 工作密钥")]
+ answer = await clearing
+ assert answer["source"]["display_name"] == "xAI 工作密钥"
+
+
+ "prices,expected",
+ [
+ ((), None),
+ # A price for one size or quality is not every image's: the card shows no unit price rather than a wrong one.
+ ((("1024x1024", "low", 11),), None),
+ ((("1024x1024", "low", 11), (None, None, 20)), {"usd": 0.02, "basis": "list"}),
+ ],
+ ids=["unpriced", "conditional-only", "unqualified"],
+)
+def test_an_image_models_card_price_is_only_an_unqualified_list_price(tmp_path, monkeypatch, prices, expected):
+ """MH-HOSTED-004: gpt-image-2's prices vary by size and quality, so its card reads "no unit price" (owner rule)."""
+ from datetime import date
+
+ from core.handlers.model_hub import hosted_tools as hosted_tools_module
+ from vibe.backend_model_catalog import HostedToolPrice, ImageModelPrice, ImageModelSpec
+
+ spec = ImageModelSpec(
+ "gpt-image-2", "OpenAI image model", "images", ("images", "size"), ("pixels",),
+ tuple(
+ ImageModelPrice(HostedToolPrice("image", usd, date(2026, 10, 15), "https://openai.com/api/pricing"), size, quality)
+ for size, quality, usd in prices
+ ),
+ )
+ monkeypatch.setattr(hosted_tools_module, "provider_image_models", lambda vendor: (spec,) if vendor == "xai" else ())
+ service, _store = _api_service(tmp_path)
+ status = service.hosted_tools_status()["hosted_tools"]
+ _validate_status(status)
+ image = next(tool for tool in status["tools"] if tool["name"] == "image_generate")
+ assert [model["price"] for model in image["models"]] == [expected]
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index 43dce596c..0e5c4ec3f 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -1,15 +1,15 @@
-"""Hosted-tool hop resolution (``vibey-hosted-tools.md`` §3.4, §3.5; §12 items 7, 14, 19, 20).
+"""Hosted-tool facts, the executor chain, the image enum and the Tools read (``vibey-hosted-tools.md`` §3.3–§3.4, §6,
+§7.2).
-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.
+Nothing is probed: a tool the overlay offers is assumed on a hop until a real
+request refuses it, and these functions are the one place that decides so.
"""
from __future__ import annotations
import json
from dataclasses import replace
-from datetime import datetime, timezone
+from datetime import date, datetime, timezone
import pytest
@@ -17,43 +17,75 @@ from config.v2_config import (
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubHostedToolConfig,
+ ModelHubImageModelChoice,
ModelHubModelConfig,
- ModelHubRouteHopConfig,
ModelHubSourceConfig,
ModelHubSourceStateConfig,
)
+from core.handlers.model_hub import hosted_tools as hosted_tools_module
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
+from core.handlers.model_hub.hosted_tools import (
+ HostedEvidence,
+ HostedToolSettingRefused,
+ apply_hosted_tool_put,
+ executor_candidates,
+ hosted_tool_facts,
+ hosted_tools_status,
+ image_choices,
+ resolve_hosted_tools,
+)
+from vibe.backend_model_catalog import HostedToolPrice, HostedToolSpec, ImageModelPrice, ImageModelSpec
-NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
-ENGINE = "model-hub-engine-v8.0.23-3"
+NOW = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)
+ENGINE, AVIBE = "model-hub-engine-v8.0.23-3", "3.2.1"
+SEARCH_PRICE = HostedToolPrice(unit="call", usd_per_1k=5, as_of=date(2026, 10, 13), url="https://docs.x.ai/pricing")
-def _spec(declaration: dict, include: tuple[str, ...] = ()) -> HostedToolSpec:
- return HostedToolSpec(declaration_json=json.dumps(declaration), price=None, include=include)
+def _spec(declaration: dict, include: tuple[str, ...] = (), price=None) -> HostedToolSpec:
+ return HostedToolSpec(declaration_json=json.dumps(declaration), price=price, include=include)
SPECS = {
- ("xai", "openai_responses", "web_search"): _spec({"type": "web_search"}),
+ ("xai", "openai_responses", "web_search"): _spec({"type": "web_search"}, price=SEARCH_PRICE),
("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"}),
}
+EXECUTOR_MODELS = {"xai": "grok-fast", "openai": "gpt-mini", "anthropic": "claude-haiku"}
+
+
+def _image(model_id: str, description: str, *, price: float | None = None) -> ImageModelSpec:
+ prices = (
+ (ImageModelPrice(HostedToolPrice("image", price * 1000, date(2026, 10, 15), "https://docs.x.ai/pricing")),)
+ if price is not None
+ else ()
+ )
+ return ImageModelSpec(model_id, description, "images", ("images", "size"), ("pixels",), prices)
+
+
+IMAGE_MODELS = {
+ "openai": (_image("gpt-image-2", "OpenAI's image model"),),
+ "xai": (_image("grok-imagine-image", "Grok Imagine", price=0.02),),
+}
+
+
[email protected](autouse=True)
+def _overlay(monkeypatch):
+ monkeypatch.setattr(hosted_tools_module, "provider_executor_model", EXECUTOR_MODELS.get)
+ monkeypatch.setattr(hosted_tools_module, "provider_image_models", lambda vendor: IMAGE_MODELS.get(vendor, ()))
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:
+def _source(source_id, vendor, protocol, model_id, *, kind="api_key", base_url=None) -> ModelHubSourceConfig:
return ModelHubSourceConfig(
id=source_id,
kind=kind,
@@ -65,182 +97,269 @@ def _source(source_id, vendor, protocol, model_id, *, kind="api_key") -> ModelHu
state=ModelHubSourceStateConfig(status="standby"),
models=[ModelHubModelConfig(id=model_id, provenance="discovered")],
credential_ref=f"cred_{source_id}",
+ base_url=base_url,
)
XAI = _source("src_xai00001", "xai", "openai_responses", "grok-4.6")
-OPENAI = _source("src_oai00001", "openai", "openai_responses", "gpt-6-astra")
+OPENAI = _source("src_oai00001", "openai", "openai_responses", "gpt-6-astra", base_url="https://relay.example/v1")
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:
+def _config(tools: dict[str, ModelHubHostedToolConfig] | None = None, sources=ALL) -> 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)
+ vibey = replace(vibey, sources=replace(vibey.sources, order=[source.id for source in sources]))
+ config = ModelHubConfig(sources=list(sources), hosted_tools=tools or {})
config.agents["vibey"] = vibey
return config
-def _store(tmp_path, *verified, engine=ENGINE) -> CapabilityEvidenceStore:
+def _evidence(tmp_path, *refused) -> HostedEvidence:
+ """Evidence holding a current refusal for each (source, model_id, tool, aspect)."""
+
store = CapabilityEvidenceStore(tmp_path / "evidence.json")
- for source, tool, aspect in verified:
- store.write(
+ evidence = HostedEvidence(store, ENGINE, AVIBE)
+ for source, model_id, tool, aspect in refused:
+ store.write_refusal(
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),
+ source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted(tool, aspect),
+ status="unsupported", observed_at=NOW, wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source), detail="400 invalid_request_error",
),
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,
- )
-
+ return evidence
-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},
- }
+ "primary,tool,refused,native,replay",
+ [
+ # The overlay offers it and nothing refused it: assumed, with no evidence at all.
+ (XAI, "web_search", (), "assumed", "assumed"),
+ (XAI, "web_search", ((XAI, "grok-4.6", "web_search", "replay"),), "assumed", "unsupported"),
+ (XAI, "web_search", ((XAI, "grok-4.6", "web_search", "call"),), "unsupported", "unsupported"),
+ # OpenAI offers no X search: the function, whatever the evidence.
+ (OPENAI, "x_search", (), "unsupported", "unsupported"),
+ (CLAUDE_SUB, "web_search", (), "unsupported", "unsupported"),
+ (GEMINI, "web_search", (), "unsupported", "unsupported"),
+ ],
+ ids=["assumed", "replay-refused", "call-refused", "not-offered", "claude-subscription-never", "translated-never"],
+)
+def test_a_hops_facts_come_from_priors_and_refusals(tmp_path, primary, tool, refused, native, replay):
+ """MH-HOSTED-001: nothing is probed; a tool is assumed where offered until a real request refuses it."""
+ facts = hosted_tool_facts(
+ primary, primary.models[0].id, tool, evidence=_evidence(tmp_path, *refused), spec_for=_spec_for,
+ )
+ assert (facts.native, facts.replay) == (native, replay)
+ assert (facts.declaration is not None) is (native == "assumed")
-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"),
+def test_the_executor_chain_follows_the_users_order_then_vibeys(tmp_path):
+ """MH-HOSTED-001: Sources whose vendor offers the tool, each on its vendor's executor model; a refused pair and
+ a Claude subscription never are candidates."""
+ evidence = _evidence(tmp_path)
+ chain = executor_candidates(_config(), "web_search", evidence=evidence, spec_for=_spec_for)
+ assert [(candidate.source.id, candidate.model_id) for candidate in chain] == [
+ ("src_xai00001", "grok-fast"), ("src_oai00001", "gpt-mini"),
+ ]
+ ordered = _config({"web_search": ModelHubHostedToolConfig(executor_order=("src_oai00001", "src_gone00001"))})
+ assert [candidate.source.id for candidate in executor_candidates(
+ ordered, "web_search", evidence=evidence, spec_for=_spec_for,
+ )] == ["src_oai00001", "src_xai00001"]
+ refused = _evidence(tmp_path / "r", (XAI, "grok-fast", "web_search", "call"))
+ assert [candidate.source.id for candidate in executor_candidates(
+ _config(), "web_search", evidence=refused, spec_for=_spec_for,
+ )] == ["src_oai00001"]
+
+
+def test_the_image_enum_is_deterministic_with_the_default_first(tmp_path):
+ """MH-HOSTED-001: a pure function of config and current refusals: the default first, the rest by id."""
+ evidence = _evidence(tmp_path)
+ choices = image_choices(_config(), evidence=evidence)
+ assert [choice.model_id for choice in choices.models] == ["grok-imagine-image", "gpt-image-2"]
+ saved = _config({"image_generate": ModelHubHostedToolConfig(
+ default_image=ModelHubImageModelChoice("src_oai00001", "gpt-image-2"),
+ )})
+ choices = image_choices(saved, evidence=evidence)
+ assert [choice.model_id for choice in choices.models] == ["gpt-image-2", "grok-imagine-image"]
+ assert choices.saved_default_available is True
+ refused = _evidence(tmp_path / "r", (OPENAI, "gpt-image-2", "image_generate", "call"))
+ choices = image_choices(saved, evidence=refused)
+ assert [choice.model_id for choice in choices.models] == ["grok-imagine-image"]
+ assert (choices.saved_default_available, choices.default.model_id) == (False, "grok-imagine-image")
+ assert image_choices(_config(sources=[CLAUDE_SUB, GEMINI]), evidence=evidence).models == ()
+
+
+def test_resolution_states_v2_facts_in_todays_hop_shape(tmp_path):
+ """MH-HOSTED-001: every tool is on unless turned off; native when assumed; the first executor binds."""
+ resolved = resolve_hosted_tools(
+ _config(), source=XAI, model_id="grok-4.6", evidence=_evidence(tmp_path), spec_for=_spec_for,
)
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,
+ "mode": "native", "declaration": {"type": "web_search"}, "include": [],
+ "executor": {"source_id": "src_xai00001", "model_id": "grok-fast"}, "replay": True,
},
"x_search": {
- "mode": "proxy",
- "executor": {"source_id": "src_xai00001", "model_id": "grok-4.6"},
- "replay": False,
+ "mode": "native", "declaration": {"type": "x_search"}, "include": [],
+ "executor": {"source_id": "src_xai00001", "model_id": "grok-fast"}, "replay": True,
},
}
+ off = _config({"x_search": ModelHubHostedToolConfig(enabled=False)})
+ assert set(resolve_hosted_tools(
+ off, source=XAI, model_id="grok-4.6", evidence=_evidence(tmp_path / "o"), spec_for=_spec_for,
+ )) == {"web_search"}
-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",
+def test_the_tools_read_states_saved_and_effective_values_and_what_real_use_showed(tmp_path):
+ """MH-HOSTED-004: the read never resolves a saved value, and its status comes from real requests only."""
+ evidence = _evidence(tmp_path, (OPENAI, "gpt-6-astra", "web_search", "call"))
+ evidence.store.note_success(
+ EvidenceRecord(
+ source_id=XAI.id, model_id="grok-fast", feature=EvidenceFeature.hosted("web_search", "call"),
+ status="verified", observed_at=NOW, wire=evidence.wire_for(XAI, "grok-fast"),
+ source_identity=identity_digest(XAI), mode="executor",
+ ),
+ live=ALL, now=NOW,
)
- assert resolved == {"web_search": {"mode": "proxy", "executor": None, "replay": False}}
-
+ config = _config({"web_search": ModelHubHostedToolConfig(executor_order=("src_oai00001",))})
+ status = hosted_tools_status(config, evidence=evidence, spec_for=_spec_for, image_price=lambda _source, _spec: None)
+ by_name = {tool["name"]: tool for tool in status["tools"]}
+ assert list(by_name) == ["web_search", "x_search", "image_generate"]
+ web = by_name["web_search"]
+ assert web["enabled"] is True and by_name["x_search"]["enabled"] is True
+ assert web["executor_order"] == ["src_oai00001"]
+ assert web["effective_order"] == ["src_oai00001", "src_xai00001"]
+ assert [(c["source_id"], c["model_id"], c["relay"]) for c in web["executor_candidates"]] == [
+ ("src_oai00001", "gpt-mini", True), ("src_xai00001", "grok-fast", False),
+ ]
+ assert web["executor_candidates"][1]["price"]["unit"] == "call"
+ assert web["status"]["latest_ok"]["mode"] == "executor"
+ assert [(item["source_id"], item["aspect"]) for item in web["status"]["refused"]] == [("src_oai00001", "call")]
+ assert web["status"]["verified"] == [
+ {"source_id": "src_xai00001", "model_id": "grok-fast", "mode": "executor", "at": "2026-10-15T12:00:00Z"}
+ ]
+ image = by_name["image_generate"]
+ assert (image["default_model"], image["effective_default"]["model_id"]) == (None, "grok-imagine-image")
+ assert image["image_offered_by"] == ["openai", "xai"]
- "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")
+ # The same Source id under a new credential is another Source: what the old one showed is not claimed for it.
+ rotated = replace(XAI, credential_ref="cred_rotated")
+ status = hosted_tools_status(
+ _config(sources=[CLAUDE_SUB, rotated, OPENAI, GEMINI]), evidence=evidence, spec_for=_spec_for,
+ image_price=lambda _source, _spec: None,
)
- assert resolved == {"web_search": {"mode": "proxy", "executor": None, "replay": False}}
+ web = next(tool for tool in status["tools"] if tool["name"] == "web_search")
+ assert (web["status"]["latest_ok"], web["status"]["verified"]) == (None, [])
-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_the_latest_success_is_the_newest_in_time_not_in_text(tmp_path):
+ """MH-HOSTED-004: a time with no fraction of a second sorts after a later one with one when read as text."""
+ from datetime import timedelta
+ evidence = _evidence(tmp_path)
+ for source, model_id, at in ((XAI, "grok-fast", NOW), (OPENAI, "gpt-mini", NOW + timedelta(milliseconds=500))):
+ evidence.store.note_success(
+ EvidenceRecord(
+ source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted("web_search", "call"),
+ status="verified", observed_at=at, wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source), mode="executor",
+ ),
+ live=ALL, now=at,
+ )
+ status = hosted_tools_status(_config(), evidence=evidence, spec_for=_spec_for, image_price=lambda _s, _m: None)
+ web = next(tool for tool in status["tools"] if tool["name"] == "web_search")
+ assert web["status"]["latest_ok"]["source_id"] == "src_oai00001"
-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_the_latest_success_is_the_newest_one_whose_source_is_still_the_same(tmp_path):
+ """MH-HOSTED-004: once the newest success's Source changes identity, the latest is the newest other success, as
+ fresh as memory holds it, not as old as the hourly file write."""
+ from datetime import timedelta
-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,
- )
+ evidence = _evidence(tmp_path)
+
+ def succeed(source, model_id, at):
+ evidence.store.note_success(
+ EvidenceRecord(
+ source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted("web_search", "call"),
+ status="verified", observed_at=at, wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source), mode="executor",
+ ),
+ live=ALL, now=at,
+ )
+
+ succeed(XAI, "grok-fast", NOW)
+ succeed(XAI, "grok-fast", NOW + timedelta(minutes=10))
+ succeed(OPENAI, "gpt-mini", NOW + timedelta(minutes=20))
+ rotated = replace(OPENAI, credential_ref="cred_rotated")
status = hosted_tools_status(
- _config({"x_search": ON}), evidence=store, spec_for=_spec_for, engine=ENGINE, now=NOW,
- probe_estimate=lambda _source, _model_id, _tool: None,
+ _config(sources=[CLAUDE_SUB, XAI, rotated, GEMINI]), evidence=evidence, spec_for=_spec_for,
+ image_price=lambda _s, _m: None,
)
- 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}
- # What a turn would bind now: the age-stale verified XAI call still routes; wire-stale ones do not.
- assert by_name["web_search"]["bound"] == {"source_id": "src_xai00001", "model_id": "grok-4.6"}
- assert by_name["x_search"]["bound"] is None
- # An aged probe record has nothing left to wait for; a wire-stale one waits for the user's re-verify.
- assert by_name["web_search"]["candidates"][0]["call"]["changes_at"] is None
- assert by_name["x_search"]["candidates"][0]["call"]["changes_at"] is None
+ web = next(tool for tool in status["tools"] if tool["name"] == "web_search")
+ assert web["status"]["latest_ok"] == {
+ "source_id": "src_xai00001", "model_id": "grok-fast", "mode": "executor", "at": "2026-10-15T12:10:00Z",
+ }
+
+
+ "base_url,relay",
+ [
+ (None, False),
+ ("https://api.openai.com/v1", False),
+ # Spellings of the official endpoint the engine treats as the same one.
+ ("https://API.OpenAI.com:443/v1/", False),
+ ("https://api.openai.com", False),
+ ("https://relay.example/v1", True),
+ ("https://api.openai.com:8443/v1", True),
+ ],
+)
+def test_a_relay_is_any_endpoint_but_the_vendors_own_by_the_engines_endpoint_identity(base_url, relay):
+ """MH-HOSTED-004: an executor candidate is marked relay, whose bill Avibe cannot know, only off the official
+ endpoint."""
+ from core.handlers.model_hub.hosted_tools import is_relay
+
+ assert is_relay(replace(OPENAI, base_url=base_url)) is relay
+
+
+ "tool,payload,expected",
+ [
+ ("web_search", {"enabled": False}, {"enabled": False, "executor_order": ("src_oai00001",)}),
+ ("web_search", {"executor_order": None}, {"enabled": True, "executor_order": None}),
+ ("web_search", {"executor_order": ["src_xai00001"]}, {"enabled": True, "executor_order": ("src_xai00001",)}),
+ ],
+)
+def test_a_put_changes_only_the_fields_it_names(tool, payload, expected):
+ """MH-HOSTED-004: an absent field is unchanged and null resets; a toggle never drops a saved order."""
+ config = _config({"web_search": ModelHubHostedToolConfig(executor_order=("src_oai00001",))})
+ setting = apply_hosted_tool_put(config, tool, payload)
+ assert (setting.enabled, setting.executor_order) == (expected["enabled"], expected["executor_order"])
+
+
+ "tool,payload,code",
+ [
+ ("image_generation", {"enabled": True}, "hosted_tool_not_found"),
+ ("web_search", {}, "invalid_parameter"),
+ ("web_search", {"default_model": None}, "invalid_parameter"),
+ ("image_generate", {"executor_order": None}, "invalid_parameter"),
+ ("web_search", {"enabled": "yes"}, "invalid_parameter"),
+ # Only the saved choices reset with null; a null switch must not turn a cost-bearing tool back on.
+ ("web_search", {"enabled": None}, "invalid_parameter"),
+ ("web_search", {"executor_order": ["not-a-source"]}, "invalid_parameter"),
+ ("image_generate", {"default_model": {"source_id": "openai", "model_id": "gpt-image-2"}}, "invalid_parameter"),
+ # A padded id would be saved and then never match the catalog id it names.
+ ("image_generate", {"default_model": {"source_id": "src_oai00001", "model_id": " gpt-image-2 "}}, "invalid_parameter"),
+ # One admission rule for model ids: text UTF-8 storage and transport cannot encode is refused too.
+ ("image_generate", {"default_model": {"source_id": "src_oai00001", "model_id": "gpt-image-\ud800"}}, "invalid_parameter"),
+ ("web_search", {"executor_order": ["src_a00000001", "src_a00000001"]}, "invalid_parameter"),
+ ],
+)
+def test_a_put_refuses_what_the_contract_forbids(tool, payload, code):
+ with pytest.raises(HostedToolSettingRefused) as refused:
+ apply_hosted_tool_put(_config(), tool, payload)
+ assert refused.value.code == code
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 5be95e854..ee0ec23c9 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_super
def 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": 14,
+ "contract_version": 15,
"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": 14,
+ "contract_version": 15,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -9588,7 +9588,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": 14,
+ "contract_version": 15,
"backend": "codex",
"channel": "native_cli",
"reachable": True,
diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.py
index b2406c6d0..97184f5c5 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_pat
def _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": 14,
+ "contract_version": 15,
"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(monkeypat
f"/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": 14, "provenance": record}
+ assert response.get_json() == {"ok": True, "contract_version": 15, "provenance": record}
assert store.config.to_payload() == before
assert adapter.synced == []
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 8d7749b4f..68b2deb90 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": 14,
+ "contract_version": 15,
"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": 14,
+ "contract_version": 15,
"outcome": "adapter_error",
"reachable": None,
"authenticated": "unknown",
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index f89e13447..67ab71199 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": 14, **supervisor.status()}
+ projected = {"contract_version": 15, **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.py
index 204221f63..97f4d8121 100644
--- a/tests/test_model_hub_vibey_consumer.py
+++ b/tests/test_model_hub_vibey_consumer.py
@@ -33,8 +33,6 @@ from config.v2_config import (
ModelHubSourceStateConfig,
)
from core.handlers.model_hub.adapter import RawOutcomeKind
-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_HEADER
from core.handlers.model_hub.request import ModelHubRequest
from core.handlers.model_hub.service import ModelHubError
@@ -107,7 +105,6 @@ def _validate(schema_name, value):
# 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"),
}
@@ -606,8 +603,9 @@ async def test_a_finished_turns_request_is_never_credited_to_the_next_turn_on_it
), ()),
LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
])
- # On, with no executor: a call its live Turn owns answers a failed record; any other call is not bound.
- service.store.config.hosted_tools["web_search"] = ModelHubHostedToolConfig(enabled=True, executor=None)
+ # On, with no executor (no Source's vendor offers X search here): a call its live Turn owns answers a failed
+ # record; any other call is not bound.
+ service.store.config.hosted_tools["x_search"] = ModelHubHostedToolConfig(enabled=True)
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
@@ -632,9 +630,9 @@ async def test_a_finished_turns_request_is_never_credited_to_the_next_turn_on_it
assert live["token"] == finished["token"]
stale = finished["request_headers"]
assert (await post(client, live, stale, "messages", message))[0] == 400
- status, answer = await post(client, live, stale, "hosted-tools/web_search", search)
+ status, answer = await post(client, live, stale, "hosted-tools/x_search", search)
assert (status, answer["error"]["code"]) == (409, "executor_not_bound")
- status, answer = await post(client, live, live["request_headers"], "hosted-tools/web_search", search)
+ status, answer = await post(client, live, live["request_headers"], "hosted-tools/x_search", search)
assert status == 200 and answer["record"]["status"] == "failed"
assert (await post(client, live, live["request_headers"], "messages", message))[0] == 200
completion = router.settle_turn("turn-live", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())
@@ -1071,29 +1069,11 @@ def test_native_cli_and_direct_are_not_vibey_channels(tmp_path):
@pytest.mark.asyncio
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."""
+ """MH-HOSTED-001: a tool the overlay offers is native with no evidence (nothing is probed); every enabled tool
+ binds the first executor of its chain, the vendor's lightweight model."""
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],
- )
+ service.store.config.hosted_tools = {"x_search": ModelHubHostedToolConfig(enabled=False)}
resolving_threads = []
resolve_on_worker = service.hosted_tools_for_hop
@@ -1114,10 +1094,9 @@ async def test_hop_resolution_states_each_enabled_hosted_tool(tmp_path):
"mode": "native",
"declaration": {"type": "web_search"},
"include": ["web_search_call.action.sources"],
- "executor": {"source_id": "src_primary01", "model_id": "gpt-6-astra"},
+ "executor": {"source_id": "src_primary01", "model_id": "gpt-6-luna"},
"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 (
diff --git a/tests/test_model_hub_vibey_contract_matrix.py b/tests/test_model_hub_vibey_contract_matrix.py
index dba313bc9..aae4e44bc 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": 14, "backend": "claude", "channel": "native_cli", "reachable": True,
+ "contract_version": 15, "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": 14, "backend": "vibey", "model_id": "fixture-model",
+ "contract_version": 15, "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": 14, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",
+ "contract_version": 15, "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.py
index 419ac7d8f..ac8861f09 100644
--- a/tests/test_provider_overlay.py
+++ b/tests/test_provider_overlay.py
@@ -24,13 +24,18 @@ BUNDLED = json.loads(catalog.get_bundled_catalog_path().read_text(encoding="utf-
BUNDLED_ROWS = catalog.load_bundled_catalog()["backends"]
AS_OF = date(2026, 10, 13)
_DROP = object()
+OPENAI_WEB_SEARCH = (
+ {"type": "web_search"},
+ ("web_search_call.action.sources",),
+ HostedToolPrice("call", 10.0, AS_OF, "https://developers.openai.com/api/docs/pricing"),
+)
@pytest.fixture(autouse=True)
def _fresh_overlay():
- catalog.bundled_provider_overlay.cache_clear()
+ catalog.bundled_provider_vendors.cache_clear()
yield
- catalog.bundled_provider_overlay.cache_clear()
+ catalog.bundled_provider_vendors.cache_clear()
def _validator() -> Draft7Validator:
@@ -65,24 +70,10 @@ def test_bundled_providers_section_satisfies_its_schema():
@pytest.mark.parametrize(
("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, "output_format": "jpeg", "output_compression": 90}, (), None),
- ),
+ ("openai", "openai_responses", "gpt-6-astra", "web_search", OPENAI_WEB_SEARCH),
+ ("openai", "openai_responses", " gpt-6-astra ", "web_search", OPENAI_WEB_SEARCH),
+ # Image generation is never a chat declaration; image models are listed apart.
+ ("openai", "openai_responses", "gpt-6-astra", "image_generation", None),
(
"xai",
"openai_responses",
@@ -182,6 +173,23 @@ def _edit(path: tuple, value: object):
return invalid
+def _with_image(entry: dict) -> dict:
+ return {**entry, "image_models": [copy.deepcopy(_IMAGE_MODEL)]}
+
+
+def _image_edit(path: tuple, value: object):
+ edit = _edit(("image_models", 0, *path), value)
+ return lambda entry: edit(_with_image(entry))
+
+
+_IMAGE_MODEL = {
+ "id": "grok-imagine-image",
+ "description": "Grok Imagine: fast photoreal images",
+ "endpoint": "images",
+ "params": ["size", "images"],
+ "size_forms": ["ratio"],
+ "prices": [{"price": {"unit": "image", "usd_per_1k": 20, "as_of": "2026-10-15", "url": "https://docs.x.ai/developers/pricing"}}],
+}
_FAMILY = ("models", 0)
_X_SEARCH = (*_FAMILY, "hosted_tools", "openai_responses", "x_search")
_PRICE = (*_X_SEARCH, "price")
@@ -215,14 +223,27 @@ _PRICE = (*_X_SEARCH, "price")
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, "unit"), "token"), id="price-unit-unknown"),
+ # Only an image model is priced per image.
+ pytest.param("xai", _edit((*_PRICE, "unit"), "image"), id="search-price-per-image"),
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"),
+ pytest.param("xai", _edit((*_PRICE, "extra", 0, "unit"), "image"), id="extra-unit-per-image"),
+ pytest.param("xai", _edit(("executor_model",), " "), id="executor-model-blank"),
+ pytest.param("xai", _edit(("image_models",), {}), id="image-models-not-a-list"),
+ pytest.param("xai", _image_edit(("endpoint",), "edits"), id="image-endpoint-unknown"),
+ pytest.param("xai", _image_edit(("description",), "x" * 81), id="image-description-too-long"),
+ pytest.param("xai", _image_edit(("params",), ["images", "quality"]), id="image-param-unknown"),
+ pytest.param("xai", _image_edit(("size_forms",), []), id="image-size-without-forms"),
+ pytest.param("xai", _image_edit(("prices", 0, "price", "unit"), "call"), id="image-price-not-per-image"),
+ pytest.param("xai", _image_edit(("tokens_per_image",), 0), id="image-tokens-not-positive"),
+ pytest.param(
+ "xai", _image_edit(("prices", 0, "price", "extra"), [{"unit": "image", "usd_per_1k": 1}]), id="image-price-extra",
+ ),
],
)
def test_an_invalid_vendor_entry_disables_only_that_vendor(monkeypatch, tmp_path, caplog, key, invalid):
@@ -243,6 +264,36 @@ def test_an_invalid_vendor_entry_disables_only_that_vendor(monkeypatch, tmp_path
assert len(warnings) == 1 and repr(key) in warnings[0]
+def test_an_image_model_entry_is_read_in_a_stable_form(monkeypatch, tmp_path):
+ """MH-HOSTED-005: an image model's params and size forms are sorted, so the tool block built from them is stable."""
+ providers = {**BUNDLED["providers"], "xai": _with_image(BUNDLED["providers"]["xai"])}
+ _validator().validate(providers)
+ _use_bundled(monkeypatch, tmp_path, providers)
+
+ (model,) = catalog.provider_image_models("xai")
+ assert (model.id, model.endpoint, model.params, model.size_forms) == (
+ "grok-imagine-image", "images", ("images", "size"), ("ratio",),
+ )
+ assert [(price.price.unit, price.price.usd_per_1k, price.size) for price in model.prices] == [("image", 20, None)]
+ assert catalog.provider_image_models("anthropic") == ()
+
+
[email protected]("vendor", sorted(BUNDLED["providers"]))
+def test_each_vendors_executor_model_runs_every_search_tool_the_vendor_offers(vendor):
+ """MH-HOSTED-005: an executor model the overlay does not declare a tool on would silently drop the vendor from
+ that tool's executor chain."""
+ offered = {
+ (protocol, tool)
+ for family in catalog.bundled_provider_overlay()[vendor]
+ for protocol, tools in family.hosted_tools.items()
+ for tool in tools
+ }
+ executor = catalog.provider_executor_model(vendor)
+ assert (executor is not None) is bool(offered)
+ for protocol, tool in offered:
+ assert catalog.hosted_tool_spec(vendor, protocol, executor, tool) is not None, (protocol, tool)
+
+
@pytest.mark.parametrize("providers", [[], "openai", None])
def test_a_providers_value_that_is_not_an_object_disables_only_the_overlay(
monkeypatch, tmp_path, caplog, providers
diff --git a/ui/e2e/chat-interactions/interactions.spec.ts b/ui/e2e/chat-interactions/interactions.spec.ts
index ad004404f..eb890c57d 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: 14, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',
+ contract_version: 15, 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.tsx
index 0889a88c2..88d877752 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: 14, backend, model_id, route_origin: origins[index],
+ contract_version: 15, 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: 14,
+ contract_version: 15,
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.tsx
index a32353a57..5d09d0d0b 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: 14, backend, model_id: modelId,
+ contract_version: 15, 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.ts
index 39ae7181a..b00e36786 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 exp
would_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: 14, error: 'source_in_route_chain', ...plan });
+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 15, 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.ts
index f0a28d7c6..6b4cc1088 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: 14, enabled: true, host_platform: 'linux',
+ contract_version: 15, 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.ts
index d65fef4f1..45ded868a 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"]] as
const 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:14,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:15,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:14,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:15,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.ts
index 66b3ab9e6..b2b6a8ff9 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: 14,
+ contract_version: 15,
enabled: true,
host_platform: 'darwin',
manifest: {
diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.ts
index c58eea7b5..7100a7d3a 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: 14, 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: 15, 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.ts
index 397095bad..bf4494125 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: 14,
+ contract_version: 15,
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.tsx
index 5e461a5c1..9af849e76 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: 14, backend: 'claude', model_id: 'opus-5',
+ contract_version: 15, 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 }],
@@ -354,7 +354,7 @@ describe('assistant installation presentation', () => {
mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });
mock.models.listSources.mockResolvedValue([]);
const chain = {
- contract_version: 14, backend: 'claude', model_id: 'opus-5',
+ contract_version: 15, 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.tsx
index b1fe1e230..0bd9ebc64 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: 14, backend: 'vibey', model_id: modelId,
+ contract_version: 15, 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.tsx
index 7fe3d315a..b4a0efca9 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: 14,
+ contract_version: 15,
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.ts
index 742051ffa..b88c88ef6 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: 14,
+ contract_version: 15,
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.tsx
index 2ca4af479..4c607dc6f 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: 14,
+ contract_version: 15,
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: 14, 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: 15, 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: 14,
+ contract_version: 15,
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: 14, 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: 15, 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: 14, 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: 15, 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: 14, 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: 15, 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.tsx
index 009fa9c90..7a8da03a6 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: 14,
+ contract_version: 15,
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/HostedCapabilityChips.tsx b/ui/src/components/settings/models/HostedCapabilityChips.tsx
index abf6af81a..229d2e061 100644
--- a/ui/src/components/settings/models/HostedCapabilityChips.tsx
+++ b/ui/src/components/settings/models/HostedCapabilityChips.tsx
@@ -1,87 +1,41 @@
-// A Source model's capability chips (`vibey-hosted-tools.md` §6.2, design.pen
-// frame FB4vC): one per hosted tool with evidence, and one per reasoning effort
-// the Source refused. No record draws nothing, because unchecked is the normal
-// state rather than a problem.
+// A Source model's capability chips (`vibey-hosted-tools.md` §8.2, design.pen
+// frame yjGXx): one per hosted tool with a record, and one per reasoning effort
+// the Source refused. No record draws nothing, because unused is the normal
+// state rather than a problem. Every chip comes from real requests; a refusal
+// chip carries the clear that lets the next request try this Source again.
//
// The hover/focus/tap detail follows TimeHint: a phone has no hover, so a tap
-// toggles it, and the chip's accessible name carries the same facts. The detail
-// stays open while the pointer is on it, so its check action can be reached.
+// toggles it, and the chip's accessible name carries the same facts.
import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { AtSign, Ban, Check, Gauge, Globe, Image as ImageIcon, Loader2, Radar, RotateCw, TriangleAlert, Waypoints } from 'lucide-react';
+import { AlertCircle, AtSign, CheckCircle2, Gauge, Globe, Image as ImageIcon } from 'lucide-react';
-import { Button } from '@/components/ui/button';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { formatDayTime, formatMonthDay, formatSentences } from './format';
-import { probeKey, type ModelCapability, type ProbeTarget } from './hostedTools';
-import type { HostedToolName, HostedToolProbeResult, RefusedEffort } from './types';
-import { ProbeAnswerNote } from './ProbeAnswerNote';
-import { useEstimateLabel } from './useEstimateLabel';
+import type { ModelCapability } from './hostedTools';
+import type { HostedToolName, RefusedEffort } from './types';
const TOOL_ICON: Record<HostedToolName, React.ComponentType<{ className?: string }>> = {
web_search: Globe,
x_search: AtSign,
- image_generation: ImageIcon,
-};
-
-/**
- * The chip's state. A probe record older than 30 days, either way, asks for a new
- * check. A refused tool reads "via proxy" only while the server binds a proxy
- * executor for it (`bound`); otherwise it is simply not supported here.
- */
-const chipState = ({ chip, proxied }: ModelCapability) => {
- if (chip.kind === 'engineUpgraded') return 'engineUpgraded' as const;
- if (chip.kind === 'native') return chip.aged ? 'reverify' as const : 'native' as const;
- if (proxied) return chip.aged ? 'viaProxyAged' as const : 'viaProxy' as const;
- return chip.aged ? 'unsupportedAged' as const : 'unsupported' as const;
-};
-type ChipState = ReturnType<typeof chipState>;
-
-const STATE_CLASS: Record<ChipState, string> = {
- native: 'model-hub-status-mint',
- reverify: 'model-hub-status-gold',
- engineUpgraded: 'model-hub-status-gold',
- viaProxy: 'model-hub-accent-pill--cyan',
- viaProxyAged: 'model-hub-status-gold',
- unsupported: 'model-hub-fill-0a border-border text-muted',
- unsupportedAged: 'model-hub-status-gold',
-};
-
-const STATE_ICON: Record<ChipState, React.ComponentType<{ className?: string }>> = {
- native: Check,
- reverify: RotateCw,
- engineUpgraded: TriangleAlert,
- viaProxy: Waypoints,
- viaProxyAged: RotateCw,
- unsupported: Ban,
- unsupportedAged: RotateCw,
+ image_generate: ImageIcon,
};
type Fact = { term: string; value: string; mono?: boolean };
-/** The facts every evidence record states: when and how it was learned, why, and until when. */
-const useEvidenceFacts = () => {
+/** The facts a refusal states: when it was learned, why, how long it stays, and the last success if any. */
+const useRefusalFacts = () => {
const { t, i18n } = useTranslation();
- return (record: { basis: 'probe' | 'observed' | null; observed_at: string | null; detail: string | null; changes_at: string | null }): Fact[] => {
- const facts: Fact[] = [];
- if (record.observed_at) {
- facts.push({
- term: t('settings.models.capability.recorded') as string,
- value: t('settings.models.capability.recordedValue', {
- time: formatDayTime(record.observed_at, i18n.language),
- basis: t(`settings.models.capability.basis.${record.basis === 'observed' ? 'observed' : 'probe'}`),
- }) as string,
- });
- }
- if (record.detail) facts.push({ term: t('settings.models.capability.reason') as string, value: record.detail, mono: true });
- if (record.changes_at) {
- facts.push({
- term: t('settings.models.capability.expiry') as string,
- value: t(record.basis === 'observed' ? 'settings.models.capability.expiryObserved' : 'settings.models.capability.expiryProbe', {
- date: formatMonthDay(record.changes_at),
- }) as string,
- });
+ return (refusal: { at: string; reason: string | null; lastOk?: string | null }): Fact[] => {
+ const facts: Fact[] = [{
+ term: t('settings.models.capability.recorded') as string,
+ value: t('settings.models.capability.recordedValue', { time: formatDayTime(refusal.at, i18n.language) }) as string,
+ }];
+ if (refusal.reason) facts.push({ term: t('settings.models.capability.reason') as string, value: refusal.reason, mono: true });
+ facts.push({ term: t('settings.models.capability.kept') as string, value: t('settings.models.capability.keptValue') as string });
+ if (refusal.lastOk) {
+ facts.push({ term: t('settings.models.capability.lastOk') as string, value: formatMonthDay(refusal.lastOk) });
}
return facts;
};
@@ -92,11 +46,11 @@ const EvidenceChip: React.FC<{
label: string;
explanation: string;
facts: Fact[];
- className: string;
- Icon: React.ComponentType<{ className?: string }>;
+ hint?: string;
+ tone: 'ok' | 'refused';
TitleIcon: React.ComponentType<{ className?: string }>;
- action?: React.ReactNode;
-}> = ({ data, label, explanation, facts, className, Icon, TitleIcon, action }) => {
+ clear?: { label: string; disabled: boolean; onClick: () => void };
+}> = ({ data, label, explanation, facts, hint, tone, TitleIcon, clear }) => {
const { t, i18n } = useTranslation();
const [open, setOpen] = React.useState(false);
const detailId = React.useId();
@@ -124,64 +78,55 @@ const EvidenceChip: React.FC<{
closing.current = window.setTimeout(() => setOpen(false), 120);
};
React.useEffect(() => () => { if (closing.current !== null) window.clearTimeout(closing.current); }, []);
- // Enter or Space moves keyboard focus into the detail, where its action is; a
- // hover or a focus that only passes by leaves focus where it is.
- const enterDetail = React.useRef(false);
- const focusDetail = () => {
- enterDetail.current = false;
- const detail = document.getElementById(detailId);
- const target = detail?.querySelector<HTMLElement>('button, [href], [tabindex]:not([tabindex="-1"])') ?? detail;
- if (target && !target.hasAttribute('tabindex') && target === detail) target.setAttribute('tabindex', '-1');
- target?.focus();
- };
+ const Icon = tone === 'ok' ? CheckCircle2 : AlertCircle;
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverAnchor asChild>
- <button
- ref={anchor}
- type="button"
+ {/* Shrinks inside its column and truncates; the detail always has the whole label. */}
+ <span
data-capability={data}
- aria-label={accessibleName as string}
- // It opens a detail that may hold a paid re-check: say so.
- aria-haspopup="dialog"
- aria-expanded={open}
- aria-controls={open ? detailId : undefined}
- // Shrinks inside its column and truncates; the detail always has the whole label.
- className={cn('model-hub-pill min-w-0 max-w-full flex-initial gap-1 border', className)}
- onPointerDown={(event) => { pointer.current = event.pointerType; }}
- onPointerEnter={(event) => { if (event.pointerType === 'mouse') keepOpen(); }}
- onPointerLeave={(event) => { if (event.pointerType === 'mouse') closeSoon(); }}
- onFocus={() => { if (pointer.current === null) keepOpen(); }}
- onBlur={() => { pointer.current = null; closeSoon(); }}
- onKeyDown={(event) => {
- if (event.key !== 'Enter' && event.key !== ' ') return;
- event.preventDefault();
- enterDetail.current = true;
- if (open) focusDetail();
- else keepOpen();
- }}
- onClick={() => {
- if (pointer.current === 'mouse') setOpen(true);
- else setOpen((previous) => !previous);
- }}
+ className={cn(
+ 'model-hub-pill model-hub-capability-chip min-w-0 max-w-full flex-initial border',
+ tone === 'ok' ? 'model-hub-status-mint' : 'model-hub-status-gold',
+ )}
>
- <Icon className="size-3 shrink-0" aria-hidden />
- <span className="truncate">{label}</span>
- </button>
+ <button
+ ref={anchor}
+ type="button"
+ aria-label={accessibleName as string}
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ aria-controls={open ? detailId : undefined}
+ className="min-w-0"
+ onPointerDown={(event) => { pointer.current = event.pointerType; }}
+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') keepOpen(); }}
+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') closeSoon(); }}
+ onFocus={() => { if (pointer.current === null) keepOpen(); }}
+ onBlur={() => { pointer.current = null; closeSoon(); }}
+ onClick={() => {
+ if (pointer.current === 'mouse') setOpen(true);
+ else setOpen((previous) => !previous);
+ }}
+ >
+ <Icon className="size-3 shrink-0" aria-hidden />
+ <span className="truncate">{label}</span>
+ </button>
+ {clear && (
+ <button type="button" className="model-hub-capability-clear shrink-0" aria-label={clear.label} disabled={clear.disabled} onClick={clear.onClick}>
+ {t('settings.models.capability.clear')}
+ </button>
+ )}
+ </span>
</PopoverAnchor>
<PopoverContent
id={detailId}
side="bottom"
align="start"
sideOffset={6}
- onOpenAutoFocus={(event) => {
- event.preventDefault();
- if (enterDetail.current) focusDetail();
- }}
+ onOpenAutoFocus={(event) => event.preventDefault()}
onInteractOutside={(event) => { if (anchor.current?.contains(event.target as Node)) event.preventDefault(); }}
onPointerEnter={(event) => { if (event.pointerType === 'mouse') keepOpen(); }}
onPointerLeave={(event) => { if (event.pointerType === 'mouse') closeSoon(); }}
- onFocusCapture={keepOpen}
className="model-hub-capability-detail flex w-[320px] max-w-[calc(100vw-24px)] flex-col gap-2.5 text-foreground"
>
<span className="flex items-center gap-1.5 font-bold"><TitleIcon className="model-hub-ink-mint size-3.5" aria-hidden />{label}</span>
@@ -193,7 +138,7 @@ const EvidenceChip: React.FC<{
))}
</dl>
)}
- {action}
+ {hint && <span className="model-hub-capability-explain">{hint}</span>}
</PopoverContent>
</Popover>
);
@@ -201,54 +146,51 @@ const EvidenceChip: React.FC<{
const CapabilityChip: React.FC<{
capability: ModelCapability;
- probing: ReadonlySet<string>;
- onProbe?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
-}> = ({ capability, probing, onProbe }) => {
+ modelId: string;
+ clearing: boolean;
+ onClear?: (tool: HostedToolName) => void;
+}> = ({ capability, modelId, clearing, onClear }) => {
const { t } = useTranslation();
- const facts = useEvidenceFacts()(capability.evidence);
- const estimate = useEstimateLabel()(capability.candidate.probe_estimate);
- const state = chipState(capability);
+ const refusalFacts = useRefusalFacts();
+ const { evidence } = capability;
const tool = t(`settings.models.tools.tool.${capability.tool}.name`) as string;
- const target: ProbeTarget = { tool: capability.tool, candidate: capability.candidate };
- const running = probing.has(probeKey(target));
- // The last answer from this chip's check, so one that became no evidence still answers here.
- const [last, setLast] = React.useState<HostedToolProbeResult | null | undefined>(undefined);
- const label = t(`settings.models.capability.chip.${state}`, {
- tool,
- date: capability.evidence.observed_at ? formatMonthDay(capability.evidence.observed_at) : '',
- }) as string;
- const explanation = t(`settings.models.capability.explain.${state}`, {
- tool,
- toolInline: t(`settings.models.tools.tool.${capability.tool}.inline`),
- }) as string;
- const action = onProbe
- ? (
- <span className="flex flex-col items-end gap-1">
- {last !== undefined && <ProbeAnswerNote result={last} />}
- <Button variant="outline" size="xs" disabled={running || probing.size > 0} aria-busy={running} onClick={() => void onProbe(target).then(setLast)}>
- {running ? <Loader2 className="animate-spin" aria-hidden /> : <Radar aria-hidden />}
- {t('settings.models.capability.recheckCost', { cost: estimate ?? t('settings.models.tools.probe.unknown') })}
- </Button>
- </span>
- )
- : undefined;
+ const toolInline = t(`settings.models.tools.tool.${capability.tool}.inline`) as string;
+ if (evidence.kind === 'ok') {
+ const date = formatMonthDay(evidence.success.at);
+ return (
+ <EvidenceChip
+ data={`${capability.tool}:ok`}
+ label={t('settings.models.capability.chip.ok', { tool, date }) as string}
+ explanation={t(`settings.models.capability.explain.${evidence.success.mode}`, { toolInline }) as string}
+ facts={[]}
+ tone="ok"
+ TitleIcon={TOOL_ICON[capability.tool]}
+ />
+ );
+ }
+ const { refusal } = evidence;
+ const state = refusal.aspect === 'call' ? 'refused' : 'replay';
return (
<EvidenceChip
data={`${capability.tool}:${state}`}
- label={label}
- explanation={explanation}
- facts={facts}
- className={STATE_CLASS[state]}
- Icon={STATE_ICON[state]}
+ label={t(`settings.models.capability.chip.${state}`, { tool }) as string}
+ explanation={t(`settings.models.capability.explain.${state}`, { toolInline }) as string}
+ facts={refusalFacts({ at: refusal.at, reason: refusal.reason, lastOk: evidence.lastOk?.at ?? null })}
+ hint={onClear ? t('settings.models.capability.clearHint') as string : undefined}
+ tone="refused"
TitleIcon={TOOL_ICON[capability.tool]}
- action={action}
+ clear={onClear && {
+ label: t('settings.models.capability.clearTool', { tool: toolInline, model: modelId }) as string,
+ disabled: clearing,
+ onClick: () => onClear(capability.tool),
+ }}
/>
);
};
-const EffortChip: React.FC<{ refused: RefusedEffort }> = ({ refused }) => {
+const EffortChip: React.FC<{ refused: RefusedEffort; modelId: string; clearing: boolean; onClear?: (effort: string) => void }> = ({ refused, modelId, clearing, onClear }) => {
const { t } = useTranslation();
- const facts = useEvidenceFacts()(refused);
+ const facts = useRefusalFacts()({ at: refused.observed_at, reason: refused.detail });
const effort = t(`chat.picker.effortOptions.${refused.effort}`, { defaultValue: refused.effort }) as string;
return (
<EvidenceChip
@@ -256,21 +198,35 @@ const EffortChip: React.FC<{ refused: RefusedEffort }> = ({ refused }) => {
label={t('settings.models.capability.effort.unsupported', { effort }) as string}
explanation={t('settings.models.capability.effort.explain') as string}
facts={facts}
- className="model-hub-fill-0a border-border text-muted"
- Icon={Ban}
+ hint={onClear ? t('settings.models.capability.clearHint') as string : undefined}
+ tone="refused"
TitleIcon={Gauge}
+ clear={onClear && {
+ label: t('settings.models.capability.clearEffort', { effort, model: modelId }) as string,
+ disabled: clearing,
+ onClick: () => onClear(refused.effort),
+ }}
/>
);
};
export const HostedCapabilityChips: React.FC<{
+ modelId: string;
capabilities: readonly ModelCapability[];
refusedEfforts?: readonly RefusedEffort[];
- probing: ReadonlySet<string>;
- onProbe?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
-}> = ({ capabilities, refusedEfforts = [], probing, onProbe }) => (
+ /** Tools with a write out: their clears wait for its answer. */
+ pendingTools: ReadonlySet<HostedToolName>;
+ /** The Source has a write out: effort clears wait for it. */
+ sourceBusy: boolean;
+ onClearTool?: (tool: HostedToolName) => void;
+ onClearEffort?: (effort: string) => void;
+}> = ({ modelId, capabilities, refusedEfforts = [], pendingTools, sourceBusy, onClearTool, onClearEffort }) => (
<span className="flex min-w-0 flex-wrap items-center gap-1.5">
- {capabilities.map((capability) => <CapabilityChip key={capability.tool} capability={capability} probing={probing} onProbe={onProbe} />)}
- {refusedEfforts.map((refused) => <EffortChip key={refused.effort} refused={refused} />)}
+ {capabilities.map((capability) => (
+ <CapabilityChip key={capability.tool} capability={capability} modelId={modelId} clearing={pendingTools.has(capability.tool)} onClear={onClearTool} />
+ ))}
+ {refusedEfforts.map((refused) => (
+ <EffortChip key={refused.effort} refused={refused} modelId={modelId} clearing={sourceBusy} onClear={onClearEffort} />
+ ))}
</span>
);
diff --git a/ui/src/components/settings/models/ProbeAnswerNote.tsx b/ui/src/components/settings/models/ProbeAnswerNote.tsx
deleted file mode 100644
index 0df6ef0cd..000000000
--- a/ui/src/components/settings/models/ProbeAnswerNote.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-// What a single check says where it was asked (a Tools row, a Source chip) when
-// its answer is not plain evidence: why a request failed, that the model did not
-// use the tool, or that the replay after a verified call did not verify.
-import { useTranslation } from 'react-i18next';
-import { AlertCircle } from 'lucide-react';
-
-import { probeUnanswered } from './hostedTools';
-import { serverText } from './serverCopy';
-import type { HostedToolProbeResult } from './types';
-
-/**
- * What a probe that became no evidence says where it was asked (a Tools row, a
- * Source chip): a request that failed says why, and one that completed without
- * the tool says that. Nothing for an answer that is evidence.
- */
-export const ProbeAnswerNote: React.FC<{ result: HostedToolProbeResult | null }> = ({ result }) => {
- const { t } = useTranslation();
- if (!probeUnanswered(result)) return result ? <ReplayNote replay={result.replay} /> : null;
- const failure = serverText(t, result?.call.error);
- return (
- <span className="model-hub-tool-cost-note flex items-center gap-1 model-hub-ink-gold" role="status">
- <AlertCircle className="size-3 shrink-0" aria-hidden />
- {failure
- ? t('settings.models.tools.probe.outcome.transientReason', { reason: failure })
- : result?.call.outcome === 'inconclusive'
- ? t('settings.models.tools.probe.outcome.inconclusive')
- : t('settings.models.tools.probe.outcome.transient')}
- </span>
- );
-};
-
-/**
- * The replay step a verified call is followed by, when it ran and did not verify.
- * Null (no replay ran) and a verified replay say nothing; a replay that got no
- * answer asks for another try, never reads as a failure.
- */
-const ReplayNote: React.FC<{ replay: HostedToolProbeResult['replay'] }> = ({ replay }) => {
- const { t } = useTranslation();
- if (!replay || replay.outcome === 'verified') return null;
- return (
- <span className="model-hub-tool-cost-note flex items-center gap-1 model-hub-ink-gold" role="status">
- <AlertCircle className="size-3 shrink-0" aria-hidden />
- {t(replay.outcome === 'unsupported' ? 'settings.models.tools.probe.replay.unsupported' : 'settings.models.tools.probe.replay.unverified')}
- </span>
- );
-};
diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
index 6b4ad0d64..ffa3eeb19 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: 14, backend, model_id: 'gpt-test', route_origin: routeOrigin,
+ contract_version: 15, 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.tsx
index b250d6ad3..49ca0508a 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: 14,
+ contract_version: 15,
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.tsx
index 878958d6e..6167fa081 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: 14, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
+ contract_version: 15, 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.tsx
index 3148a8919..02b058673 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: 14,
+ contract_version: 15,
...(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.tsx
index fd9988900..75deba8c3 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: 14,
+ contract_version: 15,
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: 14,
+ contract_version: 15,
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: 14,
+ contract_version: 15,
backend: 'claude',
model_id: routedModelId,
current: { source_id: retainedSource.id, model_id: routedModelId },
@@ -249,13 +249,13 @@ const routedImpact = {
interrupted: [{ backend: 'claude' as const, model_id: routedModelId, agents: ['Release bot'] }],
};
+const unused = { latest_ok: null, verified: [], refused: [] };
const hostedToolsStatus: HostedToolsStatus = {
tools: [
- { name: 'web_search', enabled: false, executor: null, bound: null, candidates: [] },
- { name: 'x_search', enabled: false, executor: null, bound: null, candidates: [] },
- { name: 'image_generation', enabled: false, executor: null, bound: null, candidates: [] },
+ { name: 'web_search', enabled: true, status: unused, executor_order: null, effective_order: [], executor_candidates: [] },
+ { name: 'x_search', enabled: true, status: unused, executor_order: null, effective_order: [], executor_candidates: [] },
+ { name: 'image_generate', enabled: true, status: unused, default_model: null, effective_default: null, models: [], image_offered_by: [] },
],
- reverify: { engine_upgraded: 0, aged: 0 },
};
const deferred = <T,>() => {
@@ -2862,7 +2862,7 @@ describe('SettingsModelsPage tools region', () => {
await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
});
- it('MH-HOSTED-UI-016: reads the hosted-tools report again after a committed Source change, since its models decide which pairs could run a tool', async () => {
+ it('MH-HOSTED-UI-005: reads the hosted-tools report again after a committed Source change, since a Source change can drop its evidence', async () => {
renderPage([retainedSource]);
const updatedSource = { ...retainedSource, display_name: 'Updated source' };
vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, removed_hops: [], interrupted: [] });
@@ -2885,27 +2885,21 @@ describe('SettingsModelsPage tools region', () => {
await waitFor(() => expect(read.mock.calls.length).toBeGreaterThan(readsBefore));
});
- it('MH-HOSTED-UI-016: reads the Sources again after a check, since a probe can verify its Source', async () => {
- const unknown = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
- const withCandidate: HostedToolsStatus = {
- ...hostedToolsStatus,
+ it('MH-HOSTED-UI-020: clears a refusal from its Source chip and shows the status the clear answered', async () => {
+ const withModel = { ...retainedSource, models: [{ id: 'claude-opus-5-5', display_name: null, origin: 'discovered' as const, reasoning_efforts: [], reasoning_efforts_source: null }] };
+ const refused: HostedToolsStatus = {
tools: hostedToolsStatus.tools.map((tool) => tool.name === 'web_search'
- ? { ...tool, candidates: [{ source_id: retainedSource.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown, billing: 'metered' as const, price: null, probe_estimate: null }] }
+ ? { ...tool, status: { ...unused, refused: [{ source_id: withModel.id, model_id: 'claude-opus-5-5', aspect: 'call' as const, at: '2026-10-14T09:00:00Z', reason: '400 unsupported_tool_type' }] } }
: tool),
};
- renderPage([retainedSource]);
- vi.mocked(modelsApi.getHostedTools).mockResolvedValue(withCandidate);
- const probe = vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
- probe: { tool: 'web_search', source_id: retainedSource.id, model_id: 'claude-opus-5-5', call: { outcome: 'verified', error: null }, replay: null },
- hosted_tools: withCandidate,
- });
- await screen.findByText('Retained source');
- await userEvent.click(screen.getByRole('tab', { name: /^Tools$|^工具$/ }));
- const card = await screen.findByRole('region', { name: /^Web search$|^网页搜索$/ });
- const sourceReads = vi.mocked(modelsApi.listSources).mock.calls.length;
+ renderPage([withModel]);
+ vi.mocked(modelsApi.getHostedTools).mockResolvedValue(refused);
+ const clear = vi.spyOn(modelsApi, 'clearHostedTool').mockResolvedValue(hostedToolsStatus);
+ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);
+ await screen.findByRole('dialog', { name: 'Retained source' });
- await userEvent.click(within(card).getByRole('button', { name: /^Check · cost unknown$|^检测 · 费用未知$/ }));
- expect(probe).toHaveBeenCalledTimes(1);
- await waitFor(() => expect(vi.mocked(modelsApi.listSources).mock.calls.length).toBeGreaterThan(sourceReads));
+ await userEvent.click(await screen.findByRole('button', { name: /^Clear the web search refusal of claude-opus-5-5$|^清除 claude-opus-5-5 的网页搜索拒绝记录$/ }));
+ expect(clear).toHaveBeenCalledWith('web_search', { source_id: withModel.id, model_id: 'claude-opus-5-5' });
+ await waitFor(() => expect(document.querySelector('[data-capability]')).toBeNull());
});
});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index d1d9093ef..543db085a 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -38,7 +38,6 @@ import { QuotaTab } from './QuotaTab';
import { ToolsTab } from './ToolsTab';
import { UsageTab } from './UsageTab';
import { useHostedTools } from './useHostedTools';
-import type { ProbeTarget } from './hostedTools';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKeySet, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';
@@ -1255,20 +1254,13 @@ export const SettingsModelsPage: React.FC = () => {
])
: null;
const hostedTools = useHostedTools(tab === 'tools' || selectedSource !== null, selectedSourceIdentity);
- // A probe is a real call on exactly one Source, and a successful one verifies
- // that Source (a pending credential check clears), so the Sources read follows it.
// A committed Source change (a model added, removed or refetched, or its
- // identity) changes which pairs could run a tool and what binds, so the
+ // identity) can drop that Source's evidence on the server, so the
// hosted-tools report follows it once the Sources settle.
const presentSourceMutationAndTools = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
await presentSourceMutation(commit);
void hostedTools.refresh();
}, [presentSourceMutation, hostedTools.refresh]);
- const probeHostedTool = React.useCallback(async (target: ProbeTarget) => {
- const result = await hostedTools.probe(target);
- void refresh();
- return result;
- }, [hostedTools.probe, refresh]);
const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;
const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.mode === 'hub') ?? null;
@@ -1647,7 +1639,7 @@ export const SettingsModelsPage: React.FC = () => {
selectSource({ sourceId, returnFocus: () => opener });
}}
/>
- : tab === 'tools' ? <ToolsTab read={hostedTools.read} sources={sources} pending={hostedTools.pending} probing={hostedTools.probing} onChange={(tool, body) => void hostedTools.save(tool, body)} onProbe={probeHostedTool} onRetry={() => void hostedTools.refresh()} />
+ : tab === 'tools' ? <ToolsTab read={hostedTools.read} sources={sources} pending={hostedTools.pending} onSave={(tool, body) => void hostedTools.save(tool, body)} onClear={(tool, body) => void hostedTools.clear(tool, body)} onRetry={() => void hostedTools.refresh()} />
: tab === 'usage' ? <UsageTab usage={usageRead} windowKey={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
: directEmpty ? <DirectHome agents={installedNativeAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />
@@ -1795,8 +1787,9 @@ export const SettingsModelsPage: React.FC = () => {
source={selectedSource}
hostedTools={hostedTools.read}
onRetryHostedTools={() => void hostedTools.refresh()}
- hostedProbing={hostedTools.probing}
- onProbeHostedTool={probeHostedTool}
+ hostedPending={hostedTools.pending}
+ // A chip clears its own (Source, model); the answer is the hosted-tools read, which owns that evidence.
+ onClearHostedRefusal={(tool, modelId) => void hostedTools.clear(tool, { source_id: selectedSource.id, model_id: modelId })}
activeBackends={activeBackends}
headingRef={sourceDetailHeadingRef}
trackMutation={trackSourceMutation(selectedSource.id)}
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index ccd2382aa..6811235b7 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -30,7 +30,7 @@ import {
NEEDS_ACTION_DETAIL_KEYS,
SOURCE_STATUSES,
} from './types';
-import type { HostedEvidence, HostedToolCandidate, HostedToolProbeResult, HostedToolsStatus, Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';
+import type { HostedRefusal, HostedSuccess, HostedToolsStatus, Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';
const source: Source = {
id: 'src_detail',
@@ -1381,11 +1381,11 @@ describe('SourceDetailPanel', () => {
});
-// What a Source's model rows say about hosted tools (§6.2, frame FB4vC). The
+// What a Source's model rows say about hosted tools (§8.2, frame yjGXx). The
// projection's states are `hostedTools.test.ts`'s subject; what is proved here is
-// what a Source row adds: a refused tool reads "via proxy" only while the server
-// binds a proxy for it, unchecked draws nothing, refused efforts get their own
-// chip, and the detail carries the record's facts and its check.
+// what a Source row adds: one chip per feature, unused draws nothing, refused
+// efforts get their own chip, the detail carries the record's facts, and every
+// refusal chip carries the clear for its own (Source, model).
describe('SourceDetailPanel hosted-tool capability chips', () => {
const twoModels: Source = {
...source,
@@ -1395,109 +1395,93 @@ describe('SourceDetailPanel hosted-tool capability chips', () => {
],
};
const at = '2026-10-13T10:20:00Z';
- const verified: HostedEvidence = {
- status: 'verified', stale: null, basis: 'probe', observed_at: at, detail: null, changes_at: '2026-11-12T10:20:00Z',
- };
- const refused: HostedEvidence = {
- status: 'unsupported', stale: null, basis: 'observed', observed_at: at, detail: '400 · unsupported_tool_type', changes_at: '2026-10-20T10:20:00Z',
- };
- const unknown: HostedEvidence = { status: 'unknown', stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
- const candidate = (model_id: string, call: HostedEvidence): HostedToolCandidate => ({
- source_id: source.id, model_id, call, replay: unknown, billing: 'metered', price: null, probe_estimate: { basis: 'list', usd: 0.02 },
+ const ok = (model_id: string, when = at): HostedSuccess => ({ source_id: source.id, model_id, mode: 'native', at: when });
+ const refused = (model_id: string, aspect: HostedRefusal['aspect'] = 'call'): HostedRefusal => ({
+ source_id: source.id, model_id, aspect, at, reason: '400 unsupported_tool_type',
});
- const executor = { source_id: 'src_grok0001', model_id: 'grok-4.6' };
- const status = (xSearch: { enabled: boolean; bound: typeof executor | null }): HostedToolsStatus => ({
+ const run = (verified: HostedSuccess[], refusals: HostedRefusal[]) => ({ latest_ok: null, verified, refused: refusals });
+ const status = (): HostedToolsStatus => ({
tools: [
- { name: 'web_search', enabled: true, executor: null, bound: null, candidates: [candidate('model-a', verified), candidate('model-b', unknown)] },
- { name: 'x_search', ...xSearch, executor: null, candidates: [candidate('model-a', refused)] },
- { name: 'image_generation', enabled: false, executor: null, bound: null, candidates: [] },
+ { name: 'web_search', enabled: true, status: run([ok('model-a')], [refused('model-b', 'replay')]), executor_order: null, effective_order: [], executor_candidates: [] },
+ // A later refusal on a pair that once ran the tool: the refusal is what routes.
+ { name: 'x_search', enabled: true, status: run([ok('model-a', '2026-10-10T08:00:00Z')], [refused('model-a')]), executor_order: null, effective_order: [], executor_candidates: [] },
+ { name: 'image_generate', enabled: true, status: run([], []), default_model: null, effective_default: null, models: [], image_offered_by: [] },
],
- reverify: { engine_upgraded: 0, aged: 0 },
});
+ const efforts = (model: Source['models'][number]) => model.id === 'model-b'
+ ? { ...model, refused_efforts: [{ effort: 'xhigh', basis: 'observed' as const, observed_at: at, detail: '400 unsupported_reasoning_effort' }] }
+ : model;
const renderChips = (
hostedTools: HostedToolsStatus,
- { models = twoModels.models, onProbe }: { models?: Source['models']; onProbe?: React.ComponentProps<typeof SourceDetailPanel>['onProbeHostedTool'] } = {},
+ { models = twoModels.models, onClear, track = immediateTrack }: {
+ models?: Source['models'];
+ onClear?: React.ComponentProps<typeof SourceDetailPanel>['onClearHostedRefusal'];
+ track?: TrackSourceMutation;
+ } = {},
) => render(
<I18nextProvider i18n={i18n}>
- <CommittedPanel source={{ ...twoModels, models }} hostedTools={readyRegion(hostedTools)} onProbeHostedTool={onProbe} trackMutation={immediateTrack} onReauth={noReauth} />
+ <CommittedPanel source={{ ...twoModels, models }} hostedTools={readyRegion(hostedTools)} onClearHostedRefusal={onClear} trackMutation={track} onReauth={noReauth} />
</I18nextProvider>,
);
- const chips = (modelId: string) => [...(screen.getByTitle(modelId).closest('.model-hub-source-table-row') as HTMLElement)
- .querySelectorAll('[data-capability]')].map((chip) => chip.getAttribute('data-capability'));
-
- it('MH-HOSTED-UI-006: draws evidence per model, and says "via proxy" only while a proxy is bound for the tool', () => {
- renderChips(status({ enabled: true, bound: executor }));
- expect(chips('model-a')).toEqual(['web_search:native', 'x_search:viaProxy']);
- // Unchecked is the normal state, not a problem: no chip at all.
- expect(chips('model-b')).toEqual([]);
- cleanup();
+ const row = (modelId: string) => screen.getByTitle(modelId).closest('.model-hub-source-table-row') as HTMLElement;
+ const chips = (modelId: string) => [...row(modelId).querySelectorAll('[data-capability]')].map((chip) => chip.getAttribute('data-capability'));
- // Off, or on with nothing bound: no call goes anywhere, so it is just unsupported here.
- renderChips(status({ enabled: false, bound: executor }));
- expect(chips('model-a')).toEqual(['web_search:native', 'x_search:unsupported']);
+ it('MH-HOSTED-UI-006: draws one chip per feature with a record, a refusal over a success, and nothing for an unused model', () => {
+ renderChips(status(), { models: twoModels.models.map(efforts) });
+ expect(chips('model-a')).toEqual(['web_search:ok', 'x_search:refused']);
+ expect(chips('model-b')).toEqual(['web_search:replay', 'effort:xhigh']);
cleanup();
- renderChips(status({ enabled: true, bound: null }));
- expect(chips('model-a')).toEqual(['web_search:native', 'x_search:unsupported']);
+
+ renderChips({ tools: [] });
+ expect(chips('model-a')).toEqual([]);
});
- it('MH-HOSTED-UI-017: names the record time, how it was learned, the reason, and until when it holds', async () => {
- renderChips(status({ enabled: false, bound: null }));
- const chip = screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ });
+ it('MH-HOSTED-UI-017: names the record time, the reason, how long it stays, and the last success', async () => {
+ renderChips(status());
+ const chip = within(row('model-a')).getByRole('button', { name: /^X search · not supported|^X 搜索 · 不支持/ });
// The accessible name carries the same facts as the hover detail, each with
// its term, composed by the locale.
- expect(chip.getAttribute('aria-label')).toMatch(/(Reason: |原因:)400 · unsupported_tool_type/);
- // And it says it opens a detail, which may hold a paid re-check.
+ expect(chip.getAttribute('aria-label')).toMatch(/(Reason: |原因:)400 unsupported_tool_type/);
expect(chip.getAttribute('aria-haspopup')).toBe('dialog');
expect(chip.getAttribute('aria-expanded')).toBe('false');
await userEvent.hover(chip);
const detail = await screen.findByRole('dialog');
expect(chip.getAttribute('aria-expanded')).toBe('true');
expect(chip.getAttribute('aria-controls')).toBe(detail.id);
- within(detail).getByText(/a real request|一次真实请求/);
- within(detail).getByText('400 · unsupported_tool_type');
- within(detail).getByText(/until 10-20, then the default applies|到 10-20,过期后按默认判断/);
- });
-
- it('MH-HOSTED-UI-013: checks a tool again from its chip, with the cost on the action, and answers there when the check is not evidence', async () => {
- const onProbe = vi.fn(async (): Promise<HostedToolProbeResult> => ({
- tool: 'x_search', source_id: source.id, model_id: 'model-a', call: { outcome: 'inconclusive', error: null }, replay: null,
- }));
- renderChips(status({ enabled: false, bound: null }), { onProbe });
- await userEvent.hover(screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ }));
- const detail = await screen.findByRole('dialog');
- await userEvent.click(within(detail).getByRole('button', { name: /Check again · about \$0\.02|重新检测 · 约 \$0\.02/ }));
- expect(onProbe).toHaveBeenCalledWith({ tool: 'x_search', candidate: expect.objectContaining({ source_id: source.id, model_id: 'model-a' }) });
- // Nothing was recorded, so the chip still reads as before; the detail says why.
- await within(detail).findByText(/the model didn't use the tool|模型没有调用工具/);
+ within(detail).getByText(/ · (a real request|一次真实请求)$/);
+ within(detail).getByText('400 unsupported_tool_type');
+ within(detail).getByText(/until you clear it|直到你清除/);
+ within(detail).getByText('10-10');
});
- it('MH-HOSTED-UI-017: moves keyboard focus into the detail on Enter, so its paid re-check can be reached', async () => {
- renderChips(status({ enabled: false, bound: null }), { onProbe: vi.fn(async () => null) });
- const chip = screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ });
+ it('MH-HOSTED-UI-017: opens any chip\'s detail from the keyboard, a success\'s included', async () => {
+ renderChips(status(), { onClear: vi.fn() });
+ const chip = within(row('model-a')).getByRole('button', { name: /^Web search · OK · 10-13|^网页搜索 · 正常 · 10-13/ });
chip.focus();
+ await userEvent.keyboard('{Escape}');
await userEvent.keyboard('{Enter}');
const detail = await screen.findByRole('dialog');
- await waitFor(() => expect(document.activeElement).toBe(
- within(detail).getByRole('button', { name: /Check again · about \$0\.02|重新检测 · 约 \$0\.02/ }),
- ));
+ within(detail).getByText(/Display only|只用于显示/);
+ // A success has nothing to clear.
+ expect(within(row('model-a')).getAllByRole('button', { name: /^Clear|^清除/ })).toHaveLength(1);
});
- it('MH-HOSTED-UI-003: says a re-check\'s cost is unknown when no estimate is known', async () => {
- const read = status({ enabled: false, bound: null });
- const unpriced = { ...read, tools: read.tools.map((tool) => ({ ...tool, candidates: tool.candidates.map((candidate) => ({ ...candidate, probe_estimate: null })) })) };
- renderChips(unpriced, { onProbe: vi.fn(async () => null) });
- await userEvent.hover(screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ }));
- const detail = await screen.findByRole('dialog');
- within(detail).getByRole('button', { name: /Check again · cost unknown|重新检测 · 费用未知/ });
+ it('MH-HOSTED-UI-020: clears a tool refusal for its own model only', async () => {
+ const onClear = vi.fn();
+ renderChips(status(), { onClear });
+ await userEvent.click(within(row('model-b')).getByRole('button', { name: /^Clear the web search refusal of model-b$|^清除 model-b 的网页搜索拒绝记录$/ }));
+ expect(onClear).toHaveBeenCalledWith('web_search', 'model-b');
});
- it('MH-HOSTED-UI-006: draws a chip for each reasoning effort the Source refused, even with no tool evidence', () => {
- const models = twoModels.models.map((model) => model.id === 'model-b'
- ? { ...model, refused_efforts: [{ effort: 'xhigh', basis: 'observed' as const, observed_at: at, detail: '400 · unsupported reasoning effort', changes_at: null }] }
- : model);
- renderChips({ ...status({ enabled: false, bound: null }), tools: [] }, { models });
- expect(chips('model-a')).toEqual([]);
- expect(chips('model-b')).toEqual(['effort:xhigh']);
+ it('MH-HOSTED-UI-020: clears a refused effort and shows the Source the clear answered', async () => {
+ const answered: Source = { ...twoModels, models: twoModels.models };
+ const clear = vi.spyOn(modelsApi, 'clearRefusedEffort').mockResolvedValue(answered);
+ const landed = settlement();
+ renderChips({ tools: [] }, { models: twoModels.models.map(efforts), track: async (work) => work(source, landed) });
+
+ await userEvent.click(within(row('model-b')).getByRole('button', { name: /^Clear the Extra High refusal of model-b$|^清除 model-b 的 .+ 拒绝记录$/ }));
+ expect(clear).toHaveBeenCalledWith(source.id, 'model-b', 'xhigh');
+ await waitFor(() => expect(landed.source).toHaveBeenCalledWith(answered));
});
it('MH-HOSTED-UI-006: says when the capability read failed instead of drawing a Source with no evidence', async () => {
@@ -1514,8 +1498,7 @@ describe('SourceDetailPanel hosted-tool capability chips', () => {
});
it('MH-HOSTED-UI-006: adds no capability column when no model has evidence', () => {
- const read = status({ enabled: true, bound: null });
- renderChips({ ...read, tools: read.tools.map((tool) => ({ ...tool, candidates: [] })) });
+ renderChips({ tools: status().tools.map((tool) => ({ ...tool, status: run([], []) })) });
expect(document.querySelector('.model-hub-source-table--capabilities')).toBeNull();
expect(document.querySelector('[data-capability]')).toBeNull();
});
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index f2dba0198..676266f86 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -4,6 +4,7 @@ import { FlaskConical, Info, Loader2, LogIn, MoreHorizontal, Plus, RefreshCw, Se
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
+import { useToast } from '@/context/ToastContext';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Input } from '@/components/ui/input';
import { ResponsiveMenu } from '@/components/ui/responsive-menu';
@@ -17,7 +18,7 @@ import { Field } from './dialogFields';
import { GuardDialog } from './GuardDialog';
import { GuardImpact } from './GuardImpact';
import { HostedCapabilityChips } from './HostedCapabilityChips';
-import { modelCapabilities, type ProbeTarget } from './hostedTools';
+import { modelCapabilities } from './hostedTools';
import { confirmGuardPlan, sendAgreed, unansweredRefusal } from './guardedWrite';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { SourcePrivateValue, SourcePrivacyToggle } from './SourcePrivacy';
@@ -61,7 +62,7 @@ import { SourceTestDialog } from './SourceTestDialog';
import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';
import type {
AgentBackend,
- HostedToolProbeResult,
+ HostedToolName,
HostedToolsStatus,
RouteHopRef,
Source,
@@ -145,7 +146,7 @@ const GUARD_COPY_KIND: Record<GuardedAction['kind'], 'refetch' | 'removeModel'>
const committedPlan = (hops: RouteHopRef[], gaps: SupplyGap[]): ManageGuardPlan | null =>
hops.length > 0 || gaps.length > 0 ? { hops, gaps } : null;
-const NO_PROBES: ReadonlySet<string> = new Set();
+const NO_TOOLS: ReadonlySet<HostedToolName> = new Set();
type SourceReconciliation =
| { kind: 'source'; source: Source }
@@ -173,14 +174,15 @@ export const SourceDetailPanel: React.FC<{
headingRef?: React.Ref<HTMLHeadingElement>;
/** Authoritative backends still using the gateway, when the Agent read is ready. */
activeBackends?: ReadonlySet<AgentBackend>;
- /** The hosted-tools read, for each model's capability chips (§6.2), and its retry. */
+ /** The hosted-tools read, for each model's capability chips (`vibey-hosted-tools.md` §8.2), and its retry. */
hostedTools?: RegionRead<HostedToolsStatus>;
onRetryHostedTools?: () => void;
- /** Probe keys running now, and the action a chip's re-check runs. */
- hostedProbing?: ReadonlySet<string>;
- onProbeHostedTool?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
-}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends, hostedTools, onRetryHostedTools, hostedProbing, onProbeHostedTool }) => {
+ /** Tools with a write out, and the clear a refusal chip runs for one of this Source's models. */
+ hostedPending?: ReadonlySet<HostedToolName>;
+ onClearHostedRefusal?: (tool: HostedToolName, modelId: string) => void;
+}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends, hostedTools, onRetryHostedTools, hostedPending, onClearHostedRefusal }) => {
const { t, i18n } = useTranslation();
+ const { showToast } = useToast();
const detailsHidden = useSourceDetailsHidden();
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
const { Icon, accent } = sourceVisual(source);
@@ -215,7 +217,7 @@ export const SourceDetailPanel: React.FC<{
model.id,
capabilityStatus ? modelCapabilities(capabilityStatus, source.id, model.id) : [],
]));
- // The column appears only when a model has evidence: unchecked draws nothing.
+ // The column appears only when a model has evidence: an unused model draws nothing.
const showCapabilities = [...capabilities.values()].some((list) => list.length > 0)
|| models.some((model) => (model.refused_efforts?.length ?? 0) > 0);
// A failed read is not "nothing checked": say so where chips would be. Only a
@@ -279,6 +281,32 @@ export const SourceDetailPanel: React.FC<{
}
}).finally(() => setPendingAction(null));
};
+ /** Clear one refused effort: the next request at it tries this Source again. The answer is the Source. */
+ const clearEffort = (modelId: string, effort: string) => {
+ if (busy) return Promise.resolve();
+ setPendingAction('other');
+ return trackMutation(async (latest, settlement) => {
+ try {
+ await settlement.source(await modelsApi.clearRefusedEffort(latest.id, modelId, effort));
+ } catch (error) {
+ if (apiFailure(error)?.code === 'source_not_found') {
+ await settlement.gone(latest.id);
+ return;
+ }
+ showToast(t('settings.models.capability.clearFailed') as string, 'error');
+ // A refused clear changed nothing and a lost answer may have committed:
+ // either way the chips show what the server holds now.
+ try {
+ const inventory = await settlement.readInventory();
+ const current = inventory.sources.find((item) => item.id === latest.id);
+ if (current) await settlement.source(current);
+ else await settlement.gone(latest.id, inventory);
+ } catch {
+ settlement.release();
+ }
+ }
+ }).finally(() => setPendingAction(null));
+ };
const reconcileManualCreate = async (sourceId: string, modelId: string, settlement: SourceMutationSettlement) => reconcileUnknownWrite(
settlement.readInventory,
({ sources, snapshot }) => {
@@ -767,7 +795,15 @@ export const SourceDetailPanel: React.FC<{
{models.map((model) => (
<div key={model.id} hidden={!visibleModelIds.has(model.id)} className="model-hub-source-table-row grid gap-3 border-b border-border last:border-b-0 md:items-center md:gap-y-0">
<span className="flex min-w-0 items-center gap-2"><span className="model-hub-source-model truncate font-mono text-foreground" title={model.id}>{model.id}</span>{model.origin !== 'discovered' && <span className="model-hub-source-pill model-hub-source-entry-pill model-hub-source-entry-pill--manual w-fit rounded-full border font-semibold">{t('settings.models.sourceDetail.entry.manual')}</span>}{result?.added.includes(model.id) && <span className="model-hub-accent-pill--mint model-hub-source-pill rounded-full border px-2 py-0.5 font-semibold">{t('settings.models.sourceDetail.refetch.added')}</span>}</span>
- {showCapabilities && <span className="model-hub-source-capabilities min-w-0"><HostedCapabilityChips capabilities={capabilities.get(model.id) ?? []} refusedEfforts={model.refused_efforts} probing={hostedProbing ?? NO_PROBES} onProbe={onProbeHostedTool} /></span>}
+ {showCapabilities && <span className="model-hub-source-capabilities min-w-0"><HostedCapabilityChips
+ modelId={model.id}
+ capabilities={capabilities.get(model.id) ?? []}
+ refusedEfforts={model.refused_efforts}
+ pendingTools={hostedPending ?? NO_TOOLS}
+ sourceBusy={busy}
+ onClearTool={onClearHostedRefusal && ((tool) => onClearHostedRefusal(tool, model.id))}
+ onClearEffort={(effort) => void clearEffort(model.id, effort)}
+ /></span>}
<div className="model-hub-source-row-actions flex items-center justify-end gap-1">
{removeFailure?.modelId === model.id && <span className="model-hub-source-tier text-right text-destructive-ink">{t('settings.models.sourceDetail.fail.removeModel')} <button type="button" disabled={busy} onClick={() => {
if (!removeFailure.retryRead) void remove(model);
diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.ts
index 8c2577f7c..d8a9c19b5 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: 14,
+ contract_version: 15,
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: 14,
+ contract_version: 15,
backend: 'claude',
model_id: 'model-a',
current: { source_id: current, model_id: 'model-a' },
diff --git a/ui/src/components/settings/models/ToolsTab.test.tsx b/ui/src/components/settings/models/ToolsTab.test.tsx
index f5a7d5641..30087b6bb 100644
--- a/ui/src/components/settings/models/ToolsTab.test.tsx
+++ b/ui/src/components/settings/models/ToolsTab.test.tsx
@@ -1,7 +1,9 @@
// @vitest-environment jsdom
-// What the 工具 tab writes and claims (`vibey-hosted-tools.md` §6.1): a toggle and
-// an executor pick each replace the tool's whole setting, the picker offers only
-// what is verified, and no cost is invented where none is known.
+// What the 工具 tab writes and says (`vibey-hosted-tools.md` §8.1): every tool is
+// on by default and nothing locks it, a control writes only the field it
+// changes, status lines come from real use only, and every refusal can be
+// cleared where the line that names it says so.
+import * as React from 'react';
import { cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createInstance } from 'i18next';
@@ -10,16 +12,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
-import type { ProbeTarget } from './hostedTools';
import { readyRegion } from './regionRead';
import { ToolsTab } from './ToolsTab';
import type {
- HostedEvidence,
- HostedToolCandidate,
+ HostedExecutorCandidate,
+ HostedImageToolStatus,
+ HostedRefusal,
+ HostedSearchToolStatus,
HostedToolName,
- HostedToolProbeResult,
+ HostedToolPut,
+ HostedToolRunStatus,
HostedToolsStatus,
- HostedToolStatus,
Source,
} from './types';
@@ -52,386 +55,366 @@ const RELAY = source('src_relay001', 'relay-gpt');
const GROK = source('src_grok0001', 'Grok', { vendor: 'xai' });
const SUBSCRIPTION = source('src_chatgpt1', 'OpenAI subscription', { kind: 'subscription', billing: 'monthly' });
const CLAUDE = source('src_claude01', 'relay-claude', { vendor: 'anthropic', protocol: 'anthropic' });
-
-const unknown: HostedEvidence = { status: 'unknown', stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
-const verified: HostedEvidence = {
- status: 'verified', stale: null, basis: 'probe', observed_at: '2026-10-13T10:20:00Z', detail: null, changes_at: '2026-11-12T10:20:00Z',
-};
const SOURCES = [CLAUDE, RELAY, GROK, SUBSCRIPTION];
-/** A candidate as the server reports it; billing follows its Source unless a test states it. */
-type CandidateInput = Pick<HostedToolCandidate, 'source_id' | 'model_id' | 'call' | 'replay'> & Partial<HostedToolCandidate>;
-const tool = (
- name: HostedToolName,
- over: Omit<Partial<HostedToolStatus>, 'candidates'> & { candidates?: CandidateInput[] } = {},
-): HostedToolStatus => ({
+const run = (over: Partial<HostedToolRunStatus> = {}): HostedToolRunStatus => ({ latest_ok: null, verified: [], refused: [], ...over });
+const refusal = (sourceId: string, modelId: string, at: string, aspect: HostedRefusal['aspect'] = 'call'): HostedRefusal => ({
+ source_id: sourceId, model_id: modelId, aspect, at, reason: '400 unsupported_tool_type',
+});
+
+const candidate = (sourceId: string, modelId: string, over: Partial<HostedExecutorCandidate> = {}): HostedExecutorCandidate => ({
+ source_id: sourceId,
+ model_id: modelId,
+ billing: SOURCES.find((entry) => entry.id === sourceId)?.billing ?? 'metered',
+ relay: false,
+ price: null,
+ ...over,
+});
+
+const search = (name: 'web_search' | 'x_search', over: Partial<HostedSearchToolStatus> = {}): HostedSearchToolStatus => ({
name,
- enabled: false,
- executor: null,
- bound: null,
+ enabled: true,
+ status: run(),
+ executor_order: null,
+ effective_order: (over.executor_candidates ?? []).map((entry) => entry.source_id),
+ executor_candidates: [],
...over,
- candidates: (over.candidates ?? []).map((candidate) => ({
- billing: SOURCES.find((entry) => entry.id === candidate.source_id)?.billing ?? 'metered',
- price: null,
- probe_estimate: null,
- ...candidate,
- })),
});
-const status = (tools: HostedToolStatus[], reverify = { engine_upgraded: 0, aged: 0 }): HostedToolsStatus => ({ tools, reverify });
+const image = (over: Partial<HostedImageToolStatus> = {}): HostedImageToolStatus => ({
+ name: 'image_generate',
+ enabled: true,
+ status: run(),
+ default_model: null,
+ effective_default: null,
+ models: [],
+ image_offered_by: ['openai', 'google'],
+ ...over,
+});
-type RunProbe = (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
const renderTab = (
value: HostedToolsStatus,
- {
- lng = 'en',
- pending = new Set<HostedToolName>(),
- onProbe = vi.fn<RunProbe>(async () => null),
- }: { lng?: 'en' | 'zh'; pending?: ReadonlySet<HostedToolName>; onProbe?: RunProbe } = {},
+ { lng = 'en', pending = new Set<HostedToolName>() }: { lng?: 'en' | 'zh'; pending?: ReadonlySet<HostedToolName> } = {},
) => {
- const onChange = vi.fn();
+ const onSave = vi.fn();
+ const onClear = vi.fn();
render(
<I18nextProvider i18n={translator(lng)}>
- <ToolsTab
- read={readyRegion(value)}
- sources={SOURCES}
- pending={pending}
- probing={new Set()}
- onChange={onChange}
- onProbe={onProbe}
- onRetry={() => {}}
- />
+ <ToolsTab read={readyRegion(value)} sources={SOURCES} pending={pending} onSave={onSave} onClear={onClear} onRetry={() => {}} />
</I18nextProvider>,
);
- return onChange;
+ return { onSave, onClear };
};
const card = (name: string) => screen.getByRole('region', { name });
+const openAdvanced = async (user: ReturnType<typeof userEvent.setup>, name: string) => {
+ await user.click(within(card(name)).getByRole('button', { name: /^Advanced/ }));
+};
afterEach(() => cleanup());
-describe('ToolsTab writes', () => {
- it('MH-HOSTED-UI-001: a toggle replaces the whole setting and keeps the saved executor', async () => {
- const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
- const onChange = renderTab(status([
- tool('web_search', { enabled: true, executor, candidates: [{ ...executor, call: verified, replay: verified }] }),
- tool('x_search', { bound: executor, candidates: [{ ...executor, call: verified, replay: verified }] }),
- ]));
-
- await userEvent.click(within(card('Web search')).getByRole('switch', { name: 'Turn off Web search' }));
- // The PUT body is total: a toggle that sent only `enabled` would drop the
- // user's executor back to automatic.
- expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor });
-
- await userEvent.click(within(card('X search')).getByRole('switch', { name: 'Turn on X search' }));
- expect(onChange).toHaveBeenLastCalledWith('x_search', { enabled: true, executor: null });
- });
-
- it('MH-HOSTED-UI-018: cannot turn a tool on until a pair is verified to run it, but can always turn it off', async () => {
- const onChange = renderTab(status([
- tool('web_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
- tool('x_search', { enabled: true, candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
- ]));
-
- // On with nothing verified, every call would fail with no way to fix it here.
- const off = within(card('Web search')).getByRole('switch', { name: 'Turn on Web search' }) as HTMLButtonElement;
- expect(off.disabled).toBe(true);
- within(card('Web search')).getByText('Off · check a Source first');
-
- await userEvent.click(within(card('X search')).getByRole('switch', { name: 'Turn off X search' }));
- expect(onChange).toHaveBeenLastCalledWith('x_search', { enabled: false, executor: null });
+describe('ToolsTab settings', () => {
+ it('MH-HOSTED-UI-018: shows every tool on by default under its capability, and never locks a switch', () => {
+ renderTab({ tools: [search('web_search'), search('x_search'), image()] });
+
+ expect(within(screen.getByRole('region', { name: 'Search' })).getAllByRole('region').map((region) => region.getAttribute('aria-label')))
+ .toEqual(['Web search', 'X search']);
+ expect(within(screen.getByRole('region', { name: 'Generate' })).getByRole('region', { name: 'Image generation' })).toBeTruthy();
+ for (const name of ['Web search', 'X search', 'Image generation']) {
+ const toggle = within(card(name)).getByRole('switch');
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ expect((toggle as HTMLButtonElement).disabled).toBe(false);
+ }
});
- it('MH-HOSTED-UI-018: keeps a tool off while the server binds no executor for it, and says to choose one when a verified pair exists', async () => {
- // Verified, but outside Vibey's Source order: Automatic binds nothing (`bound: null`).
- const onChange = renderTab(status([tool('web_search', {
- candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }],
- })]));
- const toggle = within(card('Web search')).getByRole('switch', { name: 'Turn on Web search' }) as HTMLButtonElement;
- expect(toggle.disabled).toBe(true);
- within(card('Web search')).getByText('Off · choose an executor first');
- // Picking the verified pair explicitly is how it binds.
- await userEvent.selectOptions(within(card('Web search')).getByRole('combobox'), 'Grok · grok-4.6');
- expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor: { source_id: GROK.id, model_id: 'grok-4.6' } });
- });
+ it('MH-HOSTED-UI-001: a switch writes only whether the tool is on', async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({ tools: [search('web_search', { executor_order: [GROK.id] }), image({ enabled: false })] });
- it('MH-HOSTED-UI-001: writes a saved executor back only while the server would still accept it', async () => {
- // The saved pair left the candidates (its model went away): resolution skips
- // it already, and echoing it would get the whole PUT refused.
- const onChange = renderTab(status([tool('web_search', {
- enabled: true,
- executor: { source_id: RELAY.id, model_id: 'gpt-6-retired' },
- candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }],
- })]));
-
- await userEvent.click(within(card('Web search')).getByRole('switch', { name: 'Turn off Web search' }));
- expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor: null });
- });
+ await user.click(within(card('Web search')).getByRole('switch'));
+ await user.click(within(card('Image generation')).getByRole('switch'));
- it('MH-HOSTED-UI-001: the executor picker offers only verified pairs, and a pick keeps the toggle', async () => {
- const onChange = renderTab(status([
- tool('web_search', {
- enabled: true,
- bound: { source_id: GROK.id, model_id: 'grok-4.6' },
- candidates: [
- { source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown },
- { source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified },
- ],
- }),
- tool('x_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
- ]));
-
- const picker = within(card('Web search')).getByRole('combobox', { name: 'Proxy executor for Web search' });
- expect(within(picker).getAllByRole('option').map((option) => option.textContent))
- // Automatic names what the server binds for it now.
- .toEqual(['Automatic (Grok · grok-4.6)', 'Grok · grok-4.6']);
- await userEvent.selectOptions(picker, 'Grok · grok-4.6');
- expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: true, executor: { source_id: GROK.id, model_id: 'grok-4.6' } });
- await userEvent.selectOptions(picker, 'Automatic (Grok · grok-4.6)');
- expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: true, executor: null });
-
- // Nothing verified: nothing to pick, and the control says why.
- const unverified = within(card('X search')).getByRole('combobox', { name: 'Proxy executor for X search' });
- expect((unverified as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
- expect((unverified as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Available after a check');
+ expect(onSave.mock.calls).toEqual([['web_search', { enabled: false }], ['image_generate', { enabled: true }]]);
});
- it('MH-HOSTED-UI-001: a saved executor that is no longer verified stays visible as itself', () => {
- const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
- renderTab(status([tool('web_search', {
- enabled: true,
- executor,
- // The saved choice is stale, so the server binds the first verified pair.
- bound: { source_id: RELAY.id, model_id: 'gpt-6-astra' },
- candidates: [
- { source_id: RELAY.id, model_id: 'gpt-6-astra', call: verified, replay: verified },
- { ...executor, call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown },
+ it('MH-HOSTED-UI-001: holds a tool\'s controls while its write is out, and leaves other tools free', async () => {
+ const user = userEvent.setup();
+ const { onSave, onClear } = renderTab({
+ tools: [
+ search('web_search', {
+ status: run({ refused: [refusal(RELAY.id, 'gpt-6-astra', '2026-10-14T09:00:00Z')] }),
+ executor_candidates: [candidate(GROK.id, 'grok-fast'), candidate(CLAUDE.id, 'claude-haiku-5-5')],
+ }),
+ search('x_search'),
],
- })]));
-
- const picker = within(card('Web search')).getByRole('combobox', { name: 'Proxy executor for Web search' });
- expect((picker as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Grok · grok-4.6 (not verified)');
- // The badge is on what a turn binds, not on the saved choice.
- const badge = within(card('Web search')).getByText('Proxy executor', { selector: '.model-hub-pill' });
- expect(badge.closest('[data-candidate]')?.getAttribute('data-candidate')).toBe('src_relay001:gpt-6-astra');
- });
-
- it('MH-HOSTED-UI-001: keeps a saved executor visible as itself when nothing is verified any more', () => {
- const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
- const onChange = renderTab(status([tool('x_search', {
- enabled: true,
- executor,
- candidates: [{ ...executor, call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown }],
- })]));
-
- const picker = within(card('X search')).getByRole('combobox', { name: 'Proxy executor for X search' }) as HTMLSelectElement;
- expect(picker.disabled).toBe(true);
- expect(picker.selectedOptions[0]?.textContent).toBe('Grok · grok-4.6 (not verified)');
- expect(within(picker).queryByText('Available after a check')).toBeNull();
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('MH-HOSTED-UI-001: holds a tool\'s controls while its write is in flight', () => {
- renderTab(status([
- tool('web_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] }),
- tool('x_search', { bound: { source_id: GROK.id, model_id: 'grok-4.6' }, candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] }),
- ]), { pending: new Set(['web_search']) });
-
- expect((within(card('Web search')).getByRole('switch') as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
- expect((within(card('Web search')).getByRole('combobox') as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
+ }, { pending: new Set<HostedToolName>(['web_search']) });
+
+ expect((within(card('Web search')).getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
+ expect((within(card('Web search')).getByRole('button', { name: 'Clear relay-gpt\'s refusal of web search' }) as HTMLButtonElement).disabled).toBe(true);
+ await openAdvanced(user, 'Web search');
+ // The arrows stay focusable while the write is out, and do nothing.
+ const down = within(card('Web search')).getByRole('button', { name: 'Move Grok down' });
+ expect(down.getAttribute('aria-disabled')).toBe('true');
+ await user.click(down);
+ expect(onSave).not.toHaveBeenCalled();
+ expect(onClear).not.toHaveBeenCalled();
expect((within(card('X search')).getByRole('switch') as HTMLButtonElement).disabled).toBe(false);
});
});
-describe('ToolsTab claims', () => {
- it('MH-HOSTED-UI-018: claims routing only while the tool is on, and shows an off tool\'s executor as a saved preference', () => {
- const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
- const candidates = [{ ...executor, call: verified, replay: verified }];
- renderTab(status([
- tool('web_search', { enabled: true, executor, bound: executor, candidates }),
- tool('x_search', { enabled: false, executor, bound: executor, candidates }),
- ]));
-
- const on = card('Web search');
- within(on).getByText('Proxy executor', { selector: '.model-hub-pill' });
- within(on).getByText(/Other models use Grok/);
-
- // Off: resolution leaves the tool out entirely, so nothing here runs or bills.
- const off = card('X search');
- expect(within(off).queryByText('Proxy executor', { selector: '.model-hub-pill' })).toBeNull();
- expect(off.textContent).not.toMatch(/Other models use|billed/);
- within(off).getByText('Applies when the tool is on.');
- expect((within(off).getByRole('combobox') as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Grok · grok-4.6');
- });
+describe('ToolsTab status lines', () => {
+ it('MH-HOSTED-UI-002: says nothing about a tool before its first use', () => {
+ renderTab({ tools: [search('web_search'), image()] });
- it('MH-HOSTED-UI-003: states a cost only where one is known, and never prices an image', () => {
- renderTab(status([
- tool('web_search', { candidates: [
- {
- source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown,
- price: { unit: 'call', usd_per_1k: 10, extra: [], as_of: '2026-10-13', url: 'https://openai.com/api/pricing' },
- },
- { source_id: CLAUDE.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown },
- { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: unknown },
- ] }),
- tool('x_search', { candidates: [{
- source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown,
- price: { unit: 'post', usd_per_1k: 5, extra: [{ unit: 'profile', usd_per_1k: 10 }], as_of: '2026-10-13', url: 'https://docs.x.ai/pricing' },
- }] }),
- tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] }),
- ]));
-
- const row = (name: string, key: string) => card(name).querySelector(`[data-candidate="${key}"]`) as HTMLElement;
- within(row('Web search', 'src_relay001:gpt-6-astra')).getByText('≈ $0.01 / call');
- within(row('Web search', 'src_relay001:gpt-6-astra')).getByText('At API price');
- // No list price for this provider: said to be unknown, never drawn as zero.
- within(row('Web search', 'src_claude01:claude-opus-5-5')).getByText('No list price');
- expect(row('Web search', 'src_claude01:claude-opus-5-5').textContent).not.toMatch(/\$/);
- within(row('Web search', 'src_chatgpt1:gpt-6.1-sol')).getByText('Included in subscription');
- within(row('X search', 'src_grok0001:grok-4.6')).getByText('≈ $0.005 / post');
- within(row('X search', 'src_grok0001:grok-4.6')).getByText('At API price · + $0.01 / profile');
- within(row('Image generation', 'src_relay001:gpt-6.1-sol')).getByText('Billed per image token · no per-image price yet');
- expect(row('Image generation', 'src_relay001:gpt-6.1-sol').textContent).not.toMatch(/\$/);
+ for (const name of ['Web search', 'Image generation']) {
+ expect(within(card(name)).queryByText(/Last run|support|replay/)).toBeNull();
+ expect(within(card(name)).queryByRole('button', { name: /Clear/ })).toBeNull();
+ }
+ // The image card has no Advanced section until its clears move there.
+ expect(within(card('Image generation')).queryByRole('button', { name: /^Advanced/ })).toBeNull();
});
- it('MH-HOSTED-UI-003: the image cost copy is the orchestrator-decided Chinese line', () => {
- renderTab(status([tool('image_generation', { candidates: [
- { source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null },
- { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null },
- ] })]), { lng: 'zh' });
+ it('MH-HOSTED-UI-002: names who ran the tool last, with the date only', () => {
+ renderTab({ tools: [search('x_search', { status: run({ latest_ok: { source_id: GROK.id, model_id: 'grok-4', mode: 'native', at: '2026-10-15T06:02:00Z' } }) })] }, { lng: 'zh' });
- const image = card('图片生成');
- within(image.querySelector('[data-candidate="src_relay001:gpt-6.1-sol"]') as HTMLElement).getByText('按图像 token 计费 · 暂无单价');
- within(image.querySelector('[data-candidate="src_chatgpt1:gpt-6.1-sol"]') as HTMLElement).getByText('订阅内含');
+ expect(within(card('X 搜索')).getByText('最近一次由 Grok 执行 · 正常 · 10-15')).toBeTruthy();
});
- it('MH-HOSTED-UI-003: lets the locale compose a price with its extras', () => {
- renderTab(status([tool('x_search', { candidates: [{
- source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown,
- price: { unit: 'post', usd_per_1k: 5, extra: [{ unit: 'profile', usd_per_1k: 10 }], as_of: '2026-10-13', url: 'https://docs.x.ai/pricing' },
- }] })]), { lng: 'zh' });
- within(card('X 搜索').querySelector('[data-candidate="src_grok0001:grok-4.6"]') as HTMLElement).getByText('API 标价 · 另加 $0.01 / 个账号');
+ it('MH-HOSTED-UI-020: one refusing Source: its line names the models and where the tool runs now, and clears that Source', async () => {
+ const user = userEvent.setup();
+ const { onClear } = renderTab({
+ tools: [search('web_search', {
+ status: run({
+ latest_ok: { source_id: CLAUDE.id, model_id: 'claude-haiku-5-5', mode: 'executor', at: '2026-10-15T08:00:00Z' },
+ refused: [refusal(RELAY.id, 'gpt-6-astra', '2026-10-14T09:00:00Z'), refusal(RELAY.id, 'gpt-6-luna', '2026-10-14T10:00:00Z')],
+ }),
+ })],
+ }, { lng: 'zh' });
+
+ const web = card('网页搜索');
+ expect(within(web).getByText('relay-gpt 不支持 · gpt-6-astra、gpt-6-luna,已改用 relay-claude')).toBeTruthy();
+ // That line already says where the tool runs, so no separate latest-run line repeats it.
+ expect(within(web).queryByText(/最近一次/)).toBeNull();
+ await user.click(within(web).getByRole('button', { name: '清除 relay-gpt 的网页搜索拒绝记录' }));
+ expect(onClear).toHaveBeenCalledWith('web_search', { source_id: RELAY.id });
});
- it('MH-HOSTED-UI-004: says how many checks an engine upgrade made stale, and nothing when none did', () => {
- renderTab(status([tool('web_search')], { engine_upgraded: 2, aged: 1 }));
- const line = screen.getByRole('status');
- // One sentence the locale composes, its first part marked.
- expect(line.textContent).toBe('Engine upgraded · 2 need a new check · 1 check is over 30 days old');
- expect(within(line).getByText('Engine upgraded · 2 need a new check').className).toContain('model-hub-ink-gold');
- cleanup();
-
- renderTab(status([tool('web_search')]));
- expect(screen.queryByRole('status')).toBeNull();
+ it('MH-HOSTED-UI-020: two refusing Sources: the line names them, and the clears and Clear all sit in Advanced', async () => {
+ const user = userEvent.setup();
+ const { onClear } = renderTab({
+ tools: [search('web_search', {
+ status: run({
+ verified: [{ source_id: CLAUDE.id, model_id: 'claude-haiku-5-5', mode: 'executor', at: '2026-10-15T08:00:00Z' }],
+ refused: [refusal(RELAY.id, 'gpt-6-astra', '2026-10-14T09:00:00Z'), refusal(SUBSCRIPTION.id, 'gpt-6.1-sol', '2026-10-15T07:00:00Z')],
+ }),
+ })],
+ });
+
+ const web = card('Web search');
+ expect(within(web).getByText('Not supported on relay-gpt, OpenAI subscription')).toBeTruthy();
+ expect(within(web).queryByRole('button', { name: /^Clear/ })).toBeNull();
+ expect(within(web).getByRole('button', { name: /^Advanced/ }).textContent).toContain('Execution order: automatic · Status by Source');
+
+ await openAdvanced(user, 'Web search');
+ const rows = within(web).getAllByRole('listitem').filter((row) => row.hasAttribute('data-pair'));
+ expect(rows.map((row) => row.textContent)).toEqual([
+ 'relay-claudeclaude-haiku-5-5OK · 10-15',
+ 'relay-gptgpt-6-astraNot supported · 10-14400 unsupported_tool_typeClear',
+ 'OpenAI subscriptiongpt-6.1-solNot supported · 10-15400 unsupported_tool_typeClear',
+ ]);
+ await user.click(within(web).getByRole('button', { name: 'Clear the web search refusal of gpt-6-astra on relay-gpt' }));
+ await user.click(within(web).getByRole('button', { name: 'Clear every refusal of web search' }));
+ expect(onClear.mock.calls).toEqual([
+ ['web_search', { source_id: RELAY.id, model_id: 'gpt-6-astra' }],
+ ['web_search', {}],
+ ]);
});
- it('MH-HOSTED-UI-006: names the Sources that have no native pair for a tool', () => {
- renderTab(status([tool('x_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] })]));
+ it('MH-HOSTED-UI-020: a replay refusal has its own line, and a Source that refused the call is not in it', async () => {
+ const user = userEvent.setup();
+ const { onClear } = renderTab({
+ tools: [
+ search('web_search', { status: run({ refused: [refusal(GROK.id, 'grok-4', '2026-10-14T09:00:00Z', 'replay')] }) }),
+ search('x_search', {
+ status: run({ refused: [refusal(RELAY.id, 'gpt-6-astra', '2026-10-14T09:00:00Z'), refusal(RELAY.id, 'gpt-6-luna', '2026-10-14T09:00:00Z', 'replay')] }),
+ }),
+ ],
+ });
- const note = within(card('X search')).getByText(/have no native X search/);
- // Grok offers the tool natively, so it is the one Source not named. Whether
- // a proxy executor serves the others is not this read's to say.
- expect(note.textContent).toMatch(/^Models on relay-claude, relay-gpt,? (and )?OpenAI subscription have no native X search\.$/);
+ expect(within(card('Web search')).getByText('Grok can\'t replay earlier results')).toBeTruthy();
+ await user.click(within(card('Web search')).getByRole('button', { name: 'Clear Grok\'s refusal of web search' }));
+ expect(onClear).toHaveBeenCalledWith('web_search', { source_id: GROK.id });
+ expect(within(card('X search')).getByText('Not supported on relay-gpt · gpt-6-astra')).toBeTruthy();
+ expect(within(card('X search')).queryByText(/replay/)).toBeNull();
});
-});
-describe('ToolsTab checks', () => {
- const searchable = () => status([
- tool('web_search', { candidates: [
- { source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown, probe_estimate: { basis: 'list', usd: 0.02 } },
- { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: unknown, probe_estimate: { basis: 'included' } },
- { source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified, probe_estimate: { basis: 'list', usd: 0.01 } },
- ] }),
- tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] }),
- ]);
- const result = (outcome: HostedToolProbeResult['call']['outcome'], source_id: string, model_id: string): HostedToolProbeResult => ({
- tool: 'web_search', source_id, model_id, call: { outcome, error: null }, replay: null,
+ it('MH-HOSTED-UI-020: an image refusal reads and clears like a search refusal, and two move into Advanced', async () => {
+ const user = userEvent.setup();
+ const { onClear } = renderTab({
+ tools: [image({ status: run({ refused: [refusal(RELAY.id, 'gpt-image-2', '2026-10-14T09:00:00Z'), refusal(CLAUDE.id, 'gpt-image-2', '2026-10-14T09:00:00Z')] }) })],
+ });
+
+ const imageCard = card('Image generation');
+ expect(within(imageCard).getByText('Not supported on relay-gpt, relay-claude')).toBeTruthy();
+ expect(within(imageCard).getByRole('button', { name: /^Advanced/ }).textContent).toContain('Status by Source');
+ await openAdvanced(user, 'Image generation');
+ // Only the clears live here: an image tool has no executor order.
+ expect(within(imageCard).queryByText('Execution order')).toBeNull();
+ await user.click(within(imageCard).getByRole('button', { name: 'Clear every refusal of image generation' }));
+ expect(onClear).toHaveBeenCalledWith('image_generate', {});
});
+});
- it('MH-HOSTED-UI-013: checks one row with its cost on the button, and says when the answer was not evidence', async () => {
- const onProbe = vi.fn<RunProbe>(async () => result('inconclusive', RELAY.id, 'gpt-6-astra'));
- renderTab(searchable(), { onProbe });
-
- const row = card('Web search').querySelector('[data-candidate="src_relay001:gpt-6-astra"]') as HTMLElement;
- await userEvent.click(within(row).getByRole('button', { name: 'Check · about $0.02' }));
- expect(onProbe).toHaveBeenCalledTimes(1);
- expect(onProbe.mock.calls[0][0]).toMatchObject({ tool: 'web_search', candidate: { source_id: RELAY.id, model_id: 'gpt-6-astra' } });
- // The model never used the tool: not recorded as unsupported, and the row offers another try.
- within(row).getByText("Not verified · the model didn't use the tool; try again");
- // Another try is as paid as the first, and says so.
- within(row).getByRole('button', { name: 'Retry · about $0.02' });
-
- // A verified row checks again; a subscription row says the check costs nothing extra.
- within(card('Web search').querySelector('[data-candidate="src_grok0001:grok-4.6"]') as HTMLElement).getByRole('button', { name: 'Check again · about $0.01' });
- within(card('Web search').querySelector('[data-candidate="src_chatgpt1:gpt-6.1-sol"]') as HTMLElement)
- .getByRole('button', { name: 'Check · included in subscription' });
- // An image check has no list price: it says so, and never shows $0.
- within(card('Image generation').querySelector('[data-candidate="src_relay001:gpt-6.1-sol"]') as HTMLElement)
- .getByRole('button', { name: 'Check · cost unknown' });
+describe('ToolsTab executor order', () => {
+ const PRICED = {
+ unit: 'call' as const,
+ usd_per_1k: 5,
+ extra: [],
+ as_of: '2026-10-01',
+ url: 'https://docs.x.ai/pricing',
+ };
+
+ it('MH-HOSTED-UI-021: lists the executors in effective order, and a move saves the whole shown order', async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ tools: [search('web_search', {
+ executor_candidates: [candidate(GROK.id, 'grok-fast', { price: PRICED }), candidate(CLAUDE.id, 'claude-haiku-5-5', { relay: true }), candidate(SUBSCRIPTION.id, 'gpt-6-mini')],
+ })],
+ });
+
+ await openAdvanced(user, 'Web search');
+ const rows = within(card('Web search')).getAllByRole('listitem');
+ expect(rows.map((row) => row.getAttribute('data-executor'))).toEqual([GROK.id, CLAUDE.id, SUBSCRIPTION.id]);
+ expect(within(card('Web search')).queryByRole('button', { name: 'Reset to automatic' })).toBeNull();
+ expect((within(rows[0]).getByRole('button', { name: 'Move Grok up' }) as HTMLButtonElement).disabled).toBe(true);
+ expect((within(rows[2]).getByRole('button', { name: 'Move OpenAI subscription down' }) as HTMLButtonElement).disabled).toBe(true);
+
+ await user.click(within(rows[1]).getByRole('button', { name: 'Move relay-claude up' }));
+ expect(onSave).toHaveBeenCalledWith('web_search', { executor_order: [CLAUDE.id, GROK.id, SUBSCRIPTION.id] });
});
- it('MH-HOSTED-UI-013: offers a check one pair at a time, never all pairs at once', () => {
- // A check is a real, paid request: with real Sources a check-all would probe hundreds of models.
- renderTab(searchable());
- expect(screen.queryByRole('button', { name: /Check available tools|检测可用工具/ })).toBeNull();
- expect(screen.queryByText(/pairs? to check|项可检测/)).toBeNull();
- // Each row still has its own check.
- expect(within(card('Web search')).getAllByRole('button', { name: /^Check/ })).toHaveLength(3);
+ it('MH-HOSTED-UI-021: a move keeps a saved executor the read does not show', async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ tools: [search('web_search', {
+ // relay-gpt is saved first but refused now, so it is not a candidate.
+ executor_order: [RELAY.id, GROK.id, CLAUDE.id],
+ executor_candidates: [candidate(GROK.id, 'grok-fast'), candidate(CLAUDE.id, 'claude-haiku-5-5')],
+ })],
+ });
+
+ await openAdvanced(user, 'Web search');
+ await user.click(screen.getByRole('button', { name: 'Move relay-claude up' }));
+ expect(onSave).toHaveBeenCalledWith('web_search', { executor_order: [RELAY.id, CLAUDE.id, GROK.id] });
});
- it('MH-HOSTED-UI-019: shows a replay that did not verify as its own result, and nothing when no replay ran', async () => {
- const replayed = (replay: HostedToolProbeResult['replay']): HostedToolProbeResult => ({ ...result('verified', RELAY.id, 'gpt-6-astra'), replay });
- const onProbe = vi.fn<RunProbe>()
- .mockResolvedValueOnce(replayed({ outcome: 'transient', error: null }))
- .mockResolvedValueOnce(replayed(null));
- renderTab(searchable(), { onProbe });
- const row = card('Web search').querySelector('[data-candidate="src_relay001:gpt-6-astra"]') as HTMLElement;
-
- // The call verified; the replay after it ran out of time. That asks for another try, never reads as a failure.
- await userEvent.click(within(row).getByRole('button', { name: 'Check · about $0.02' }));
- within(row).getByText('Replay not verified · try again');
- expect(row.textContent).not.toMatch(/Not verified|Couldn't verify/);
-
- // No replay ran: nothing more to say.
- await userEvent.click(within(row).getByRole('button', { name: /^Check/ }));
- expect(within(row).queryByText(/Replay/)).toBeNull();
- });
+ it('MH-HOSTED-UI-021: a customized order offers Reset, which saves automatic', async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ tools: [search('x_search', { executor_order: [GROK.id], executor_candidates: [candidate(GROK.id, 'grok-fast')] })],
+ });
- it('MH-HOSTED-UI-013: says why a failed check failed, and never shows the server\'s key as text', async () => {
- const failed = (error: string): HostedToolProbeResult => ({ ...result('inconclusive', RELAY.id, 'gpt-6-astra'), call: { outcome: 'transient', error } });
- const onProbe = vi.fn<RunProbe>()
- .mockResolvedValueOnce(failed('models.source.cooldown.rate_limited'))
- // A detail key this bundle has no copy for.
- .mockResolvedValueOnce(failed('models.source.cooldown.network'));
- renderTab(searchable(), { onProbe });
- const row = card('Web search').querySelector('[data-candidate="src_relay001:gpt-6-astra"]') as HTMLElement;
-
- await userEvent.click(within(row).getByRole('button', { name: 'Check · about $0.02' }));
- within(row).getByText("Couldn't verify · Rate limited");
- await userEvent.click(within(row).getByRole('button', { name: 'Retry · about $0.02' }));
- within(row).getByText("Couldn't verify · try again");
- expect(row.textContent).not.toContain('models.source');
+ expect(within(card('X search')).getByRole('button', { name: /^Advanced/ }).textContent).toContain('Execution order: customized');
+ await openAdvanced(user, 'X search');
+ await user.click(within(card('X search')).getByRole('button', { name: 'Reset to automatic' }));
+ expect(onSave).toHaveBeenCalledWith('x_search', { executor_order: null });
});
- it('MH-HOSTED-UI-018: keeps an image tool off until a check verifies one of its pairs, and offers that check', () => {
- renderTab(status([tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] })]));
- const image = card('Image generation');
- within(image).getByText('Off · check a Source first');
- expect((within(image).getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
- within(image).getByRole('button', { name: 'Check · cost unknown' });
+ it('MH-HOSTED-UI-021: announces a move and moves focus only once the server order shows it, and drops one that did not land', async () => {
+ const user = userEvent.setup();
+ const i18n = translator('en');
+ let asked: string[] | null = null;
+ const view = (order: string[], pending: ReadonlySet<HostedToolName> = new Set()) => (
+ <I18nextProvider i18n={i18n}>
+ <ToolsTab
+ read={readyRegion({ tools: [search('web_search', { executor_order: order, executor_candidates: order.map((id) => candidate(id, `${id}-mini`)) })] })}
+ sources={SOURCES}
+ pending={pending}
+ onSave={(_tool, body: HostedToolPut) => { asked = body.executor_order ?? null; }}
+ onClear={() => {}}
+ onRetry={() => {}}
+ />
+ </I18nextProvider>
+ );
+ const before = [GROK.id, CLAUDE.id, RELAY.id];
+ const writing = new Set<HostedToolName>(['web_search']);
+ const { rerender } = render(view(before));
+ await openAdvanced(user, 'Web search');
+ const status = screen.getByRole('status');
+
+ // Refused: nothing moved, so nothing is announced and nothing waits to take focus.
+ await user.click(screen.getByRole('button', { name: 'Move relay-gpt up' }));
+ rerender(view(before, writing));
+ expect(status.textContent).toBe('');
+ rerender(view(before));
+ expect(status.textContent).toBe('');
+ const elsewhere = screen.getByRole('switch');
+ elsewhere.focus();
+ rerender(view([GROK.id, RELAY.id, CLAUDE.id]));
+ expect(status.textContent).toBe('');
+ expect(document.activeElement).toBe(elsewhere);
+
+ // Landed: the server's order shows it, so it is announced and focus follows the row.
+ await user.click(screen.getByRole('button', { name: 'Move relay-gpt up' }));
+ rerender(view([GROK.id, RELAY.id, CLAUDE.id], writing));
+ expect(status.textContent).toBe('');
+ rerender(view(asked ?? []));
+ expect(screen.getAllByRole('listitem').map((row) => row.getAttribute('data-executor'))).toEqual([RELAY.id, GROK.id, CLAUDE.id]);
+ expect(status.textContent).toBe('Moved relay-gpt to position 1 of 3.');
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Move relay-gpt down' }));
});
- it('MH-HOSTED-UI-003: says a check\'s cost is unknown before it runs, when no estimate is known', () => {
- renderTab(status([tool('web_search', { candidates: [{ source_id: CLAUDE.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown }] })]));
- within(card('Web search')).getByRole('button', { name: 'Check · cost unknown' });
+ it('MH-HOSTED-UI-021: keeps focus on the moved row once the answer lands, on its other arrow at an end', async () => {
+ const user = userEvent.setup();
+ const Harness = () => {
+ const [order, setOrder] = React.useState([GROK.id, CLAUDE.id, RELAY.id]);
+ const value: HostedToolsStatus = {
+ tools: [search('web_search', {
+ executor_order: order,
+ executor_candidates: order.map((id) => candidate(id, `${id}-mini`)),
+ })],
+ };
+ return (
+ <I18nextProvider i18n={translator('en')}>
+ <ToolsTab
+ read={readyRegion(value)}
+ sources={SOURCES}
+ pending={new Set()}
+ onSave={(_tool, body: HostedToolPut) => { if (body.executor_order) setOrder(body.executor_order); }}
+ onClear={() => {}}
+ onRetry={() => {}}
+ />
+ </I18nextProvider>
+ );
+ };
+ render(<Harness />);
+
+ await openAdvanced(user, 'Web search');
+ await user.click(screen.getByRole('button', { name: 'Move relay-gpt up' }));
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Move relay-gpt up' }));
+ await user.click(screen.getByRole('button', { name: 'Move relay-gpt up' }));
+ expect(screen.getAllByRole('listitem').map((row) => row.getAttribute('data-executor'))).toEqual([RELAY.id, GROK.id, CLAUDE.id]);
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Move relay-gpt down' }));
});
- it('MH-HOSTED-UI-018: says an enabled tool with nothing verified fails its calls, instead of naming a proxy', () => {
- renderTab(status([tool('x_search', {
- enabled: true,
- candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown }],
- })]));
- within(card('X search')).getByText('No Source is verified, so calls to it fail until you check one.');
+ it('MH-HOSTED-UI-003: prices each executor where a price is known, and never shows unknown as zero', async () => {
+ const user = userEvent.setup();
+ renderTab({
+ tools: [search('web_search', {
+ executor_candidates: [
+ candidate(GROK.id, 'grok-fast', { price: { ...PRICED, extra: [{ unit: 'post', usd_per_1k: 5 }] } }),
+ candidate(RELAY.id, 'gpt-6-mini', { relay: true }),
+ candidate(SUBSCRIPTION.id, 'gpt-6-mini', { price: PRICED }),
+ ],
+ })],
+ }, { lng: 'zh' });
+
+ await user.click(within(card('网页搜索')).getByRole('button', { name: /^高级/ }));
+ const [grok, relay, subscription] = within(card('网页搜索')).getAllByRole('listitem');
+ expect(grok.textContent).toContain('$0.005 / 次API 标价 · 另加 $0.005 / 条帖子');
+ expect(relay.textContent).toContain('暂无标价');
+ expect(relay.textContent).not.toContain('$0');
+ // A subscription is never billed per call, whatever list price its vendor has.
+ expect(subscription.textContent).toContain('订阅内含不另计费');
});
});
-
diff --git a/ui/src/components/settings/models/ToolsTab.tsx b/ui/src/components/settings/models/ToolsTab.tsx
index 0d70377c5..87699474e 100644
--- a/ui/src/components/settings/models/ToolsTab.tsx
+++ b/ui/src/components/settings/models/ToolsTab.tsx
@@ -1,87 +1,134 @@
-// 工具 — the hosted tools Vibey may call (`vibey-hosted-tools.md` §6.1, design.pen
-// frames E5IkUQ and XZjhj).
+// 工具 — the hosted tools Vibey may use (`vibey-hosted-tools.md` §8.1, design.pen
+// frames pDd61 and kPTBo).
//
-// One card per catalog tool: its toggle (off by default), the (Source, model)
-// pairs that could run it natively with their evidence and a check for each, and
-// the proxy executor that runs it for every other model. The read is a report:
-// hop resolution reads config and evidence itself, so nothing on this tab decides
-// a route, and every claim about one comes from `bound`, the server's answer.
+// One card per tool, grouped by capability, each with one switch, on by default.
+// A card says only what real use learned: the latest run, and the Sources that
+// refused, each of which the user can clear so it is tried again from the next
+// request. Nothing here checks a Source or decides a route.
import * as React from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-import { AtSign, Ban, Check, Globe, Image as ImageIcon, Info, Loader2, Radar, RotateCw, TriangleAlert, Waypoints } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { AlertCircle, ArrowDown, ArrowUp, AtSign, CheckCircle2, ChevronRight, Eraser, Globe, Image as ImageIcon, Info, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
-import { Select } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { ToggleSwitch } from '../SettingsPrimitives';
import { formatMonthDay, formatNameList, formatSmallUsd } from './format';
-import { ProbeAnswerNote } from './ProbeAnswerNote';
-import {
- evidenceChip,
- probeKey,
- probeUnanswered,
- sameExecutor,
- verifiedCandidates,
- type HostedEvidenceChip,
- type ProbeTarget,
-} from './hostedTools';
+import { executorOrderAfterMove, pairEvidence, refusalSummary, type PairEvidence, type RefusalSummary } from './hostedTools';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';
import type {
- HostedToolCandidate,
+ HostedExecutorCandidate,
+ HostedSearchToolStatus,
+ HostedToolClear,
HostedToolName,
HostedToolPriceUnit,
- HostedToolProbeResult,
HostedToolPut,
HostedToolsStatus,
HostedToolStatus,
Source,
} from './types';
-import { useEstimateLabel } from './useEstimateLabel';
-type RunProbe = (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+type Save = (tool: HostedToolName, body: HostedToolPut) => void;
+type Clear = (tool: HostedToolName, body: HostedToolClear) => void;
const TOOL_ICON: Record<HostedToolName, React.ComponentType<{ className?: string }>> = {
web_search: Globe,
x_search: AtSign,
- image_generation: ImageIcon,
+ image_generate: ImageIcon,
};
-const AUTOMATIC = '';
-const executorValue = (executor: { source_id: string; model_id: string } | null): string =>
- executor ? JSON.stringify([executor.source_id, executor.model_id]) : AUTOMATIC;
+/** The tab's groups, by capability, in catalog order. */
+const TOOL_GROUPS: { key: 'search' | 'generate'; tools: readonly HostedToolName[] }[] = [
+ { key: 'search', tools: ['web_search', 'x_search'] },
+ { key: 'generate', tools: ['image_generate'] },
+];
-/** The native-run cell: the call evidence, or 「未检测」 when there is none. */
-export const NativeEvidenceChip: React.FC<{ chip: HostedEvidenceChip | null }> = ({ chip }) => {
+type SourceLookup = { name: (id: string) => string; source: (id: string) => Source | undefined };
+
+const SourceGlyph: React.FC<{ source: Source | undefined }> = ({ source }) => {
+ const { Icon, accent } = source ? sourceVisual(source) : { Icon: Globe, accent: 'muted' as const };
+ return (
+ <span className={cn('flex size-[22px] shrink-0 items-center justify-center rounded-[6px]', ACCENT_TILE[accent])}>
+ <Icon className={cn('size-3', ACCENT_ICON[accent])} />
+ </span>
+ );
+};
+
+/** One status line: what real use showed, with a clear when this line owns one. */
+const StatusLine: React.FC<{ tone: 'ok' | 'refused'; text: string; clear?: { label: string; onClick: () => void; disabled: boolean } }> = ({ tone, text, clear }) => {
const { t } = useTranslation();
- if (chip === null) {
- return <span className="model-hub-pill model-hub-fill-0a border border-border text-muted">{t('settings.models.tools.chip.unchecked')}</span>;
- }
- const date = chip.at ? formatMonthDay(chip.at) : '';
- if (chip.kind === 'engineUpgraded') {
- return <span className="model-hub-pill model-hub-status-gold gap-1 border"><TriangleAlert className="size-3" aria-hidden />{t('settings.models.tools.chip.engineUpgraded')}</span>;
- }
- if (chip.aged) {
- return <span className="model-hub-pill model-hub-status-gold gap-1 border"><RotateCw className="size-3" aria-hidden />{t(chip.kind === 'native' ? 'settings.models.tools.chip.reverify' : 'settings.models.tools.chip.unsupportedAged', { date })}</span>;
- }
- return chip.kind === 'native'
- ? <span className="model-hub-pill model-hub-status-mint gap-1 border"><Check className="size-3" aria-hidden />{t('settings.models.tools.chip.native', { date })}</span>
- : <span className="model-hub-pill model-hub-fill-0a gap-1 border border-border text-muted"><Ban className="size-3" aria-hidden />{t('settings.models.tools.chip.unsupported')}</span>;
+ const Icon = tone === 'ok' ? CheckCircle2 : AlertCircle;
+ return (
+ <p className="model-hub-tool-status flex items-start gap-2 border-t border-border">
+ <Icon className={cn('mt-0.5 size-[14px] shrink-0', tone === 'ok' ? 'model-hub-ink-mint' : 'model-hub-ink-gold')} aria-hidden />
+ <span className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1">
+ <span className="min-w-0 text-foreground">{text}</span>
+ {clear && (
+ <button type="button" className="model-hub-accent-ink--cyan shrink-0 font-semibold disabled:opacity-50" aria-label={clear.label} disabled={clear.disabled} onClick={clear.onClick}>
+ {t('settings.models.tools.clear.label')}
+ </button>
+ )}
+ </span>
+ </p>
+ );
};
/**
- * What a call costs on this row: included on a subscription, else the overlay's
- * list price per unit (an estimate; a relay may bill differently). An image has
- * no per-image list price (it is billed per image token), and a price nobody
- * lists is said to be unknown, never shown as zero.
+ * The card's status lines, only after something happened. With one Source
+ * refused, its line names the models and carries the clear; with two or more,
+ * the lines name the Sources and the clears move into Advanced. A call line that
+ * says where the tool now runs stands in for the latest-run line.
*/
-const CostCell: React.FC<{ tool: HostedToolName; candidate: HostedToolCandidate }> = ({ tool, candidate }) => {
+const StatusLines: React.FC<{ tool: HostedToolStatus; summary: RefusalSummary; lookup: SourceLookup; pending: boolean; onClear: Clear }> = ({ tool, summary, lookup, pending, onClear }) => {
+ const { t, i18n } = useTranslation();
+ const latest = tool.status.latest_ok;
+ const inline = summary.sources === 1;
+ const toolInline = t(`settings.models.tools.tool.${tool.name}.inline`) as string;
+ const names = (groups: RefusalSummary['call']) => formatNameList(groups.map((group) => lookup.name(group.sourceId)), i18n.language);
+ const clearFor = (sourceId: string) => ({
+ label: t('settings.models.tools.clear.source', { source: lookup.name(sourceId), toolInline }) as string,
+ onClick: () => onClear(tool.name, { source_id: sourceId }),
+ disabled: pending,
+ });
+ const call = summary.call;
+ const callLine = call.length === 0
+ ? null
+ : inline
+ ? t('settings.models.tools.status.refused', { source: lookup.name(call[0].sourceId), models: formatNameList(call[0].models, i18n.language) }) as string
+ : t('settings.models.tools.status.refusedMany', { sources: names(call) }) as string;
+ const replay = summary.replay;
+ return (
+ <>
+ {latest && summary.switchedTo === null && (
+ <StatusLine tone="ok" text={t('settings.models.tools.status.ok', { source: lookup.name(latest.source_id), date: formatMonthDay(latest.at) }) as string} />
+ )}
+ {callLine !== null && (
+ <StatusLine
+ tone="refused"
+ text={summary.switchedTo === null
+ ? callLine
+ : t('settings.models.tools.status.switched', { line: callLine, source: lookup.name(summary.switchedTo) }) as string}
+ clear={inline ? clearFor(call[0].sourceId) : undefined}
+ />
+ )}
+ {replay.length > 0 && (
+ <StatusLine
+ tone="refused"
+ text={inline
+ ? t('settings.models.tools.status.replay', { source: lookup.name(replay[0].sourceId) }) as string
+ : t('settings.models.tools.status.replayMany', { sources: names(replay) }) as string}
+ clear={inline ? clearFor(replay[0].sourceId) : undefined}
+ />
+ )}
+ </>
+ );
+};
+
+/** What one executor call costs: included on a subscription, else the overlay's list price; unknown is never zero. */
+const ExecutorPrice: React.FC<{ candidate: HostedExecutorCandidate }> = ({ candidate }) => {
const { t } = useTranslation();
if (candidate.billing === 'monthly') {
- return <span className="flex min-w-0 flex-col"><span className="font-semibold text-foreground">{t('settings.models.tools.cost.included')}</span><span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.includedNote')}</span></span>;
- }
- if (tool === 'image_generation') {
- return <span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.imageTokens')}</span>;
+ return <span className="flex flex-col"><span className="font-semibold text-foreground">{t('settings.models.tools.cost.included')}</span><span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.includedNote')}</span></span>;
}
const price = candidate.price;
if (!price) return <span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.unknown')}</span>;
@@ -90,8 +137,8 @@ const CostCell: React.FC<{ tool: HostedToolName; candidate: HostedToolCandidate
unit: t(`settings.models.tools.cost.unit.${unit}`),
}) as string;
return (
- <span className="flex min-w-0 flex-col">
- <span className="font-semibold text-foreground">{t('settings.models.tools.cost.list', { price: perUnit(price.usd_per_1k, price.unit) })}</span>
+ <span className="flex flex-col">
+ <span className="font-semibold text-foreground">{perUnit(price.usd_per_1k, price.unit)}</span>
<span className="model-hub-tool-cost-note">
{price.extra.length === 0
? t('settings.models.tools.cost.listNote')
@@ -105,115 +152,239 @@ const CostCell: React.FC<{ tool: HostedToolName; candidate: HostedToolCandidate
);
};
-/** A row's check: run it now, with its cost on the button (§6.1: the probe's estimate shows first). */
-const ProbeCell: React.FC<{
- target: ProbeTarget;
- running: boolean;
- last: HostedToolProbeResult | null | undefined;
- onProbe: RunProbe;
- disabled: boolean;
-}> = ({ target, running, last, onProbe, disabled }) => {
+/**
+ * The search executors in the order the gateway tries them, for models that
+ * cannot run the search natively. Each move saves the whole order; Reset saves
+ * `null`, which is automatic. The order shown is always the server's.
+ */
+const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLookup; pending: boolean; onSave: Save }> = ({ tool, lookup, pending, onSave }) => {
const { t } = useTranslation();
- const estimate = useEstimateLabel()(target.candidate.probe_estimate);
- const checked = target.candidate.call.basis !== null;
- const unanswered = last !== undefined && probeUnanswered(last);
- // Every action that starts a paid request says what it is estimated to cost.
- const action = unanswered ? 'retry' : checked ? 'recheck' : 'check';
- const label = running
- ? t('settings.models.tools.probe.running')
- : t(`settings.models.tools.probe.${action}Cost`, { cost: estimate ?? t('settings.models.tools.probe.unknown') });
+ const toolInline = t(`settings.models.tools.tool.${tool.name}.inline`) as string;
+ const candidates = tool.executor_candidates;
+ const custom = tool.executor_order !== null;
+ // A move is announced, and focus follows the moved row, only once the server's
+ // order shows it. One that did not land (refused, or lost and reconciled to
+ // another order) is dropped once its write has been out and settled, without
+ // a word.
+ const [requested, setRequested] = React.useState<{
+ sourceId: string;
+ direction: -1 | 1;
+ expected: string;
+ position: number;
+ count: number;
+ /** Its write has been seen out, so the tool no longer pending means it settled. */
+ sent: boolean;
+ } | null>(null);
+ const shownOrder = candidates.map((candidate) => candidate.source_id).join('\n');
+ const landed = requested !== null && shownOrder === requested.expected;
+ if (requested !== null && !landed) {
+ if (pending && !requested.sent) setRequested({ ...requested, sent: true });
+ else if (!pending && requested.sent) setRequested(null);
+ }
+ const list = React.useRef<HTMLOListElement>(null);
+ const buttons = React.useRef(new Map<string, HTMLButtonElement>());
+ const focusedFor = React.useRef<typeof requested>(null);
+ React.useEffect(() => {
+ if (!landed || requested === null || focusedFor.current === requested) return;
+ focusedFor.current = requested;
+ // Only where focus still is the list: a user who has moved on is not pulled back.
+ const active = document.activeElement;
+ if (active !== null && active !== document.body && !list.current?.contains(active)) return;
+ const index = candidates.findIndex((candidate) => candidate.source_id === requested.sourceId);
+ const atEnd = requested.direction === -1 ? index === 0 : index === candidates.length - 1;
+ const direction = atEnd ? -requested.direction : requested.direction;
+ buttons.current.get(`${requested.sourceId}:${direction}`)?.focus();
+ }, [candidates, landed, requested]);
+ const move = (index: number, direction: -1 | 1) => {
+ if (pending) return;
+ const shown = candidates.map((candidate) => candidate.source_id);
+ setRequested({
+ sourceId: shown[index],
+ direction,
+ expected: executorOrderAfterMove(null, shown, index, direction).join('\n'),
+ position: index + direction + 1,
+ count: shown.length,
+ sent: false,
+ });
+ onSave(tool.name, { executor_order: executorOrderAfterMove(tool.executor_order, shown, index, direction) });
+ };
return (
- <span className="flex min-w-0 flex-col items-start gap-1 md:items-end">
- <Button
- variant="outline"
- size="xs"
- disabled={disabled || running}
- aria-busy={running}
- onClick={() => void onProbe(target)}
- title={estimate ?? undefined}
- >
- {running ? <Loader2 className="animate-spin" aria-hidden /> : checked || unanswered ? <RotateCw aria-hidden /> : <Radar aria-hidden />}
- {label}
- </Button>
- {last !== undefined && <ProbeAnswerNote result={last} />}
- </span>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <h4 className="font-semibold text-foreground">{t('settings.models.tools.order.title')}</h4>
+ <p className="model-hub-tool-note">{t(custom ? 'settings.models.tools.order.captionCustom' : 'settings.models.tools.order.caption')}</p>
+ </div>
+ {custom && (
+ <Button variant="outline" size="xs" disabled={pending} onClick={() => { setRequested(null); onSave(tool.name, { executor_order: null }); }}>
+ <RotateCcw aria-hidden />{t('settings.models.tools.order.reset')}
+ </Button>
+ )}
+ </div>
+ {candidates.length === 0
+ ? <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.order.empty', { toolInline })}</p>
+ : (
+ <ol ref={list} className="flex flex-col gap-1.5" aria-label={t('settings.models.tools.order.title') as string}>
+ {candidates.map((candidate, index) => {
+ const source = lookup.source(candidate.source_id);
+ const name = lookup.name(candidate.source_id);
+ const arrow = (direction: -1 | 1) => {
+ const blocked = direction === -1 ? index === 0 : index === candidates.length - 1;
+ return (
+ <Button
+ ref={(node) => {
+ const key = `${candidate.source_id}:${direction}`;
+ if (node) buttons.current.set(key, node);
+ else buttons.current.delete(key);
+ }}
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="model-hub-route-action model-hub-order-row-action"
+ aria-label={t(direction === -1 ? 'settings.models.tools.order.moveUp' : 'settings.models.tools.order.moveDown', { source: name }) as string}
+ // While a write is out the arrows stay focusable and do nothing:
+ // the next move must be built on the order that write answers.
+ aria-disabled={pending || undefined}
+ disabled={blocked}
+ onClick={() => move(index, direction)}
+ >
+ {direction === -1 ? <ArrowUp aria-hidden /> : <ArrowDown aria-hidden />}
+ </Button>
+ );
+ };
+ return (
+ <li key={candidate.source_id} className="model-hub-tool-executor-row grid items-center rounded-lg border border-border bg-background" data-executor={candidate.source_id}>
+ <span className={cn('model-hub-order-ordinal', index === 0 && 'is-first')}>{index + 1}</span>
+ <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
+ <SourceGlyph source={source} />
+ <span className="truncate font-semibold text-foreground" title={name}>{name}</span>
+ <span className="truncate font-mono text-muted" title={candidate.model_id}>{candidate.model_id}</span>
+ {source && <span className={cn('model-hub-pill border', ACCENT_PILL[source.kind === 'api_key' ? 'cyan' : sourceVisual(source).accent])}>{t(`settings.models.upstream.kind.${source.kind === 'subscription' ? 'subscription' : 'apiKey'}`)}</span>}
+ </span>
+ <ExecutorPrice candidate={candidate} />
+ <span className="flex items-center gap-1">{arrow(-1)}{arrow(1)}</span>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ <span role="status" className="sr-only">{landed && t('settings.models.tools.order.moved', { source: lookup.name(requested.sourceId), position: requested.position, count: requested.count })}</span>
+ </div>
);
};
-const CandidateRow: React.FC<{
- tool: HostedToolName;
- candidate: HostedToolCandidate;
- source: Source | undefined;
- executor: boolean;
- probe: { running: boolean; last: HostedToolProbeResult | null | undefined; run: RunProbe; disabled: boolean } | null;
-}> = ({ tool, candidate, source, executor, probe }) => {
+/** One (Source, model)'s record on the tool, as the Advanced status list states it. */
+const PairRow: React.FC<{ tool: HostedToolName; pair: PairEvidence; lookup: SourceLookup; pending: boolean; onClear: Clear }> = ({ tool, pair, lookup, pending, onClear }) => {
const { t } = useTranslation();
- const { Icon, accent } = source ? sourceVisual(source) : { Icon: Globe, accent: 'muted' as const };
- const name = source?.display_name ?? candidate.source_id;
+ const name = lookup.name(pair.sourceId);
+ const refusal = pair.kind === 'refused' ? pair.refusal : null;
+ const date = formatMonthDay(pair.kind === 'refused' ? pair.refusal.at : pair.success.at);
return (
- <div className="model-hub-tool-row grid items-center rounded-lg border border-border bg-background" data-candidate={`${candidate.source_id}:${candidate.model_id}`}>
- <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
- <span className={cn('flex size-[26px] shrink-0 items-center justify-center rounded-[7px]', ACCENT_TILE[accent])}><Icon className={cn('size-[13px]', ACCENT_ICON[accent])} /></span>
+ <li className="model-hub-tool-pair-row grid items-center rounded-lg border border-border bg-background" data-pair={`${pair.sourceId}:${pair.modelId}`}>
+ <span className="flex min-w-0 items-center gap-2">
+ <SourceGlyph source={lookup.source(pair.sourceId)} />
<span className="truncate font-semibold text-foreground" title={name}>{name}</span>
- <span className="truncate font-mono text-muted" title={candidate.model_id}>{candidate.model_id}</span>
- {source && <span className={cn('model-hub-pill border', ACCENT_PILL[source.kind === 'api_key' ? 'cyan' : accent])}>{t(`settings.models.upstream.kind.${source.kind === 'subscription' ? 'subscription' : 'apiKey'}`)}</span>}
- </span>
- <span className="flex min-w-0 flex-wrap items-center gap-1.5">
- <NativeEvidenceChip chip={evidenceChip(candidate.call)} />
- {executor && <span className="model-hub-pill gap-1 model-hub-accent-pill--cyan border"><Waypoints className="size-3" aria-hidden />{t('settings.models.tools.chip.executor')}</span>}
+ <span className="truncate font-mono text-muted" title={pair.modelId}>{pair.modelId}</span>
</span>
- <CostCell tool={tool} candidate={candidate} />
- {probe
- ? <ProbeCell target={{ tool, candidate }} running={probe.running} last={probe.last} onProbe={probe.run} disabled={probe.disabled} />
+ {refusal
+ ? (
+ <span className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1">
+ <span className="model-hub-pill model-hub-status-gold gap-1 border"><AlertCircle className="size-3" aria-hidden />{t(refusal.aspect === 'call' ? 'settings.models.tools.pair.refused' : 'settings.models.tools.pair.replay', { date })}</span>
+ {refusal.reason && <span className="truncate font-mono text-muted" title={refusal.reason}>{refusal.reason}</span>}
+ </span>
+ )
+ : <span className="model-hub-pill model-hub-status-mint gap-1 border"><CheckCircle2 className="size-3" aria-hidden />{t('settings.models.tools.pair.ok', { date })}</span>}
+ {refusal
+ ? (
+ <button
+ type="button"
+ className="model-hub-accent-ink--cyan justify-self-end font-semibold disabled:opacity-50"
+ aria-label={t('settings.models.tools.clear.model', { source: name, model: pair.modelId, toolInline: t(`settings.models.tools.tool.${tool}.inline`) }) as string}
+ disabled={pending}
+ onClick={() => onClear(tool, { source_id: pair.sourceId, model_id: pair.modelId })}
+ >
+ {t('settings.models.tools.clear.label')}
+ </button>
+ )
: <span />}
+ </li>
+ );
+};
+
+/** Every (Source, model) with a record, with the clears, once two or more Sources refused. */
+const SourceStatusList: React.FC<{ tool: HostedToolStatus; lookup: SourceLookup; pending: boolean; onClear: Clear }> = ({ tool, lookup, pending, onClear }) => {
+ const { t } = useTranslation();
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <h4 className="font-semibold text-foreground">{t('settings.models.tools.sources.title')}</h4>
+ <p className="model-hub-tool-note">{t('settings.models.tools.sources.caption')}</p>
+ </div>
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={pending}
+ aria-label={t('settings.models.tools.clear.allLabel', { toolInline: t(`settings.models.tools.tool.${tool.name}.inline`) }) as string}
+ onClick={() => onClear(tool.name, {})}
+ >
+ <Eraser aria-hidden />{t('settings.models.tools.clear.all')}
+ </Button>
+ </div>
+ <ul className="flex flex-col gap-1.5">
+ {pairEvidence(tool.status).map((pair) => (
+ <PairRow key={`${pair.sourceId}:${pair.modelId}`} tool={tool.name} pair={pair} lookup={lookup} pending={pending} onClear={onClear} />
+ ))}
+ </ul>
</div>
);
};
-const ToolCard: React.FC<{
- tool: HostedToolStatus;
- sources: ReadonlyMap<string, Source>;
- hubSources: readonly Source[];
- pending: boolean;
- probing: ReadonlySet<string>;
- lastProbes: ReadonlyMap<string, HostedToolProbeResult | null>;
- onChange: (tool: HostedToolName, body: HostedToolPut) => void;
- onProbe: RunProbe;
-}> = ({ tool, sources, hubSources, pending, probing, lastProbes, onChange, onProbe }) => {
- const { t, i18n } = useTranslation();
+/**
+ * The collapsed Advanced section: a search tool's executor order, and every
+ * tool's clears once two or more Sources refused it. A card with neither has
+ * no Advanced section.
+ */
+const Advanced: React.FC<{ tool: HostedToolStatus; summary: RefusalSummary; lookup: SourceLookup; pending: boolean; onSave: Save; onClear: Clear }> = ({ tool, summary, lookup, pending, onSave, onClear }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = React.useState(false);
+ const bodyId = React.useId();
+ const search = tool.name === 'image_generate' ? null : tool;
+ const statusList = summary.sources >= 2;
+ if (!search && !statusList) return null;
+ const order = search
+ ? t(search.executor_order === null ? 'settings.models.tools.order.summaryAuto' : 'settings.models.tools.order.summaryCustom') as string
+ : null;
+ const label = order === null
+ ? t('settings.models.tools.sources.title') as string
+ : statusList
+ ? t('settings.models.tools.advanced.summaryBoth', { order, sources: t('settings.models.tools.sources.title') }) as string
+ : order;
+ return (
+ <div className="model-hub-tool-advanced flex flex-col border-t border-border">
+ <button type="button" className="model-hub-tool-advanced-toggle flex items-center gap-2 text-left" aria-expanded={open} aria-controls={bodyId} onClick={() => setOpen((previous) => !previous)}>
+ <ChevronRight className={cn('size-[14px] shrink-0 text-muted transition-transform', open && 'rotate-90')} aria-hidden />
+ <span className="font-semibold text-foreground">{t('settings.models.tools.advanced.label')}</span>
+ {!open && <span className="truncate text-muted">{label}</span>}
+ </button>
+ {open && (
+ <div id={bodyId} className="model-hub-tool-advanced-body flex flex-col gap-4">
+ {search && <ExecutorOrder tool={search} lookup={lookup} pending={pending} onSave={onSave} />}
+ {statusList && <SourceStatusList tool={tool} lookup={lookup} pending={pending} onClear={onClear} />}
+ </div>
+ )}
+ </div>
+ );
+};
+
+const ToolCard: React.FC<{ tool: HostedToolStatus; lookup: SourceLookup; pending: boolean; onSave: Save; onClear: Clear }> = ({ tool, lookup, pending, onSave, onClear }) => {
+ const { t } = useTranslation();
const Icon = TOOL_ICON[tool.name];
const name = t(`settings.models.tools.tool.${tool.name}.name`) as string;
- const toolInline = t(`settings.models.tools.tool.${tool.name}.inline`) as string;
- const verified = verifiedCandidates(tool);
- // What a turn would bind now: the server's own answer, so the card claims no
- // routing it cannot see.
- const bound = tool.bound;
- const sourceName = (id: string) => sources.get(id)?.display_name ?? id;
- // Sources with no (Source, model) pair that could run this tool natively.
- const offering = new Set(tool.candidates.map((candidate) => candidate.source_id));
- const withoutNative = hubSources.filter((source) => !offering.has(source.id)).map((source) => source.display_name);
- // The saved executor as the server would accept it back: a pair still among the
- // candidates. One that left them (its Source or model went away, or the overlay
- // stopped offering the tool there) is refused on write, and resolution already
- // skips it, so it reads and writes as Automatic.
- const savedExecutor = tool.executor && tool.candidates.some((candidate) => sameExecutor(candidate, tool.executor))
- ? tool.executor
- : null;
- // A stored choice that is no longer verified still shows, so the picker never
- // silently reads as a different executor than the one saved.
- const options = savedExecutor && !verified.some((candidate) => sameExecutor(candidate, savedExecutor))
- ? [...verified, { ...savedExecutor, stale: true as const }]
- : verified;
- // With nothing verified there is nothing to pick, but a saved choice still reads as itself.
- const pickable = verified.length > 0;
- // Turning a tool on needs an executor the server binds (`bound`): on without
- // one, every proxied call would fail. A verified pair Automatic cannot bind (its
- // Source is outside Vibey's order) is picked explicitly, which binds it. Turning
- // a tool off is always possible.
- const locked = !tool.enabled && bound === null;
+ const summary = refusalSummary(tool.status);
return (
<section className="model-hub-tool-card overflow-hidden rounded-xl border border-border bg-surface" aria-label={name} data-tool={tool.name}>
- <header className="model-hub-tool-card-head flex items-center gap-3 border-b border-border">
+ <header className="model-hub-tool-card-head flex items-center gap-3">
<span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE.cyan)}><Icon className={cn('size-[17px]', ACCENT_ICON.cyan)} /></span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="flex min-w-0 flex-wrap items-center gap-2">
@@ -223,150 +394,46 @@ const ToolCard: React.FC<{
<span className="model-hub-tool-description">{t(`settings.models.tools.tool.${tool.name}.description`)}</span>
</span>
<span className="flex shrink-0 items-center gap-2.5">
- <span className={cn('model-hub-tool-state font-semibold', tool.enabled ? 'model-hub-ink-mint' : 'text-muted')}>{t(tool.enabled
- ? 'settings.models.tools.state.on'
- : !locked
- ? 'settings.models.tools.state.off'
- : pickable
- ? 'settings.models.tools.state.needsExecutor'
- : 'settings.models.tools.state.needsCheck')}</span>
+ <span className={cn('model-hub-tool-state font-semibold', tool.enabled ? 'model-hub-ink-mint' : 'text-muted')}>{t(tool.enabled ? 'settings.models.tools.state.on' : 'settings.models.tools.state.off')}</span>
<ToggleSwitch
enabled={tool.enabled}
- disabled={pending || locked}
+ disabled={pending}
label={t(tool.enabled ? 'settings.models.tools.toggle.turnOff' : 'settings.models.tools.toggle.turnOn', { name }) as string}
- onClick={() => onChange(tool.name, { enabled: !tool.enabled, executor: savedExecutor })}
+ onClick={() => onSave(tool.name, { enabled: !tool.enabled })}
/>
</span>
</header>
- <div className="model-hub-tool-table flex flex-col gap-2">
- {tool.candidates.length === 0
- ? <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.empty', { toolInline })}</p>
- : <>
- <div className="model-hub-tool-table-head hidden font-semibold md:grid" aria-hidden>
- <span>{t('settings.models.tools.col.source')}</span>
- <span>{t('settings.models.tools.col.native')}</span>
- <span>{t('settings.models.tools.col.cost')}</span>
- <span />
- </div>
- {tool.candidates.map((candidate) => {
- const key = probeKey({ tool: tool.name, candidate });
- return (
- <CandidateRow
- key={key}
- tool={tool.name}
- candidate={candidate}
- source={sources.get(candidate.source_id)}
- executor={tool.enabled && sameExecutor(candidate, bound)}
- probe={{ running: probing.has(key), last: lastProbes.get(key), run: onProbe, disabled: probing.size > 0 && !probing.has(key) }}
- />
- );
- })}
- {withoutNative.length > 0 && <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.noNative', { sources: formatNameList(withoutNative, i18n.language), toolInline })}</p>}
- </>}
- </div>
- <div className="model-hub-tool-executor flex flex-col gap-2 border-t border-border sm:flex-row sm:items-center sm:gap-3">
- <span className="shrink-0 font-semibold text-foreground">{t('settings.models.tools.executor.label')}</span>
- <Select
- wrapperClassName="sm:w-[330px] shrink-0"
- className="h-8 text-[12px]"
- aria-label={t('settings.models.tools.executor.pick', { name }) as string}
- disabled={pending || !pickable}
- value={executorValue(savedExecutor)}
- onChange={(event) => {
- const picked = options.find((option) => executorValue(option) === event.target.value);
- onChange(tool.name, {
- enabled: tool.enabled,
- executor: picked ? { source_id: picked.source_id, model_id: picked.model_id } : null,
- });
- }}
- >
- {!pickable && savedExecutor === null
- ? <option value={AUTOMATIC}>{t('settings.models.tools.executor.unavailable')}</option>
- : <>
- {pickable && (
- <option value={AUTOMATIC}>
- {/* Automatic names what it resolves to now, when the saved choice is Automatic. */}
- {savedExecutor === null && bound
- ? t('settings.models.tools.executor.automaticBound', { source: sourceName(bound.source_id), model: bound.model_id })
- : t('settings.models.tools.executor.automatic')}
- </option>
- )}
- {options.map((option) => (
- <option key={executorValue(option)} value={executorValue(option)}>
- {'stale' in option
- ? t('settings.models.tools.executor.notVerified', { source: sourceName(option.source_id), model: option.model_id })
- : t('settings.models.tools.executor.option', { source: sourceName(option.source_id), model: option.model_id })}
- </option>
- ))}
- </>}
- </Select>
- <span className="model-hub-tool-note">
- {/* A routing claim holds only while the tool is on: resolution leaves an
- off tool out entirely, so its executor is just a saved preference. */}
- {!tool.enabled
- ? t('settings.models.tools.executor.note.off')
- : bound
- ? t('settings.models.tools.executor.note.bound', { source: sourceName(bound.source_id) })
- : t('settings.models.tools.executor.note.unbound')}
- </span>
- </div>
+ <StatusLines tool={tool} summary={summary} lookup={lookup} pending={pending} onClear={onClear} />
+ <Advanced tool={tool} summary={summary} lookup={lookup} pending={pending} onSave={onSave} onClear={onClear} />
</section>
);
};
export const ToolsTab: React.FC<{
read: RegionRead<HostedToolsStatus>;
- /** The Sources read, for names and glyphs; candidates carry only ids. */
+ /** The Sources read, for names and glyphs; the status carries only ids. */
sources: readonly Source[];
pending: ReadonlySet<HostedToolName>;
- /** Probe keys (`probeKey`) running now. */
- probing: ReadonlySet<string>;
- onChange: (tool: HostedToolName, body: HostedToolPut) => void;
- onProbe: RunProbe;
+ onSave: Save;
+ onClear: Clear;
onRetry: () => void;
-}> = ({ read, sources, pending, probing, onChange, onProbe, onRetry }) => {
+}> = ({ read, sources, pending, onSave, onClear, onRetry }) => {
const { t } = useTranslation();
- // A row's last answer that did not become evidence (inconclusive, transient, a
- // failed request) shows where it was asked, until that row is checked again.
- const [lastProbes, setLastProbes] = React.useState<ReadonlyMap<string, HostedToolProbeResult | null>>(() => new Map());
- const runProbe = React.useCallback<RunProbe>(async (target) => {
- const result = await onProbe(target);
- setLastProbes((previous) => new Map(previous).set(probeKey(target), result));
- return result;
- }, [onProbe]);
const status = foldRegionRead<HostedToolsStatus, HostedToolsStatus | null>(read, {
loading: () => null,
ready: (data) => data,
unread: () => null,
degraded: (staleData) => staleData,
});
- const byId = React.useMemo(() => new Map(sources.map((source) => [source.id, source])), [sources]);
- const hubSources = React.useMemo(() => sources.filter((source) => source.supply_channel === 'hub'), [sources]);
- const reverify = status?.reverify;
+ const lookup = React.useMemo<SourceLookup>(() => {
+ const byId = new Map(sources.map((source) => [source.id, source]));
+ return { name: (id) => byId.get(id)?.display_name ?? id, source: (id) => byId.get(id) };
+ }, [sources]);
return (
<section className="model-hub-tools flex flex-col" aria-label={t('settings.models.tools.title') as string}>
- <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
- <div className="flex min-w-0 flex-col gap-1">
- <h2 className="model-hub-tools-title font-bold text-foreground">{t('settings.models.tools.title')}</h2>
- <p className="model-hub-tools-subtitle">{t('settings.models.tools.subtitle')}</p>
- </div>
- <div className="flex shrink-0 flex-col items-start gap-1.5 sm:items-end">
- {reverify && (reverify.engine_upgraded > 0 || reverify.aged > 0) && (
- <p className="model-hub-tools-reverify flex flex-wrap items-center gap-x-2" role="status">
- {/* Both counts read as one sentence the locale composes. */}
- <Trans
- i18nKey={reverify.engine_upgraded > 0
- ? reverify.aged > 0 ? 'settings.models.tools.reverify.both' : 'settings.models.tools.reverify.upgradedOnly'
- : 'settings.models.tools.reverify.agedOnly'}
- values={{
- engineUpgraded: t('settings.models.tools.reverify.engineUpgraded', { count: reverify.engine_upgraded }),
- aged: t('settings.models.tools.reverify.aged', { count: reverify.aged }),
- }}
- components={{ upgraded: <span className="model-hub-ink-gold font-semibold" /> }}
- />
- </p>
- )}
- </div>
+ <div className="flex min-w-0 flex-col gap-1">
+ <h2 className="model-hub-tools-title font-bold text-foreground">{t('settings.models.tools.title')}</h2>
+ <p className="model-hub-tools-subtitle">{t('settings.models.tools.subtitle')}</p>
</div>
{regionFailed(read) && (
<div className="model-hub-usage-failure flex items-center justify-between gap-3 rounded-xl border border-border bg-background text-destructive-ink">
@@ -377,19 +444,18 @@ export const ToolsTab: React.FC<{
{status === null
? read.kind === 'loading' && <p className="model-hub-usage-pending text-muted">{t('common.loading')}</p>
: <>
- {status.tools.map((tool) => (
- <ToolCard
- key={tool.name}
- tool={tool}
- sources={byId}
- hubSources={hubSources}
- pending={pending.has(tool.name)}
- probing={probing}
- lastProbes={lastProbes}
- onChange={onChange}
- onProbe={runProbe}
- />
- ))}
+ {TOOL_GROUPS.map((group) => {
+ const tools = group.tools.flatMap((name) => status.tools.filter((tool) => tool.name === name));
+ if (tools.length === 0) return null;
+ return (
+ <section key={group.key} className="model-hub-tool-group flex flex-col" aria-label={t(`settings.models.tools.group.${group.key}`) as string}>
+ <h3 className="model-hub-tool-group-title font-semibold">{t(`settings.models.tools.group.${group.key}`)}</h3>
+ {tools.map((tool) => (
+ <ToolCard key={tool.name} tool={tool} lookup={lookup} pending={pending.has(tool.name)} onSave={onSave} onClear={onClear} />
+ ))}
+ </section>
+ );
+ })}
<p className="model-hub-tools-foot">{t('settings.models.tools.footnote')}</p>
</>}
</section>
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
index b72932254..5cc35f7a2 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: 14,
+ contract_version: 15,
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.ts
index ed291ead6..f9bc15ad7 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: 14,
+ contract_version: 15,
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/hostedTools.test.ts b/ui/src/components/settings/models/hostedTools.test.ts
index 1d195edb0..1ff02ddaf 100644
--- a/ui/src/components/settings/models/hostedTools.test.ts
+++ b/ui/src/components/settings/models/hostedTools.test.ts
@@ -1,65 +1,91 @@
import { describe, expect, it } from 'vitest';
-import { evidenceChip, modelCapabilities } from './hostedTools';
-import type { HostedEvidence, HostedToolCandidate } from './types';
+import { executorOrderAfterMove, modelCapabilities, pairEvidence, refusalSummary } from './hostedTools';
+import type { HostedRefusal, HostedSuccess, HostedToolRunStatus, HostedToolsStatus } from './types';
-const evidence = (overrides: Partial<HostedEvidence>): HostedEvidence => ({
- status: 'unknown',
- stale: null,
- basis: null,
- observed_at: null,
- detail: null,
- changes_at: null,
- ...overrides,
+const RELAY = 'src_relay001';
+const SUB = 'src_chatgpt1';
+const CLAUDE = 'src_claude01';
+
+const ok = (sourceId: string, modelId: string, at: string): HostedSuccess => ({ source_id: sourceId, model_id: modelId, mode: 'native', at });
+const refused = (sourceId: string, modelId: string, at: string, aspect: HostedRefusal['aspect'] = 'call'): HostedRefusal => ({
+ source_id: sourceId, model_id: modelId, aspect, at, reason: '400 unsupported_tool_type',
});
+const run = (over: Partial<HostedToolRunStatus>): HostedToolRunStatus => ({ latest_ok: null, verified: [], refused: [], ...over });
-const AT = '2026-10-13T10:20:00Z';
+describe('hosted-tool status projection', () => {
+ it('MH-HOSTED-UI-002: groups refusals by aspect and Source, with each group\'s models and newest time', () => {
+ const summary = refusalSummary(run({
+ refused: [
+ refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z'),
+ refused(RELAY, 'gpt-6-luna', '2026-10-14T11:00:00Z'),
+ refused(SUB, 'gpt-6.1-sol', '2026-10-14T10:00:00Z', 'replay'),
+ ],
+ }));
-const candidate = (sourceId: string, modelId: string, call: HostedEvidence): HostedToolCandidate => ({
- source_id: sourceId,
- model_id: modelId,
- call,
- replay: null,
- billing: 'metered',
- price: null,
- probe_estimate: null,
-});
+ expect(summary.call).toEqual([{ sourceId: RELAY, aspect: 'call', models: ['gpt-6-astra', 'gpt-6-luna'], at: '2026-10-14T11:00:00Z' }]);
+ expect(summary.replay).toEqual([{ sourceId: SUB, aspect: 'replay', models: ['gpt-6.1-sol'], at: '2026-10-14T10:00:00Z' }]);
+ expect(summary.sources).toBe(2);
+ });
+
+ it('MH-HOSTED-UI-002: leaves a Source that refused the call out of the replay line, so it counts once', () => {
+ const summary = refusalSummary(run({
+ refused: [refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z'), refused(RELAY, 'gpt-6-luna', '2026-10-14T09:00:00Z', 'replay')],
+ }));
+
+ expect(summary.call.map((group) => group.sourceId)).toEqual([RELAY]);
+ expect(summary.replay).toEqual([]);
+ expect(summary.sources).toBe(1);
+ });
-describe('hosted-tool evidence projection', () => {
- // Every evidence shape the status read can carry (hosted-tools-status.schema.json),
- // and the chip each one owes the user. A wire-stale record reads `unknown` for
- // routing, so a projection keyed on `status` alone would hide that it was
- // ever checked, and the engine-upgrade re-check would have no row to point at.
- const cases: [string, HostedEvidence, ReturnType<typeof evidenceChip>][] = [
- ['no record', evidence({}), null],
- ['verified on the current engine', evidence({ status: 'verified', basis: 'probe', observed_at: AT }), { kind: 'native', aged: false, at: AT }],
- ['verified, older than 30 days', evidence({ status: 'verified', stale: 'age', basis: 'probe', observed_at: AT }), { kind: 'native', aged: true, at: AT }],
- ['taken on another engine', evidence({ status: 'unknown', stale: 'wire', basis: 'probe', observed_at: AT }), { kind: 'engineUpgraded', aged: false, at: AT }],
- ['refused by a probe', evidence({ status: 'unsupported', basis: 'probe', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: false, at: AT }],
- // An old refusal still routes, but it is counted in `reverify.aged`, so its
- // row has to say which record that count is about.
- ['refused by a probe older than 30 days', evidence({ status: 'unsupported', stale: 'age', basis: 'probe', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: true, at: AT }],
- ['refused by a real request', evidence({ status: 'unsupported', basis: 'observed', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: false, at: AT }],
+ // "已改用" claims the tool has run elsewhere since every refusal: it needs a
+ // later success, on a Source that is not among the refusing ones.
+ const switched: [string, Partial<HostedToolRunStatus>, string | null][] = [
+ ['a later success on another Source', { latest_ok: ok(CLAUDE, 'claude-haiku-5-5', '2026-10-15T08:00:00Z') }, CLAUDE],
+ ['no success since', { latest_ok: ok(CLAUDE, 'claude-haiku-5-5', '2026-10-13T08:00:00Z') }, null],
+ ['the success is on the refusing Source', { latest_ok: ok(RELAY, 'gpt-6-sol', '2026-10-15T08:00:00Z') }, null],
+ ['no success at all', {}, null],
];
- it('MH-HOSTED-UI-002: gives every evidence shape the chip it owes the user', () => {
- for (const [name, call, chip] of cases) expect(evidenceChip(call), name).toEqual(chip);
+ it.each(switched)('MH-HOSTED-UI-002: says where the tool runs now only after %s', (_name, over, expected) => {
+ expect(refusalSummary(run({ refused: [refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z')], ...over })).switchedTo).toBe(expected);
});
- it('MH-HOSTED-UI-006: gives a Source model one capability per tool with evidence, in catalog order', () => {
- const verified = evidence({ status: 'verified', basis: 'probe', observed_at: AT });
- const refused = evidence({ status: 'unsupported', basis: 'observed', observed_at: AT, detail: '400 · unsupported_tool_type' });
- const status = {
+ it('MH-HOSTED-UI-006: gives each pair one record, a refusal over a success and a call refusal over a replay one', () => {
+ const lastOk = ok(RELAY, 'gpt-6-astra', '2026-10-13T08:00:00Z');
+ const pairs = pairEvidence(run({
+ verified: [lastOk, ok(CLAUDE, 'claude-haiku-5-5', '2026-10-15T08:00:00Z')],
+ refused: [
+ refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z', 'replay'),
+ refused(RELAY, 'gpt-6-astra', '2026-10-14T10:00:00Z'),
+ ],
+ }));
+
+ expect(pairs).toEqual([
+ { kind: 'ok', sourceId: CLAUDE, modelId: 'claude-haiku-5-5', success: ok(CLAUDE, 'claude-haiku-5-5', '2026-10-15T08:00:00Z') },
+ { kind: 'refused', sourceId: RELAY, modelId: 'gpt-6-astra', refusal: refused(RELAY, 'gpt-6-astra', '2026-10-14T10:00:00Z'), lastOk },
+ ]);
+ });
+
+ it('MH-HOSTED-UI-006: gives a Source model one capability per tool with a record, in catalog order', () => {
+ const status: HostedToolsStatus = {
tools: [
- { name: 'web_search' as const, enabled: true, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', verified)] },
- { name: 'x_search' as const, enabled: true, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', refused)] },
- // Unchecked draws nothing: absence is the normal state, not a problem.
- { name: 'image_generation' as const, enabled: false, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', evidence({}))] },
+ { name: 'web_search', enabled: true, status: run({ verified: [ok(RELAY, 'gpt-6-astra', '2026-10-15T08:00:00Z')] }), executor_order: null, effective_order: [], executor_candidates: [] },
+ { name: 'x_search', enabled: true, status: run({ refused: [refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z')] }), executor_order: null, effective_order: [], executor_candidates: [] },
+ // No record draws nothing: unused is the normal state, not a problem.
+ { name: 'image_generate', enabled: true, status: run({}), default_model: null, effective_default: null, models: [], image_offered_by: [] },
],
- reverify: { engine_upgraded: 0, aged: 0 },
};
- expect(modelCapabilities(status, 'src_relay001', 'gpt-6-astra').map(({ tool, chip }) => [tool, chip.kind]))
- .toEqual([['web_search', 'native'], ['x_search', 'unsupported']]);
- expect(modelCapabilities(status, 'src_relay001', 'gpt-6-sol')).toEqual([]);
+ expect(modelCapabilities(status, RELAY, 'gpt-6-astra').map(({ tool, evidence }) => [tool, evidence.kind]))
+ .toEqual([['web_search', 'ok'], ['x_search', 'refused']]);
+ expect(modelCapabilities(status, RELAY, 'gpt-6-sol')).toEqual([]);
+ });
+
+ it('MH-HOSTED-UI-021: moves only the shown executors within the saved order, keeping hidden ones in place', () => {
+ // H is saved but not shown now (refused, or gone for a while); C is shown but not saved.
+ expect(executorOrderAfterMove(['A', 'H', 'B'], ['A', 'B', 'C'], 2, -1)).toEqual(['A', 'H', 'C', 'B']);
+ expect(executorOrderAfterMove(['H', 'A', 'B'], ['A', 'B'], 1, -1)).toEqual(['H', 'B', 'A']);
+ // Automatic: the shown order is the whole order.
+ expect(executorOrderAfterMove(null, ['A', 'B'], 0, 1)).toEqual(['B', 'A']);
});
});
diff --git a/ui/src/components/settings/models/hostedTools.ts b/ui/src/components/settings/models/hostedTools.ts
index cb9e0e266..3e17af4cc 100644
--- a/ui/src/components/settings/models/hostedTools.ts
+++ b/ui/src/components/settings/models/hostedTools.ts
@@ -1,78 +1,114 @@
-// What the Tools tab and the Source chips say about hosted-tool evidence
-// (`vibey-hosted-tools.md` §6.1–§6.2). Pure projections of the Tools-tab read
-// (`hosted-tools-status.schema.json`): the server has already folded staleness
-// into `status`, so nothing here re-derives routing.
-import type {
- HostedEvidence,
- HostedToolCandidate,
- HostedToolExecutor,
- HostedToolName,
- HostedToolProbeResult,
- HostedToolsStatus,
- HostedToolStatus,
-} from './types';
+// What the Tools tab and the Source chips say about hosted tools
+// (`vibey-hosted-tools.md` §8). Pure projections of the Tools-tab read
+// (`hosted-tools-status.schema.json`): positive records are display only,
+// refusals are routing state until the user clears them, and nothing here
+// decides a route.
+import type { HostedRefusal, HostedSuccess, HostedToolName, HostedToolRunStatus, HostedToolsStatus } from './types';
-/**
- * One call-evidence record as a chip.
- *
- * - `native`: verified; the tool runs natively.
- * - `unsupported`: the Source refused the tool, by probe or by a real error.
- * - `engineUpgraded`: taken on another engine or probe shape. It routes as
- * unknown, i.e. through the proxy, until the user checks again.
- *
- * `aged` marks a probe record older than 30 days, whichever way it went: it
- * still routes as recorded and only asks for a new check.
- *
- * `null` is no record: unchecked, which is the normal state and draws no chip
- * on a Source (§6.2).
- */
-export type HostedEvidenceChip = {
- kind: 'native' | 'unsupported' | 'engineUpgraded';
- aged: boolean;
- at: string | null;
+const time = (at: string): number => Date.parse(at);
+
+/** One Source's refusals of a tool on one aspect: the models it refused, and when it last did. */
+export type RefusalGroup = { sourceId: string; aspect: HostedRefusal['aspect']; models: string[]; at: string };
+
+export type RefusalSummary = {
+ /** Sources that refused the tool itself. */
+ call: RefusalGroup[];
+ /** Sources that still run the tool but refused earlier results sent back to it. */
+ replay: RefusalGroup[];
+ /** Distinct Sources across both lines; with two or more, the clears move into Advanced. */
+ sources: number;
+ /** The Source the tool has run on since every call refusal, when that is another Source. */
+ switchedTo: string | null;
};
-export const evidenceChip = (evidence: HostedEvidence): HostedEvidenceChip | null => {
- // Staleness first: a wire-stale record reads `unknown` but still has a past
- // the user needs to see, whatever it once said.
- if (evidence.stale === 'wire') return { kind: 'engineUpgraded', aged: false, at: evidence.observed_at };
- const aged = evidence.stale === 'age';
- if (evidence.status === 'verified') return { kind: 'native', aged, at: evidence.observed_at };
- if (evidence.status === 'unsupported') return { kind: 'unsupported', aged, at: evidence.observed_at };
- return null;
+/**
+ * The refusal lines of one tool. A Source that refused the call is left out of
+ * the replay line: replay is moot where the tool is not declared natively.
+ */
+export const refusalSummary = (status: HostedToolRunStatus): RefusalSummary => {
+ const groups = new Map<string, RefusalGroup>();
+ for (const refusal of status.refused) {
+ const key = `${refusal.aspect}:${refusal.source_id}`;
+ const group = groups.get(key);
+ if (!group) {
+ groups.set(key, { sourceId: refusal.source_id, aspect: refusal.aspect, models: [refusal.model_id], at: refusal.at });
+ continue;
+ }
+ if (!group.models.includes(refusal.model_id)) group.models.push(refusal.model_id);
+ if (time(refusal.at) > time(group.at)) group.at = refusal.at;
+ }
+ const call = [...groups.values()].filter((group) => group.aspect === 'call');
+ const callSources = new Set(call.map((group) => group.sourceId));
+ const replay = [...groups.values()].filter((group) => group.aspect === 'replay' && !callSources.has(group.sourceId));
+ const latest = status.latest_ok;
+ const switchedTo = latest !== null
+ && call.length > 0
+ && !callSources.has(latest.source_id)
+ && call.every((group) => time(group.at) < time(latest.at))
+ ? latest.source_id
+ : null;
+ return { call, replay, sources: call.length + replay.length, switchedTo };
};
-export const sameExecutor = (left: HostedToolExecutor | null, right: HostedToolExecutor | null): boolean =>
- left !== null && right !== null && left.source_id === right.source_id && left.model_id === right.model_id;
+/** One (Source, model) on a tool, as the Advanced status list and the Source chips show it. */
+export type PairEvidence =
+ | { kind: 'ok'; sourceId: string; modelId: string; success: HostedSuccess }
+ | { kind: 'refused'; sourceId: string; modelId: string; refusal: HostedRefusal; lastOk: HostedSuccess | null };
-/** The candidates a user may pick as executor: those verified for the call now. */
-export const verifiedCandidates = (tool: HostedToolStatus): HostedToolCandidate[] =>
- tool.candidates.filter((candidate) => candidate.call.status === 'verified');
+const pairKey = (sourceId: string, modelId: string) => JSON.stringify([sourceId, modelId]);
-export type ModelCapability = {
- tool: HostedToolName;
- evidence: HostedEvidence;
- chip: HostedEvidenceChip;
- candidate: HostedToolCandidate;
- /** The tool is on and a turn would bind an executor (`bound`): a model that
- * cannot run it natively reaches it through that proxy. */
- proxied: boolean;
+/**
+ * Every (Source, model) the tool has a record for, one entry each. A refusal
+ * wins over a success on the same pair, because it is routing state, and a call
+ * refusal over a replay refusal.
+ */
+export const pairEvidence = (status: HostedToolRunStatus): PairEvidence[] => {
+ const verified = new Map(status.verified.map((success) => [pairKey(success.source_id, success.model_id), success]));
+ const refused = new Map<string, HostedRefusal>();
+ for (const refusal of status.refused) {
+ const key = pairKey(refusal.source_id, refusal.model_id);
+ const held = refused.get(key);
+ if (!held || (held.aspect === 'replay' && refusal.aspect === 'call')) refused.set(key, refusal);
+ }
+ const pairs: PairEvidence[] = [];
+ for (const [key, success] of verified) {
+ if (!refused.has(key)) pairs.push({ kind: 'ok', sourceId: success.source_id, modelId: success.model_id, success });
+ }
+ for (const [key, refusal] of refused) {
+ pairs.push({ kind: 'refused', sourceId: refusal.source_id, modelId: refusal.model_id, refusal, lastOk: verified.get(key) ?? null });
+ }
+ return pairs;
};
-/** A Source model's evidence for each tool, in catalog order, for its detail chips. */
+export type ModelCapability = { tool: HostedToolName; evidence: PairEvidence };
+
+/** A Source model's evidence for each tool, in catalog order, for its detail chips. No record draws nothing. */
export const modelCapabilities = (status: HostedToolsStatus, sourceId: string, modelId: string): ModelCapability[] =>
status.tools.flatMap((tool) => {
- const candidate = tool.candidates.find((entry) => entry.source_id === sourceId && entry.model_id === modelId);
- const chip = candidate ? evidenceChip(candidate.call) : null;
- return candidate && chip
- ? [{ tool: tool.name, evidence: candidate.call, chip, candidate, proxied: tool.enabled && tool.bound !== null }]
- : [];
+ const evidence = pairEvidence(tool.status).find((pair) => pair.sourceId === sourceId && pair.modelId === modelId);
+ return evidence ? [{ tool: tool.name, evidence }] : [];
});
-export type ProbeTarget = { tool: HostedToolName; candidate: HostedToolCandidate };
-
-export const probeKey = ({ tool, candidate }: ProbeTarget): string => `${tool}:${candidate.source_id}:${candidate.model_id}`;
+/**
+ * The executor order to save after moving one shown executor. The saved order may
+ * name Sources the read does not show now (refused, or gone for a while); the
+ * server keeps those on purpose and skips them, so a move rearranges only the
+ * shown ones within the saved list and leaves every hidden id where it was. A
+ * shown executor the saved list lacks follows the list, in its new place.
+ */
+export const executorOrderAfterMove = (
+ saved: readonly string[] | null,
+ shown: readonly string[],
+ index: number,
+ direction: -1 | 1,
+): string[] => {
+ const moved = [...shown];
+ const [item] = moved.splice(index, 1);
+ moved.splice(index + direction, 0, item);
+ if (saved === null) return moved;
+ const visible = new Set(shown);
+ const next = moved[Symbol.iterator]();
+ const merged = saved.map((id) => (visible.has(id) ? next.next().value as string : id));
+ return [...merged, ...next];
+};
-/** Whether a probe's answer became no evidence: inconclusive, transient, or a request that failed (null). */
-export const probeUnanswered = (result: HostedToolProbeResult | null): boolean =>
- result === null || result.call.outcome === 'inconclusive' || result.call.outcome === 'transient';
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index c047b5cb6..70382fbdd 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -216,12 +216,13 @@
--model-hub-quota-row-gap: 14px;
--model-hub-quota-nested-indent: 12px;
- /* Tools tab: hosted tools (frames E5IkUQ, XZjhj). Reuses the usage tab's type scale. */
+ /* Tools tab: hosted tools (frames pDd61, kPTBo). Reuses the usage tab's type scale. */
--model-hub-tools-gap: 16px;
+ --model-hub-tool-group-gap: 10px;
--model-hub-tool-pad-x: 20px;
+ --model-hub-tool-line-pad-y: 10px;
--model-hub-tool-row-pad-x: 14px;
--model-hub-tool-row-pad-y: 9px;
- --model-hub-tool-columns: minmax(0, 1.5fr) minmax(0, 1.3fr) minmax(0, 1fr) auto;
/* Backend model catalog dialog. `--model-hub-catalog-row-gap` is read from a
* Tailwind arbitrary value in the dialog's markup, which has no selector of
@@ -1544,6 +1545,21 @@
}
}
.model-hub-capability-detail { font-size: var(--model-hub-usage-cell-size); line-height: 18px; }
+/* A chip is its label (which opens the detail) and, on a refusal, a trailing clear. */
+.model-hub-capability-chip { padding: 0; }
+.model-hub-capability-chip > button {
+ display: inline-flex;
+ min-width: 0;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 8px;
+ border-radius: inherit;
+}
+.model-hub-capability-chip > .model-hub-capability-clear {
+ border-left: 1px solid var(--model-hub-gold-66);
+ border-radius: 0 999px 999px 0;
+}
+.model-hub-capability-clear:disabled { opacity: 0.5; }
.model-hub-source-capabilities-failure { font-size: var(--model-hub-source-tier-size); }
.model-hub-capability-explain { color: var(--model-hub-usage-note-ink); }
.model-hub-capability-facts {
@@ -2114,38 +2130,48 @@
.model-hub-tools { gap: var(--model-hub-tools-gap); }
.model-hub-tools-title { font-size: 15px; line-height: 21px; }
.model-hub-tools-subtitle,
-.model-hub-tools-reverify,
.model-hub-tools-foot {
color: var(--model-hub-usage-note-ink);
font-size: var(--model-hub-usage-cell-size);
line-height: 18px;
}
.model-hub-tools-foot { font-size: var(--model-hub-usage-note-size); line-height: 16px; }
+.model-hub-tool-group { gap: var(--model-hub-tool-group-gap); }
+.model-hub-tool-group-title {
+ color: var(--model-hub-ink-73);
+ font-size: var(--model-hub-usage-label-size);
+ line-height: 15px;
+}
.model-hub-tool-card-head { padding: 14px var(--model-hub-tool-pad-x); }
.model-hub-tool-name { font-size: 14px; line-height: 20px; }
.model-hub-tool-description,
.model-hub-tool-state { font-size: var(--model-hub-usage-cell-size); }
.model-hub-tool-description { color: var(--model-hub-usage-note-ink); }
-.model-hub-tool-table { padding: 12px var(--model-hub-tool-row-pad-x) 14px; }
-.model-hub-tool-table-head,
-.model-hub-tool-row {
- grid-template-columns: var(--model-hub-tool-columns);
- column-gap: var(--model-hub-usage-gutter);
- padding-inline: var(--model-hub-tool-row-pad-x);
-}
-.model-hub-tool-table-head {
- color: var(--model-hub-ink-73);
- font-size: var(--model-hub-usage-label-size);
- line-height: 15px;
+/* A status line, and the Advanced toggle, each a full-width row under the head. */
+.model-hub-tool-status,
+.model-hub-tool-advanced-toggle {
+ padding: var(--model-hub-tool-line-pad-y) var(--model-hub-tool-pad-x);
+ font-size: var(--model-hub-usage-cell-size);
+ line-height: 18px;
}
-.model-hub-tool-row {
- row-gap: 8px;
- padding-block: var(--model-hub-tool-row-pad-y);
+.model-hub-tool-advanced-body {
+ padding: 2px var(--model-hub-tool-pad-x) 16px;
font-size: var(--model-hub-usage-cell-size);
}
-/* Below md the row stacks: identity, then evidence, then cost. */
+.model-hub-tool-executor-row,
+.model-hub-tool-pair-row {
+ column-gap: var(--model-hub-usage-gutter);
+ row-gap: 6px;
+ padding: var(--model-hub-tool-row-pad-y) var(--model-hub-tool-row-pad-x);
+}
+.model-hub-tool-executor-row { grid-template-columns: auto minmax(0, 1fr) minmax(0, auto) auto; }
+.model-hub-tool-pair-row { grid-template-columns: minmax(0, 1fr) minmax(0, auto) auto; }
+/* Below md a row stacks: identity, then its state or price, then its actions. */
@media (max-width: 767px) {
- .model-hub-tool-row { grid-template-columns: minmax(0, 1fr); }
+ .model-hub-tool-executor-row { grid-template-columns: auto minmax(0, 1fr) auto; }
+ .model-hub-tool-executor-row > :nth-child(3) { grid-column: 2 / -1; grid-row: 2; }
+ .model-hub-tool-pair-row { grid-template-columns: minmax(0, 1fr) auto; }
+ .model-hub-tool-pair-row > :nth-child(2) { grid-column: 1 / -1; grid-row: 2; }
}
.model-hub-tool-cost-note {
color: var(--model-hub-usage-note-ink);
@@ -2157,10 +2183,6 @@
font-size: var(--model-hub-usage-note-size);
line-height: 16px;
}
-.model-hub-tool-executor {
- padding: 12px var(--model-hub-tool-pad-x);
- font-size: var(--model-hub-usage-cell-size);
-}
.model-hub-usage-empty {
padding: 26px var(--model-hub-usage-padding-x);
font-size: var(--model-hub-usage-cell-size);
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index e26d72eb6..c3d818c8c 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -28,9 +28,8 @@ import type {
ModelCandidateModelsDev,
ModelCandidateSupplier,
ModelsDevMatch,
- HostedToolExecutor,
+ HostedToolClear,
HostedToolName,
- HostedToolProbeResult,
HostedToolPut,
HostedToolsStatus,
NativeProtocol,
@@ -173,12 +172,14 @@ export type ModelsApi = {
getQuota(): Promise<QuotaSummary>;
/** The same report, re-read now (the service bounds how often). */
refreshQuota(): Promise<QuotaSummary>;
- /** The Tools tab read: each hosted tool's toggle, executor and evidence. */
+ /** The Tools tab read: each hosted tool's setting and what real use learned. */
getHostedTools(): Promise<HostedToolsStatus>;
- /** Replace one tool's toggle and executor; answers the whole status again. */
+ /** Change the fields the body names; answers the whole status again. */
putHostedTool(tool: HostedToolName, body: HostedToolPut): Promise<HostedToolsStatus>;
- /** One user-started call probe on exactly one (Source, model); answers the status it left. */
- probeHostedTool(tool: HostedToolName, target: HostedToolExecutor): Promise<{ probe: HostedToolProbeResult; hosted_tools: HostedToolsStatus }>;
+ /** Clear a tool's refusals (one Source, one of its models, or all); answers the whole status again. */
+ clearHostedTool(tool: HostedToolName, body: HostedToolClear): Promise<HostedToolsStatus>;
+ /** Clear one refused reasoning effort on a Source model; answers that Source. */
+ clearRefusedEffort(sourceId: string, modelId: string, effort: string): Promise<Source>;
getRuntimeStatus(): Promise<RuntimeDependency>;
/** Start the contract-owned client installation transaction. */
installRuntime(): Promise<RuntimeDependency>;
@@ -454,7 +455,7 @@ export const apiFailure = (
// backstop for a server that never answers, so it must outlast that controlled
// failure. The margin covers CSRF acquisition, both transits (including a
// tunnel), one fast CSRF-rejected attempt and replay, handler dispatch, and body
-// decoding. Keep the ceiling aligned with core/handlers/model_hub/hosted_probe.py:MODEL_HUB_RPC_TIMEOUT_SECONDS.
+// decoding. Keep the ceiling aligned with vibe/model_hub_client.py:MODEL_HUB_RPC_TIMEOUT_SECONDS.
export const MODEL_HUB_RPC_CEILING_MS = 300_000;
const TRANSPORT_MARGIN_MS = 30_000;
export const MODEL_HUB_REQUEST_DEADLINE_MS =
@@ -690,9 +691,13 @@ export const modelsApi: ModelsApi = {
putHostedTool: (tool, body) => call<{ hosted_tools: HostedToolsStatus }>(
`/api/models/hosted-tools/${encodeURIComponent(tool)}`, jsonInit('PUT', body),
).then((r) => r.hosted_tools),
- probeHostedTool: (tool, target) => call<{ probe: HostedToolProbeResult; hosted_tools: HostedToolsStatus }>(
- `/api/models/hosted-tools/${encodeURIComponent(tool)}/probe`, jsonInit('POST', target),
- ),
+ clearHostedTool: (tool, body) => call<{ hosted_tools: HostedToolsStatus }>(
+ `/api/models/hosted-tools/${encodeURIComponent(tool)}/clear`, jsonInit('POST', body),
+ ).then((r) => r.hosted_tools),
+ clearRefusedEffort: (sourceId, modelId, effort) => call<{ source: Source }>(
+ `/api/models/sources/${encodeURIComponent(sourceId)}/evidence/clear`,
+ jsonInit('POST', { model_id: modelId, feature: { kind: 'effort', name: effort } }),
+ ).then((r) => r.source),
getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),
installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
diff --git a/ui/src/components/settings/models/modelsApiDeadline.test.ts b/ui/src/components/settings/models/modelsApiDeadline.test.ts
index 19f7957f1..43e33c9b8 100644
--- a/ui/src/components/settings/models/modelsApiDeadline.test.ts
+++ b/ui/src/components/settings/models/modelsApiDeadline.test.ts
@@ -19,7 +19,7 @@ afterEach(() => {
describe('Model Hub request deadlines', () => {
it('keeps the browser backstop beyond the backend RPC ceiling', async () => {
// The server side owns the RPC ceiling; the UI-process client imports it from there.
- const backendSource = await readFile('../core/handlers/model_hub/hosted_probe.py', 'utf8');
+ const backendSource = await readFile('../vibe/model_hub_client.py', 'utf8');
const match = backendSource.match(/MODEL_HUB_RPC_TIMEOUT_SECONDS(?::\s*Final)?\s*=\s*([\d.]+)/);
expect(match?.[1]).toBeDefined();
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
index 7a0c5837a..5ca836510 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: 14,
+ contract_version: 15,
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.ts
index a2e68c725..89dc0b858 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: 14,
+ contract_version: 15,
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.ts
index e65b8ff6a..8fa868247 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 = 14 as const;
-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] as const;
+export const CONTRACT_VERSION = 15 as const;
+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] as const;
export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;
export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;
@@ -117,13 +117,14 @@ export type SuppliedModel = {
refused_efforts?: RefusedEffort[];
};
-/** One reasoning effort a Source model refused, as capability evidence records it. */
+/** One reasoning effort a Source model refused, as capability evidence records it.
+ * It stays until the user clears it or the Source's wire stamp changes. */
export type RefusedEffort = {
effort: string;
- basis: 'probe' | 'observed';
+ basis: 'observed';
observed_at: string;
+ /** The HTTP status and upstream code, never provider prose. */
detail: string | null;
- changes_at: string | null;
};
export type Source = {
@@ -1025,22 +1026,32 @@ export type QuotaSummary = {
// ── hosted-tools-status.schema.json ─────────────────────────────────────
/** The catalog's tools, in catalog order (`vibey-hosted-tools.md` §2). */
-export const HOSTED_TOOL_NAMES = ['web_search', 'x_search', 'image_generation'] as const;
+export const HOSTED_TOOL_NAMES = ['web_search', 'x_search', 'image_generate'] as const;
export type HostedToolName = (typeof HOSTED_TOOL_NAMES)[number];
+export type HostedSearchToolName = Exclude<HostedToolName, 'image_generate'>;
-/** One capability record as routing reads it: `status` already folds in staleness,
- * so a wire-stale record reads `unknown` here even though it once verified. */
-export type HostedEvidence = {
- status: 'verified' | 'unsupported' | 'unknown';
- /** `wire`: taken on another engine or probe shape, so it routes as unknown.
- * `age`: older than 30 days, so it still routes and only asks for a re-check. */
- stale: null | 'wire' | 'age';
- basis: null | 'probe' | 'observed';
- observed_at: string | null;
- detail: string | null;
- /** When the record stops reading as it does now: an observed record's expiry,
- * or a probe record's 30-day re-verify mark; null when nothing is scheduled. */
- changes_at: string | null;
+/** How a call ran: natively in the model's request, through a search executor, or on an image endpoint. */
+export type HostedExecutionMode = 'native' | 'executor' | 'direct';
+
+/** A positive record: a real response ran the tool on this (Source, model). Display only. */
+export type HostedSuccess = { source_id: string; model_id: string; mode: HostedExecutionMode; at: string };
+
+/** A current negative record: routing state until the user clears it or the wire stamp changes. */
+export type HostedRefusal = {
+ source_id: string;
+ model_id: string;
+ /** `call`: the tool itself; `replay`: earlier results sent back to it. */
+ aspect: 'call' | 'replay';
+ at: string;
+ /** The HTTP status and upstream code, never provider prose. */
+ reason: string;
+};
+
+/** What real use learned: the latest success, every pair's positive record, and the current refusals. */
+export type HostedToolRunStatus = {
+ latest_ok: HostedSuccess | null;
+ verified: HostedSuccess[];
+ refused: HostedRefusal[];
};
/** The overlay's list price for one hosted tool on a provider (`usd_per_1k` per `unit`). */
@@ -1053,58 +1064,61 @@ export type HostedToolListPrice = {
url: string;
};
-/** A cost the server states: at list price (`usd`), or included in a subscription (no `usd`). */
-export type HostedCostEstimate = { basis: 'list'; usd: number } | { basis: 'included' };
-
-export type HostedToolExecutor = { source_id: string; model_id: string };
-
-/** A (Source, model) the overlay offers the tool on, with an eligible credential
- * and an untranslated path; Vibey's Source order first. */
-export type HostedToolCandidate = HostedToolExecutor & {
- call: HostedEvidence;
- /** Null for image generation, which is never replayed. */
- replay: HostedEvidence | null;
+/** A Source that can execute a search for models that cannot run it natively, with the vendor's executor model. */
+export type HostedExecutorCandidate = {
+ source_id: string;
+ model_id: string;
billing: 'monthly' | 'metered';
- /** Null when no list price is known, never zero (image generation has none). */
+ /** A non-official endpoint: its price is the vendor's API price, which it may not bill. */
+ relay: boolean;
+ /** Null when no list price is known, never zero. */
price: HostedToolListPrice | null;
- /** One call probe's cost; null when unknown, which is never added as zero. */
- probe_estimate: HostedCostEstimate | null;
};
-export type HostedToolStatus = {
- name: HostedToolName;
- enabled: boolean;
- /** The user's choice, or null for the first verified candidate. */
- executor: HostedToolExecutor | null;
- /** The executor a turn would bind now, by hop resolution's own rule; null when none is verified. */
- bound: HostedToolExecutor | null;
- candidates: HostedToolCandidate[];
+export type HostedModelRef = { source_id: string; model_id: string };
+
+/** One image's price: the vendor's list price, or an estimate from token pricing. */
+export type HostedImagePrice = { usd: number; basis: 'list' | 'estimated' };
+
+export type HostedImageModel = HostedModelRef & { description: string; price: HostedImagePrice | null };
+
+type HostedToolBase = { enabled: boolean; status: HostedToolRunStatus };
+
+export type HostedSearchToolStatus = HostedToolBase & {
+ name: HostedSearchToolName;
+ /** The saved order; null when automatic. */
+ executor_order: string[] | null;
+ /** The order the gateway would try now. */
+ effective_order: string[];
+ /** Every eligible executor, in effective order. */
+ executor_candidates: HostedExecutorCandidate[];
};
-export type HostedToolsStatus = {
- tools: HostedToolStatus[];
- reverify: { engine_upgraded: number; aged: number };
+export type HostedImageToolStatus = HostedToolBase & {
+ name: 'image_generate';
+ /** The saved default; null when default. A saved model no longer available stays, flagged. */
+ default_model: (HostedModelRef & { available: boolean }) | null;
+ effective_default: HostedModelRef | null;
+ /** Exactly the pairs `image_generate` offers now. */
+ models: HostedImageModel[];
+ /** Vendors whose overlay lists image models, for the empty state. */
+ image_offered_by: string[];
};
-/** PUT /api/models/hosted-tools/<tool>: the whole setting, applied from the next turn. */
-export type HostedToolPut = { enabled: boolean; executor: HostedToolExecutor | null };
+export type HostedToolStatus = HostedSearchToolStatus | HostedImageToolStatus;
-/** One aspect of a probe: only verified and unsupported become evidence. */
-export type HostedProbeAspect = {
- outcome: 'verified' | 'unsupported' | 'inconclusive' | 'transient';
- /** The Source test's detail key, for a request that failed before completing. */
- error: string | null;
-};
+export type HostedToolsStatus = { tools: HostedToolStatus[] };
-/** POST /api/models/hosted-tools/<tool>/probe (`hosted-tool-probe-result.schema.json`). */
-export type HostedToolProbeResult = {
- tool: HostedToolName;
- source_id: string;
- model_id: string;
- call: HostedProbeAspect;
- replay: HostedProbeAspect | null;
+/** PUT /api/models/hosted-tools/<tool>, per field: an absent field is unchanged, `null` resets it. */
+export type HostedToolPut = {
+ enabled?: boolean;
+ executor_order?: string[] | null;
+ default_model?: HostedModelRef | null;
};
+/** POST /api/models/hosted-tools/<tool>/clear: one Source (one of its models), or `{}` for every Source. */
+export type HostedToolClear = { source_id: string; model_id?: string } | Record<string, never>;
+
// ── API envelope + request shapes (api.md) ──────────────────────────────
export type ApiOk<T> = { ok: true; contract_version: typeof CONTRACT_VERSION } & T;
export type ApiErr = {
diff --git a/ui/src/components/settings/models/useEstimateLabel.ts b/ui/src/components/settings/models/useEstimateLabel.ts
deleted file mode 100644
index 66146a9bf..000000000
--- a/ui/src/components/settings/models/useEstimateLabel.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { useTranslation } from 'react-i18next';
-
-import { formatSmallUsd } from './format';
-import type { HostedCostEstimate } from './types';
-
-/** 「约 $0.02」, 「订阅内含」, or nothing when the estimate is unknown. */
-export const useEstimateLabel = () => {
- const { t } = useTranslation();
- return (estimate: HostedCostEstimate | null | undefined): string | null => {
- if (!estimate) return null;
- return estimate.basis === 'included'
- ? t('settings.models.tools.probe.included') as string
- : t('settings.models.tools.probe.about', { usd: formatSmallUsd(estimate.usd) }) as string;
- };
-};
diff --git a/ui/src/components/settings/models/useHostedTools.test.tsx b/ui/src/components/settings/models/useHostedTools.test.tsx
index 3fa13a762..da020df54 100644
--- a/ui/src/components/settings/models/useHostedTools.test.tsx
+++ b/ui/src/components/settings/models/useHostedTools.test.tsx
@@ -15,8 +15,14 @@ import type { HostedToolsStatus } from './types';
import { useHostedTools } from './useHostedTools';
const status = (enabled: boolean): HostedToolsStatus => ({
- tools: [{ name: 'web_search', enabled, executor: null, bound: null, candidates: [] }],
- reverify: { engine_upgraded: 0, aged: 0 },
+ tools: [{
+ name: 'web_search',
+ enabled,
+ status: { latest_ok: null, verified: [], refused: [] },
+ executor_order: null,
+ effective_order: [],
+ executor_candidates: [],
+ }],
});
const deferred = <T,>() => {
@@ -51,7 +57,7 @@ describe('useHostedTools ordering', () => {
await waitFor(() => expect(shown(result.current.read)).toBe(false));
let saving!: Promise<void>;
- act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ act(() => { saving = result.current.save('web_search', { enabled: true }); });
// The tab is left and reopened while the PUT is still out.
await act(async () => { await result.current.refresh(); });
expect(get).toHaveBeenCalledTimes(1);
@@ -75,8 +81,8 @@ describe('useHostedTools ordering', () => {
let writes!: Promise<void>[];
act(() => {
writes = [
- result.current.save('web_search', { enabled: true, executor: null }),
- result.current.save('x_search', { enabled: true, executor: null }),
+ result.current.save('web_search', { enabled: true }),
+ result.current.save('x_search', { enabled: true }),
];
});
// The second PUT has not left: had both, the server could commit them in
@@ -95,7 +101,7 @@ describe('useHostedTools ordering', () => {
vi.spyOn(modelsApi, 'putHostedTool').mockResolvedValue(status(true));
const { result } = renderHook(() => useHostedTools(true), { wrapper });
- await act(async () => { await result.current.save('web_search', { enabled: true, executor: null }); });
+ await act(async () => { await result.current.save('web_search', { enabled: true }); });
expect(shown(result.current.read)).toBe(true);
// The read cannot tell whether it saw the write, so its answer never lands.
await act(async () => { first.resolve(status(false)); await first.promise; });
@@ -109,7 +115,7 @@ describe('useHostedTools ordering', () => {
await waitFor(() => expect(get).toHaveBeenCalledTimes(1));
get.mockResolvedValue(status(true));
- await act(async () => { await result.current.save('web_search', { enabled: true, executor: null }); });
+ await act(async () => { await result.current.save('web_search', { enabled: true }); });
await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
expect(shown(result.current.read)).toBe(true);
});
@@ -125,77 +131,6 @@ describe('useHostedTools ordering', () => {
await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
});
- it('MH-HOSTED-UI-007: keeps the status a probe answered with when the read after it fails', async () => {
- // Before: unchecked (shown here as off). The probe's answer: the tool's state after it.
- vi.spyOn(modelsApi, 'getHostedTools')
- .mockResolvedValueOnce(status(false))
- .mockRejectedValueOnce(new Error('offline'));
- vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
- probe: { tool: 'web_search', source_id: 'src_relay001', model_id: 'gpt-6-astra', call: { outcome: 'verified', error: null }, replay: null },
- hosted_tools: status(true),
- });
- const { result } = renderHook(() => useHostedTools(true), { wrapper });
- await waitFor(() => expect(shown(result.current.read)).toBe(false));
-
- const candidate = {
- source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null,
- call: { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null },
- replay: null,
- };
- await act(async () => { await result.current.probe({ tool: 'web_search', candidate }); });
- // The read that follows failed; what the probe answered still stands.
- await waitFor(() => expect(shown(result.current.read)).toBe(true));
- });
-
- it('MH-HOSTED-UI-013: reads the record before calling a probe unanswered when its answer was lost', async () => {
- const before = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
- const candidate = {
- source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: before, replay: null,
- };
- const recorded: HostedToolsStatus = {
- tools: [{
- name: 'web_search', enabled: false, executor: null, bound: null,
- candidates: [{ ...candidate, call: { ...before, status: 'verified', basis: 'probe', observed_at: '2026-10-14T07:00:00Z' } }],
- }],
- reverify: { engine_upgraded: 0, aged: 0 },
- };
- vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(false)).mockResolvedValue(recorded);
- // The probe ran and recorded its evidence, but its answer never arrived.
- vi.spyOn(modelsApi, 'probeHostedTool').mockRejectedValue(new Error('connection reset'));
- const { result } = renderHook(() => useHostedTools(true), { wrapper });
- await waitFor(() => expect(shown(result.current.read)).toBe(false));
-
- let outcome: Awaited<ReturnType<typeof result.current.probe>> = null;
- await act(async () => { outcome = await result.current.probe({ tool: 'web_search', candidate }); });
- // Verified, not "no answer", so nothing invites a second paid request.
- expect(outcome).toMatchObject({ call: { outcome: 'verified' } });
- });
-
- it('MH-HOSTED-UI-007: lands the status read for a lost probe answer, even when the read after it fails', async () => {
- const before = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
- const candidate = {
- source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: before, replay: null,
- };
- const recorded: HostedToolsStatus = {
- tools: [{
- name: 'web_search', enabled: true, executor: null, bound: null,
- candidates: [{ ...candidate, call: { ...before, status: 'verified', basis: 'probe', observed_at: '2026-10-14T07:00:00Z' } }],
- }],
- reverify: { engine_upgraded: 0, aged: 0 },
- };
- vi.spyOn(modelsApi, 'getHostedTools')
- .mockResolvedValueOnce(status(false))
- .mockResolvedValueOnce(recorded)
- .mockRejectedValue(new Error('offline'));
- vi.spyOn(modelsApi, 'probeHostedTool').mockRejectedValue(new Error('connection reset'));
- const { result } = renderHook(() => useHostedTools(true), { wrapper });
- await waitFor(() => expect(shown(result.current.read)).toBe(false));
-
- await act(async () => { await result.current.probe({ tool: 'web_search', candidate }); });
- // The recovered status shows; the failed read after it only marks it degraded.
- await waitFor(() => expect(shown(result.current.read)).toBe(true));
- });
-
it('MH-HOSTED-UI-007: shows no status of the previous Source identity while the new identity\'s read fails', async () => {
vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(true)).mockRejectedValue(new Error('offline'));
const { result, rerender } = renderHook(({ revision }) => useHostedTools(true, revision), {
@@ -218,7 +153,7 @@ describe('useHostedTools ordering', () => {
await waitFor(() => expect(shown(result.current.read)).toBe(false));
let saving!: Promise<void>;
- act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ act(() => { saving = result.current.save('web_search', { enabled: true }); });
// The answer was lost and the write may have committed: still pending while the read is out.
await waitFor(() => expect(modelsApi.getHostedTools).toHaveBeenCalledTimes(2));
expect(result.current.pending.has('web_search')).toBe(true);
@@ -228,6 +163,28 @@ describe('useHostedTools ordering', () => {
expect(shown(result.current.read)).toBe(true);
});
+ it('MH-HOSTED-UI-007: keeps a tool pending while the read reconciling its lost write fails, until a read lands', async () => {
+ vi.spyOn(modelsApi, 'getHostedTools')
+ .mockResolvedValueOnce(status(false))
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce(status(true));
+ vi.spyOn(modelsApi, 'putHostedTool').mockRejectedValue(new Error('connection reset'));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ await act(async () => { await result.current.save('web_search', { enabled: true }); });
+ // The write may have committed and the read that would say so failed: what
+ // is shown is the pre-write status, so nothing may build on it.
+ expect(modelsApi.getHostedTools).toHaveBeenCalledTimes(2);
+ expect(result.current.read.kind).toBe('degraded');
+ expect(result.current.pending.has('web_search')).toBe(true);
+
+ // The tab's Retry reads again; that read lands and settles it.
+ await act(async () => { await result.current.refresh(); });
+ expect(shown(result.current.read)).toBe(true);
+ expect(result.current.pending.has('web_search')).toBe(false);
+ });
+
it('MH-HOSTED-UI-007: drops a write answer asked under another Source identity', async () => {
const put = deferred<HostedToolsStatus>();
vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(false)).mockRejectedValue(new Error('offline'));
@@ -239,7 +196,7 @@ describe('useHostedTools ordering', () => {
await waitFor(() => expect(shown(result.current.read)).toBe(false));
let saving!: Promise<void>;
- act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ act(() => { saving = result.current.save('web_search', { enabled: true }); });
// The key is replaced while the write is out.
rerender({ revision: 'identity-b' });
await act(async () => { put.resolve(status(true)); await saving; });
@@ -247,26 +204,49 @@ describe('useHostedTools ordering', () => {
expect(shown(result.current.read)).toBeNull();
});
- it('MH-HOSTED-UI-013: reads a verdict the status does not carry as not verified, with why', async () => {
- const unknown = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
- const candidate = {
- source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: unknown, replay: null,
- };
- const unrecorded: HostedToolsStatus = {
- tools: [{ name: 'web_search', enabled: false, executor: null, bound: null, candidates: [candidate] }],
- reverify: { engine_upgraded: 0, aged: 0 },
- };
- vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(unrecorded);
- // The probe verified the tool, but the server could not write the record.
- vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
- probe: { tool: 'web_search', source_id: 'src_relay001', model_id: 'gpt-6-astra', call: { outcome: 'verified', error: null }, replay: null },
- hosted_tools: unrecorded,
+ it('MH-HOSTED-UI-007: keeps a tool pending until every write queued for it has settled', async () => {
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ const put = deferred<HostedToolsStatus>();
+ const clear = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'putHostedTool').mockReturnValue(put.promise);
+ vi.spyOn(modelsApi, 'clearHostedTool').mockReturnValue(clear.promise);
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let writes!: Promise<void>[];
+ act(() => {
+ writes = [
+ result.current.save('web_search', { enabled: true }),
+ result.current.clear('web_search', { source_id: 'src_relay001' }),
+ ];
});
+ await act(async () => { put.resolve(status(true)); await writes[0]; });
+ // The clear is still out and will answer a newer status: no control may build on this one.
+ expect(result.current.pending.has('web_search')).toBe(true);
+
+ await act(async () => { clear.resolve(status(true)); await writes[1]; });
+ expect(result.current.pending.has('web_search')).toBe(false);
+ });
+
+ it('MH-HOSTED-UI-007: queues a clear behind a write like any write, so its answer lands last', async () => {
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ const put = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'putHostedTool').mockReturnValue(put.promise);
+ const clear = vi.spyOn(modelsApi, 'clearHostedTool').mockResolvedValue(status(false));
const { result } = renderHook(() => useHostedTools(true), { wrapper });
- await waitFor(() => expect(result.current.read.kind).toBe('ready'));
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
- let outcome: Awaited<ReturnType<typeof result.current.probe>> = null;
- await act(async () => { outcome = await result.current.probe({ tool: 'web_search', candidate }); });
- expect(outcome).toMatchObject({ call: { outcome: 'transient', error: 'settings.models.tools.probe.notRecorded' } });
+ let writes!: Promise<void>[];
+ act(() => {
+ writes = [
+ result.current.save('web_search', { enabled: true }),
+ result.current.clear('web_search', { source_id: 'src_relay001', model_id: 'gpt-6-astra' }),
+ ];
+ });
+ await waitFor(() => expect(modelsApi.putHostedTool).toHaveBeenCalledTimes(1));
+ expect(clear).not.toHaveBeenCalled();
+ await act(async () => { put.resolve(status(true)); await Promise.all(writes); });
+ expect(clear).toHaveBeenCalledWith('web_search', { source_id: 'src_relay001', model_id: 'gpt-6-astra' });
+ expect(shown(result.current.read)).toBe(false);
});
});
diff --git a/ui/src/components/settings/models/useHostedTools.ts b/ui/src/components/settings/models/useHostedTools.ts
index 3b52f3525..a1a7e7228 100644
--- a/ui/src/components/settings/models/useHostedTools.ts
+++ b/ui/src/components/settings/models/useHostedTools.ts
@@ -4,8 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useToast } from '@/context/ToastContext';
import { modelsApi } from './modelsApi';
import { beginRegionRead, loadingRegion, readRegion, readyRegion, settleRegionRead, type RegionRead } from './regionRead';
-import { probeKey, sameExecutor, type ProbeTarget } from './hostedTools';
-import type { HostedToolName, HostedToolProbeResult, HostedToolPut, HostedToolsStatus } from './types';
+import type { HostedToolClear, HostedToolName, HostedToolPut, HostedToolsStatus } from './types';
/**
* The hosted-tools read, shared by the Tools tab and the Source chips.
@@ -16,11 +15,20 @@ import type { HostedToolName, HostedToolProbeResult, HostedToolPut, HostedToolsS
* a change of which drops its evidence on the server, so the old status is
* dropped here too before the new read.
*
- * Every write answers the whole status, so writes run one at a time: each PUT
- * starts after the previous one settled, and each answer is then the newest
- * state the server committed. A read never overlaps a write: one asked for
- * while writes are queued waits for them to drain, and one already out when a
- * write is queued is dropped, because it cannot tell whether it saw that write.
+ * Every write (a PUT or a clear) answers the whole status, so writes run one
+ * at a time: each starts after the previous one settled, and each answer is
+ * then the newest state the server committed. A read never overlaps a write:
+ * one asked for while writes are queued waits for them to drain, and one
+ * already out when a write is queued is dropped, because it cannot tell
+ * whether it saw that write.
+ *
+ * `pending` comes from one per-tool ledger and nowhere else. A tool is pending
+ * while a write for it is queued or out, or while a write for it ended without
+ * an answer and no authoritative status has landed since: that write may have
+ * committed, so no control may build a body on what is shown. Only an
+ * authoritative status ends that wait: a write's answer or a read that landed.
+ * Each is the whole status and newer than every write before it, so it covers
+ * every tool. A read that failed or was dropped covers nothing.
*/
export function useHostedTools(active: boolean, revision: string | null = null) {
const { t } = useTranslation();
@@ -32,15 +40,33 @@ export function useHostedTools(active: boolean, revision: string | null = null)
}, []);
const [read, setRead] = React.useState<RegionRead<HostedToolsStatus>>(loadingRegion);
const [pending, setPending] = React.useState<ReadonlySet<HostedToolName>>(() => new Set());
- const [probing, setProbing] = React.useState<ReadonlySet<string>>(() => new Set());
- const order = React.useRef({ reads: 0, writes: 0, queued: 0, rereadAfterWrites: false });
+ const order = React.useRef({ reads: 0, writes: 0, rereadAfterWrites: false });
const writeQueue = React.useRef<Promise<void>>(Promise.resolve());
+ const ledger = React.useRef(new Map<HostedToolName, { queued: number; awaiting: boolean }>());
+ const entry = (tool: HostedToolName) => {
+ const found = ledger.current.get(tool);
+ if (found) return found;
+ const created = { queued: 0, awaiting: false };
+ ledger.current.set(tool, created);
+ return created;
+ };
+ const queuedWrites = () => [...ledger.current.values()].reduce((sum, item) => sum + item.queued, 0);
+ const publish = React.useCallback(() => {
+ if (!alive.current) return;
+ setPending(new Set([...ledger.current].filter(([, item]) => item.queued > 0 || item.awaiting).map(([tool]) => tool)));
+ }, []);
+ /** An authoritative status landed: no lost write is unaccounted for any more. */
+ const covered = React.useCallback(() => {
+ for (const item of ledger.current.values()) item.awaiting = false;
+ publish();
+ }, [publish]);
+
/** Read the status. `forget` drops what is shown first: it belonged to another Source identity. */
const refresh = React.useCallback(async ({ forget = false }: { forget?: boolean } = {}) => {
const clock = order.current;
if (forget) setRead(loadingRegion);
- if (clock.queued > 0) {
+ if (queuedWrites() > 0) {
clock.rereadAfterWrites = true;
return;
}
@@ -50,7 +76,8 @@ export function useHostedTools(active: boolean, revision: string | null = null)
const incoming = await readRegion(() => modelsApi.getHostedTools());
if (!alive.current || readId !== clock.reads || writesAtStart !== clock.writes) return;
setRead((previous) => settleRegionRead(previous, incoming));
- }, []);
+ if (incoming.kind === 'ready') covered();
+ }, [covered]);
// `revision` is the open Source's identity. Evidence follows it, so a new one
// never shows the old one's records, even if its own read fails.
@@ -62,163 +89,58 @@ export function useHostedTools(active: boolean, revision: string | null = null)
void refresh({ forget });
}, [active, revision, refresh]);
- // Tools whose write ended without an answer: they stay pending until the read
- // that reconciles them lands, so no control writes a body built on the status
- // that write may already have changed.
- const unsettled = React.useRef<Set<HostedToolName>>(new Set());
- const release = React.useCallback((tools: Iterable<HostedToolName>) => {
- const done = [...tools];
- if (!alive.current || done.length === 0) return;
- setPending((previous) => {
- const next = new Set(previous);
- for (const tool of done) next.delete(tool);
- return next;
- });
- }, []);
-
- const save = React.useCallback(async (tool: HostedToolName, body: HostedToolPut) => {
+ const write = React.useCallback(async (
+ tool: HostedToolName,
+ send: () => Promise<HostedToolsStatus>,
+ failure: 'saveFailed' | 'clearFailed',
+ ) => {
const clock = order.current;
clock.writes += 1;
- clock.queued += 1;
// An answer is for the Source identity it was asked under (see `shownRevision`).
const revisionAtStart = shownRevision.current;
- setPending((previous) => new Set(previous).add(tool));
- const write = writeQueue.current.then(async () => {
+ entry(tool).queued += 1;
+ publish();
+ const turn = writeQueue.current.then(async () => {
try {
- const status = await modelsApi.putHostedTool(tool, body);
+ const status = await send();
if (!alive.current) return;
- if (shownRevision.current === revisionAtStart) setRead(readyRegion(status));
- else clock.rereadAfterWrites = true;
+ if (shownRevision.current === revisionAtStart) {
+ setRead(readyRegion(status));
+ covered();
+ } else {
+ clock.rereadAfterWrites = true;
+ }
} catch {
// A refused write changed nothing, and a lost answer may have committed;
// either way the tab converges on what the server now holds.
clock.rereadAfterWrites = true;
- unsettled.current.add(tool);
+ entry(tool).awaiting = true;
if (alive.current) {
- showToast(t('settings.models.tools.saveFailed', { toolInline: t(`settings.models.tools.tool.${tool}.inline`) }) as string, 'error');
+ showToast(t(`settings.models.tools.${failure}`, { toolInline: t(`settings.models.tools.tool.${tool}.inline`) }) as string, 'error');
}
}
});
- writeQueue.current = write;
- await write;
- clock.queued -= 1;
+ writeQueue.current = turn;
+ await turn;
+ entry(tool).queued -= 1;
+ publish();
if (!alive.current) return;
- if (!unsettled.current.has(tool)) release([tool]);
- if (clock.queued === 0 && clock.rereadAfterWrites) {
+ if (queuedWrites() === 0 && clock.rereadAfterWrites) {
clock.rereadAfterWrites = false;
- const reconciling = [...unsettled.current];
- unsettled.current.clear();
await refresh();
- release(reconciling);
- }
- }, [refresh, release, showToast, t]);
-
- /**
- * Run one call probe: a real, cost-bearing request the user asked for. Its
- * answer carries the status it left, which lands at once unless a write went
- * out while it ran (that write's answer is newer); an ordinary read then
- * reconciles, and if that read fails the probe's status still stands.
- * Null when the request itself failed.
- */
- const probe = React.useCallback(async (target: ProbeTarget): Promise<HostedToolProbeResult | null> => {
- const key = probeKey(target);
- const clock = order.current;
- const writesAtStart = clock.writes;
- const recordBefore = target.candidate.call.observed_at;
- const revisionAtStart = shownRevision.current;
- setProbing((previous) => new Set(previous).add(key));
- try {
- const { probe: answered, hosted_tools: status } = await modelsApi.probeHostedTool(target.tool, {
- source_id: target.candidate.source_id,
- model_id: target.candidate.model_id,
- });
- const result = recordedOutcome(answered, status, target, recordBefore);
- if (alive.current && clock.writes === writesAtStart && clock.queued === 0 && shownRevision.current === revisionAtStart) {
- // Newer than any read still out, which must not overwrite it.
- clock.reads += 1;
- setRead(readyRegion(status));
- }
- return result;
- } catch {
- // The request may have run and recorded its evidence though its answer was
- // lost: read the record before calling it unanswered, and keep the check
- // running until then, so no second paid request starts meanwhile. The
- // status read for that lands as a probe's answer would.
- const recovered = await lostProbeOutcome(target, recordBefore);
- if (recovered && alive.current && clock.writes === writesAtStart && clock.queued === 0 && shownRevision.current === revisionAtStart) {
- clock.reads += 1;
- setRead(readyRegion(recovered.status));
- }
- return recovered?.result ?? null;
- } finally {
- if (alive.current) {
- setProbing((previous) => {
- const next = new Set(previous);
- next.delete(key);
- return next;
- });
- void refresh();
- }
}
- }, [refresh]);
+ }, [covered, publish, refresh, showToast, t]);
- return { read, pending, probing, refresh, save, probe };
-}
+ /** Change the fields `body` names; an absent field stays as saved. */
+ const save = React.useCallback(
+ (tool: HostedToolName, body: HostedToolPut) => write(tool, () => modelsApi.putHostedTool(tool, body), 'saveFailed'),
+ [write],
+ );
+ /** Clear refusals: from the next request the tool is tried natively again there. */
+ const clear = React.useCallback(
+ (tool: HostedToolName, body: HostedToolClear) => write(tool, () => modelsApi.clearHostedTool(tool, body), 'clearFailed'),
+ [write],
+ );
-/**
- * A probe's outcome as far as it was recorded. Only a verified or unsupported
- * record routes, so an answer the status does not carry as a new probe record
- * for the pair (the record could not be written, or the Source's identity
- * changed while it ran) reads as not verified, with that reason, rather than as
- * a verdict routing never sees.
- */
-function recordedOutcome(
- result: HostedToolProbeResult,
- status: HostedToolsStatus,
- target: ProbeTarget,
- recordBefore: string | null,
-): HostedToolProbeResult {
- const { outcome } = result.call;
- if (outcome !== 'verified' && outcome !== 'unsupported') return result;
- const call = status.tools
- .find((tool) => tool.name === target.tool)?.candidates
- .find((candidate) => sameExecutor(candidate, target.candidate))?.call;
- if (call && call.basis === 'probe' && call.observed_at !== recordBefore && call.status === outcome) return result;
- return { ...result, call: { outcome: 'transient', error: PROBE_NOT_RECORDED } };
-}
-
-/** The reason a probe's verdict did not become a record (a UI key, read as the server's error keys are). */
-const PROBE_NOT_RECORDED = 'settings.models.tools.probe.notRecorded';
-
-/**
- * What a probe whose answer was lost left behind: a new probe record for its
- * pair (one the read did not have before it) is its outcome; anything else is
- * no answer (null).
- */
-async function lostProbeOutcome(
- target: ProbeTarget,
- recordBefore: string | null,
-): Promise<{ result: HostedToolProbeResult | null; status: HostedToolsStatus } | null> {
- try {
- const status = await modelsApi.getHostedTools();
- const call = status.tools
- .find((tool) => tool.name === target.tool)?.candidates
- .find((candidate) => sameExecutor(candidate, target.candidate))?.call;
- if (!call || call.basis !== 'probe' || call.observed_at === recordBefore || call.status === 'unknown') {
- return { status, result: null };
- }
- return {
- status,
- result: {
- tool: target.tool,
- source_id: target.candidate.source_id,
- model_id: target.candidate.model_id,
- call: { outcome: call.status, error: null },
- replay: null,
- },
- };
- } catch {
- // Unread: still no answer.
- return null;
- }
+ return { read, pending, refresh, save, clear };
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 28d214310..b54cbd0b0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2350,16 +2350,11 @@
"failed": "Couldn't do that, please retry"
},
"tools": {
- "title": "Hosted tools",
- "subtitle": "Vendor-hosted tools Vibey can call in a conversation. They are off by default: a call may cost money, and its content goes to the vendor that runs the tool.",
- "reverify": {
- "engineUpgraded_one": "Engine upgraded · {{count}} needs a new check",
- "engineUpgraded_other": "Engine upgraded · {{count}} need a new check",
- "aged_one": "{{count}} check is over 30 days old",
- "aged_other": "{{count}} checks are over 30 days old",
- "both": "<upgraded>{{engineUpgraded}}</upgraded> · {{aged}}",
- "upgradedOnly": "<upgraded>{{engineUpgraded}}</upgraded>",
- "agedOnly": "{{aged}}"
+ "title": "Tools",
+ "subtitle": "Tools Vibey can use in a conversation. Searches send the query to the vendor that runs them; if one fails, the query may be retried with another of your Sources. Image prompts go to the image model's vendor. On metered Sources each call is billed.",
+ "group": {
+ "search": "Search",
+ "generate": "Generate"
},
"tool": {
"web_search": {
@@ -2372,41 +2367,64 @@
"inline": "X search",
"description": "Searches posts on X, with operators such as from: and within_time:."
},
- "image_generation": {
+ "image_generate": {
"name": "Image generation",
"inline": "image generation",
- "description": "Generates images, shown in the answer and saved as files."
+ "description": "Vibey calls an image model to generate or edit images, saved as files."
}
},
"state": {
"on": "On",
- "off": "Off",
- "needsCheck": "Off · check a Source first",
- "needsExecutor": "Off · choose an executor first"
+ "off": "Off"
},
"toggle": {
"turnOn": "Turn on {{name}}",
"turnOff": "Turn off {{name}}"
},
- "col": {
- "source": "Source · model",
- "native": "Runs natively",
- "cost": "Cost per call"
- },
- "chip": {
- "unsupportedAged": "Not supported as of {{date}} · check again",
- "native": "Native · verified {{date}}",
- "reverify": "Verified {{date}} · check again",
- "engineUpgraded": "Engine upgraded · check again",
- "unsupported": "Not supported on this Source",
- "unchecked": "Not checked",
- "executor": "Proxy executor"
+ "status": {
+ "ok": "Last run by {{source}} · OK · {{date}}",
+ "refused": "Not supported on {{source}} · {{models}}",
+ "refusedMany": "Not supported on {{sources}}",
+ "switched": "{{line}}; now using {{source}}",
+ "replay": "{{source}} can't replay earlier results",
+ "replayMany": "{{sources}} can't replay earlier results"
+ },
+ "clear": {
+ "label": "Clear",
+ "source": "Clear {{source}}'s refusal of {{toolInline}}",
+ "model": "Clear the {{toolInline}} refusal of {{model}} on {{source}}",
+ "all": "Clear all",
+ "allLabel": "Clear every refusal of {{toolInline}}"
+ },
+ "advanced": {
+ "label": "Advanced",
+ "summaryBoth": "{{order}} · {{sources}}"
+ },
+ "order": {
+ "title": "Execution order",
+ "caption": "When the current model can't search natively, Vibey asks these Sources to search for it, in this order.",
+ "captionCustom": "When the current model can't search natively, Vibey asks these Sources to search for it, in this order. Customized.",
+ "summaryAuto": "Execution order: automatic",
+ "summaryCustom": "Execution order: customized",
+ "reset": "Reset to automatic",
+ "empty": "None of your Sources can search for models that can't run {{toolInline}} natively.",
+ "moveUp": "Move {{source}} up",
+ "moveDown": "Move {{source}} down",
+ "moved_one": "Moved {{source}} to position {{position}} of {{count}}.",
+ "moved_other": "Moved {{source}} to position {{position}} of {{count}}."
+ },
+ "sources": {
+ "title": "Status by Source",
+ "caption": "From real requests. A refusal stays until you clear it, or until the Source's settings, the engine or Avibe change. After a clear, the next request tries that Source again."
+ },
+ "pair": {
+ "ok": "OK · {{date}}",
+ "refused": "Not supported · {{date}}",
+ "replay": "No replay · {{date}}"
},
"cost": {
"included": "Included in subscription",
"includedNote": "No extra charge",
- "imageTokens": "Billed per image token · no per-image price yet",
- "list": "≈ {{price}}",
"perUnit": "${{usd}} / {{unit}}",
"unit": {
"call": "call",
@@ -2420,85 +2438,41 @@
"extraSeparator": " · ",
"unknown": "No list price"
},
- "empty": "None of your Sources can run {{toolInline}} natively. Add a Source that offers it, then check it here.",
- "noNative": "Models on {{sources}} have no native {{toolInline}}.",
- "executor": {
- "label": "Proxy executor",
- "pick": "Proxy executor for {{name}}",
- "automatic": "Automatic: first verified in Vibey's order",
- "unavailable": "Available after a check",
- "option": "{{source}} · {{model}}",
- "notVerified": "{{source}} · {{model}} (not verified)",
- "note": {
- "off": "Applies when the tool is on.",
- "bound": "Verified models run it natively. Other models use {{source}}, and those calls are billed to it.",
- "unbound": "No Source is verified, so calls to it fail until you check one."
- },
- "automaticBound": "Automatic ({{source}} · {{model}})"
- },
- "footnote": "Costs are estimates per call. API keys are valued at the vendor's list price, and a relay may bill differently. Subscriptions add no charge. A Claude subscription can't run hosted tools.",
+ "footnote": "Costs are estimated at the vendor's API price, and a relay may bill differently. Subscriptions add no charge. A Claude subscription can't run these tools.",
"saveFailed": "Couldn't save the {{toolInline}} setting. Please retry.",
- "probe": {
- "check": "Check",
- "checkCost": "Check · {{cost}}",
- "recheckCost": "Check again · {{cost}}",
- "retryCost": "Retry · {{cost}}",
- "recheck": "Check again",
- "retry": "Retry",
- "running": "Checking…",
- "about": "about ${{usd}}",
- "included": "included in subscription",
- "unknown": "cost unknown",
- "notRecorded": "the result couldn't be recorded",
- "replay": {
- "unverified": "Replay not verified · try again",
- "unsupported": "Replay not supported on this Source"
- },
- "outcome": {
- "inconclusive": "Not verified · the model didn't use the tool; try again",
- "transient": "Couldn't verify · try again",
- "transientReason": "Couldn't verify · {{reason}}"
- }
- }
+ "clearFailed": "Couldn't clear the {{toolInline}} refusal. Please retry."
},
"capability": {
"readFailed": "Couldn't read this Source's tool capabilities.",
"col": "Capabilities",
"chip": {
- "unsupportedAged": "{{tool}} · not supported as of {{date}} · check again",
- "native": "{{tool}} · native · verified {{date}}",
- "reverify": "{{tool}} · verified {{date}} · check again",
- "engineUpgraded": "{{tool}} · engine upgraded · check again",
- "unsupported": "{{tool}} · not supported on this Source",
- "viaProxy": "{{tool}} · via proxy",
- "viaProxyAged": "{{tool}} · via proxy · check again"
+ "ok": "{{tool}} · OK · {{date}}",
+ "refused": "{{tool}} · not supported",
+ "replay": "{{tool}} · no replay"
},
"explain": {
- "unsupportedAged": "This Source refused {{toolInline}} in a check over 30 days old. Check again to see whether it supports it now.",
- "native": "Verified: this model runs the vendor's own tool on this Source.",
- "reverify": "This check is over 30 days old. The tool still runs natively; check again when convenient.",
- "engineUpgraded": "The model engine was upgraded after this check, so it no longer counts as verified until it is checked again.",
- "unsupported": "This Source refused {{toolInline}}, so it is never sent here.",
- "viaProxy": "{{tool}} is on, but this Source can't run it natively, so calls go to the proxy executor.",
- "viaProxyAged": "{{tool}} is on. This Source refused it in a check over 30 days old, so calls go to the proxy executor; check again to see whether it runs natively now."
+ "native": "A real request ran {{toolInline}} natively on this model. Display only; it doesn't change routing.",
+ "executor": "This model ran {{toolInline}} for other models as the executor. Display only; it doesn't change routing.",
+ "direct": "This model generated images on its image endpoint. Display only; it doesn't change routing.",
+ "refused": "This Source refused {{toolInline}} in a real request on this model. Until you clear it, Vibey does it another way.",
+ "replay": "This model runs {{toolInline}} on this Source but refused earlier results sent back to it, so they go back as plain text."
},
"recorded": "Recorded",
- "recordedValue": "{{time}} · {{basis}}",
- "basis": {
- "probe": "a check",
- "observed": "a real request"
- },
+ "recordedValue": "{{time}} · a real request",
"reason": "Reason",
- "expiry": "Valid",
- "expiryObserved": "until {{date}}, then the default applies",
- "expiryProbe": "check again after {{date}}",
- "recheck": "Check again",
- "recheckCost": "Check again · {{cost}}",
+ "kept": "Kept",
+ "keptValue": "until you clear it, or the Source's settings, the engine or Avibe change",
+ "lastOk": "Last OK",
+ "clear": "Clear",
+ "clearTool": "Clear the {{tool}} refusal of {{model}}",
+ "clearEffort": "Clear the {{effort}} refusal of {{model}}",
+ "clearHint": "Supported now? Select Clear on the chip, and the next request tries this Source again.",
+ "clearFailed": "Couldn't clear the refusal. Please retry.",
"accessibleName": "{{label}}. {{explanation}}",
"accessibleNameFacts": "{{label}}. {{explanation}} {{facts}}",
"accessibleFact": "{{term}}: {{value}}.",
"effort": {
- "unsupported": "{{effort}} · not supported on this Source",
+ "unsupported": "{{effort}} · not supported",
"explain": "This Source refused this reasoning effort, so requests at it skip this Source."
}
}
@@ -4850,7 +4824,7 @@
"effort": "Effort",
"effortNotOn": "Not on {{sources}}",
"effortNotOnSome": "Not on some Sources",
- "effortRefused": "No Source accepts it now",
+ "effortRefused": "No Source accepts it now · clear it under Models → Sources",
"newAgent": "New agent",
"addModel": "Add model",
"noModels": "No models found",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b932a1707..93700cfaf 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2350,16 +2350,11 @@
"failed": "没能处理,请重试"
},
"tools": {
- "title": "托管工具",
- "subtitle": "Vibey 在对话中可调用的厂商托管工具。默认关闭:开启后每次调用可能产生费用,内容会发给提供该工具的厂商。",
- "reverify": {
- "engineUpgraded_one": "引擎已升级 · {{count}} 项需重新检测",
- "engineUpgraded_other": "引擎已升级 · {{count}} 项需重新检测",
- "aged_one": "{{count}} 项检测已超过 30 天",
- "aged_other": "{{count}} 项检测已超过 30 天",
- "both": "<upgraded>{{engineUpgraded}}</upgraded> · {{aged}}",
- "upgradedOnly": "<upgraded>{{engineUpgraded}}</upgraded>",
- "agedOnly": "{{aged}}"
+ "title": "工具",
+ "subtitle": "Vibey 在对话中可使用的工具。搜索会把查询发给执行它的厂商,失败时可能改由你的其他供应商重试;图片提示词会发给图片模型的厂商。按量付费的供应商每次调用都会计费。",
+ "group": {
+ "search": "搜索",
+ "generate": "生成"
},
"tool": {
"web_search": {
@@ -2372,41 +2367,64 @@
"inline": "X 搜索",
"description": "搜索 X 上的帖子,支持 from:、within_time: 等高级语法。"
},
- "image_generation": {
+ "image_generate": {
"name": "图片生成",
"inline": "图片生成",
- "description": "生成图片,显示在回答里并保存为文件。"
+ "description": "Vibey 按需调用图片模型生成或编辑图片,结果存为文件。"
}
},
"state": {
"on": "已开启",
- "off": "已关闭",
- "needsCheck": "已关闭 · 需先检测",
- "needsExecutor": "已关闭 · 需先选择代理执行者"
+ "off": "已关闭"
},
"toggle": {
"turnOn": "开启{{name}}",
"turnOff": "关闭{{name}}"
},
- "col": {
- "source": "供应商 · 模型",
- "native": "原生运行",
- "cost": "每次费用"
- },
- "chip": {
- "unsupportedAged": "{{date}} 检测为不支持 · 需重新检测",
- "native": "原生 · {{date}} 已验证",
- "reverify": "{{date}} 已验证 · 需重新检测",
- "engineUpgraded": "引擎已升级 · 需重新检测",
- "unsupported": "此供应商不支持",
- "unchecked": "未检测",
- "executor": "代理执行者"
+ "status": {
+ "ok": "最近一次由 {{source}} 执行 · 正常 · {{date}}",
+ "refused": "{{source}} 不支持 · {{models}}",
+ "refusedMany": "{{sources}} 不支持",
+ "switched": "{{line}},已改用 {{source}}",
+ "replay": "{{source}} 不支持回放历史结果",
+ "replayMany": "{{sources}} 不支持回放历史结果"
+ },
+ "clear": {
+ "label": "清除",
+ "source": "清除 {{source}} 的{{toolInline}}拒绝记录",
+ "model": "清除 {{source}} 上 {{model}} 的{{toolInline}}拒绝记录",
+ "all": "全部清除",
+ "allLabel": "清除{{toolInline}}的全部拒绝记录"
+ },
+ "advanced": {
+ "label": "高级",
+ "summaryBoth": "{{order}} · {{sources}}"
+ },
+ "order": {
+ "title": "执行顺序",
+ "caption": "当前模型不能原生搜索时,按这个顺序找供应商代为搜索。",
+ "captionCustom": "当前模型不能原生搜索时,按这个顺序找供应商代为搜索。已自定义。",
+ "summaryAuto": "执行顺序:自动",
+ "summaryCustom": "执行顺序:已自定义",
+ "reset": "恢复自动",
+ "empty": "你的供应商都不能为无法原生运行{{toolInline}}的模型代为搜索。",
+ "moveUp": "上移 {{source}}",
+ "moveDown": "下移 {{source}}",
+ "moved_one": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。",
+ "moved_other": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。"
+ },
+ "sources": {
+ "title": "各供应商状态",
+ "caption": "来自真实调用。“不支持”会一直保留,直到你清除,或供应商配置、引擎或 Avibe 版本变化;清除后,下一次请求会再试这个供应商。"
+ },
+ "pair": {
+ "ok": "正常 · {{date}}",
+ "refused": "不支持 · {{date}}",
+ "replay": "不支持回放 · {{date}}"
},
"cost": {
"included": "订阅内含",
"includedNote": "不另计费",
- "imageTokens": "按图像 token 计费 · 暂无单价",
- "list": "≈ {{price}}",
"perUnit": "${{usd}} / {{unit}}",
"unit": {
"call": "次",
@@ -2420,85 +2438,41 @@
"extraSeparator": ",",
"unknown": "暂无标价"
},
- "empty": "你的供应商都不能原生运行{{toolInline}}。添加提供该工具的供应商后,在这里检测。",
- "noNative": "{{sources}} 上的模型没有原生{{toolInline}}。",
- "executor": {
- "label": "代理执行",
- "pick": "{{name}}的代理执行者",
- "automatic": "自动:Vibey 顺序中第一个已验证的",
- "unavailable": "检测后可选",
- "option": "{{source}} · {{model}}",
- "notVerified": "{{source}} · {{model}}(未验证)",
- "note": {
- "off": "开启后生效。",
- "bound": "已验证的模型直接原生调用;其他模型由 {{source}} 代为调用,费用记在 {{source}}。",
- "unbound": "还没有已验证的供应商:在检测通过前调用会失败。"
- },
- "automaticBound": "自动({{source}} · {{model}})"
- },
- "footnote": "费用为每次调用的估算:API Key 按厂商 API 标价估算,中转的实际账单可能不同;订阅不另计费。Claude 订阅不能运行托管工具。",
+ "footnote": "费用按厂商 API 标价估算,中转的实际账单可能不同;订阅不另计费。Claude 订阅不能运行这些工具。",
"saveFailed": "{{toolInline}}设置未能保存,请重试。",
- "probe": {
- "check": "检测",
- "checkCost": "检测 · {{cost}}",
- "recheckCost": "重新检测 · {{cost}}",
- "retryCost": "重试 · {{cost}}",
- "recheck": "重新检测",
- "retry": "重试",
- "running": "检测中…",
- "about": "约 ${{usd}}",
- "included": "订阅内含",
- "unknown": "费用未知",
- "notRecorded": "结果未能记录",
- "replay": {
- "unverified": "回放未验证 · 请重试",
- "unsupported": "此供应商不支持回放"
- },
- "outcome": {
- "inconclusive": "未能检测 · 模型没有调用工具,请重试",
- "transient": "未能检测 · 请重试",
- "transientReason": "未能检测 · {{reason}}"
- }
- }
+ "clearFailed": "{{toolInline}}拒绝记录未能清除,请重试。"
},
"capability": {
"readFailed": "未能读取此供应商的工具能力。",
"col": "能力",
"chip": {
- "unsupportedAged": "{{tool}} · {{date}} 检测为不支持 · 需重新检测",
- "native": "{{tool}} · 原生 · {{date}} 已验证",
- "reverify": "{{tool}} · {{date}} 已验证 · 需重新检测",
- "engineUpgraded": "{{tool}} · 引擎已升级 · 需重新检测",
- "unsupported": "{{tool}} · 此供应商不支持",
- "viaProxy": "{{tool}} · 由代理提供",
- "viaProxyAged": "{{tool}} · 由代理提供 · 需重新检测"
+ "ok": "{{tool}} · 正常 · {{date}}",
+ "refused": "{{tool}} · 不支持",
+ "replay": "{{tool}} · 不支持回放"
},
"explain": {
- "unsupportedAged": "此供应商在超过 30 天前的检测中不支持{{toolInline}},可重新检测现在是否已支持。",
- "native": "检测通过:这个模型在此供应商上直接调用厂商自带的工具。",
- "reverify": "检测已超过 30 天,仍按原结果原生运行,可重新检测。",
- "engineUpgraded": "检测之后模型引擎已升级,重新检测前不再算作已验证。",
- "unsupported": "此供应商拒绝过{{toolInline}},之后不会再发到这里。",
- "viaProxy": "{{tool}}已开启,但此供应商不能原生运行,调用交给代理执行者。",
- "viaProxyAged": "{{tool}}已开启。此供应商在超过 30 天前的检测中不支持它,调用交给代理执行者;可重新检测现在是否已能原生运行。"
+ "native": "最近一次真实调用在这个模型上原生执行了{{toolInline}}。只用于显示,不影响路由。",
+ "executor": "这个模型作为执行者,为其他模型执行了{{toolInline}}。只用于显示,不影响路由。",
+ "direct": "这个模型通过图片接口生成了图片。只用于显示,不影响路由。",
+ "refused": "此供应商在这个模型的真实请求中拒绝了{{toolInline}}。清除前,Vibey 会改用其他方式完成。",
+ "replay": "这个模型能在此供应商上执行{{toolInline}},但拒绝回放历史结果,之后历史结果会以文本形式发回。"
},
"recorded": "记录时间",
- "recordedValue": "{{time}} · {{basis}}",
- "basis": {
- "probe": "一次检测",
- "observed": "一次真实请求"
- },
- "reason": "失败原因",
- "expiry": "有效期",
- "expiryObserved": "到 {{date}},过期后按默认判断",
- "expiryProbe": "{{date}} 后需重新检测",
- "recheck": "重新检测",
- "recheckCost": "重新检测 · {{cost}}",
+ "recordedValue": "{{time}} · 一次真实请求",
+ "reason": "原因",
+ "kept": "保留",
+ "keptValue": "直到你清除,或供应商配置、引擎或 Avibe 版本变化",
+ "lastOk": "上次正常",
+ "clear": "清除",
+ "clearTool": "清除 {{model}} 的{{tool}}拒绝记录",
+ "clearEffort": "清除 {{model}} 的 {{effort}} 拒绝记录",
+ "clearHint": "现在支持了?点标签上的“清除”,下一次请求会再试这个供应商。",
+ "clearFailed": "拒绝记录未能清除,请重试。",
"accessibleName": "{{label}}。{{explanation}}",
"accessibleNameFacts": "{{label}}。{{explanation}}{{facts}}",
"accessibleFact": "{{term}}:{{value}}。",
"effort": {
- "unsupported": "{{effort}} · 此供应商不支持",
+ "unsupported": "{{effort}} · 不支持",
"explain": "此供应商拒绝过这个推理强度,之后的请求会跳过它。"
}
}
@@ -4850,7 +4824,7 @@
"effort": "思考强度",
"effortNotOn": "{{sources}} 不支持",
"effortNotOnSome": "部分供应商不支持",
- "effortRefused": "当前没有供应商支持",
+ "effortRefused": "当前没有供应商支持 · 可在模型 → 供应商中清除",
"newAgent": "新建 Agent",
"addModel": "添加模型",
"noModels": "未找到模型",
diff --git a/vibe/authorization.py b/vibe/authorization.py
index dd01fbf29..ac2c62d03 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -527,6 +527,7 @@ _MEMBER_HTTP_RULES = tuple(
("DELETE", r"^/api/models/sources/[^/]+$"),
("PUT", r"^/api/models/sources/[^/]+/credential$"),
("POST", r"^/api/models/sources/[^/]+/(?:reauth|refresh|probe)$"),
+ ("POST", r"^/api/models/sources/[^/]+/evidence/clear$"),
("POST", r"^/api/models/sources/[^/]+/models$"),
# Model IDs are path parameters and may contain vendor/model slashes.
("PATCH", r"^/api/models/sources/[^/]+/models/.+$"),
@@ -551,7 +552,7 @@ _MEMBER_HTTP_RULES = tuple(
("POST", r"^/api/models/quota/refresh$"),
("GET", r"^/api/models/hosted-tools$"),
("PUT", r"^/api/models/hosted-tools/[^/]+$"),
- ("POST", r"^/api/models/hosted-tools/[^/]+/probe$"),
+ ("POST", r"^/api/models/hosted-tools/[^/]+/clear$"),
("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.py
index 253efc925..6936b32b9 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -24,7 +24,7 @@ from typing import TYPE_CHECKING, Any, Callable, Final, Iterable, Literal, Mappi
from config import paths
from config.atomic_io import write_atomic
-from core.agent_core.messages import HOSTED_TOOLS, PROTOCOLS
+from core.agent_core.messages import PROTOCOLS
from core.command_runner import run_supervised_command
from vibe.claude_model_catalog import (
DEFAULT_CLAUDE_MODEL_ALIASES,
@@ -675,6 +675,15 @@ def bundled_catalog_wire_efforts_by_model() -> Mapping[str, tuple[str, ...]]:
# 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")
+# An image model is priced per image, and only an image model is.
+_IMAGE_PRICE_UNITS = ("image",)
+# The tools a chat request may declare natively. Image generation is never one (vibey-hosted-tools.md §7).
+OVERLAY_SEARCH_TOOLS: tuple[str, ...] = ("web_search", "x_search")
+IMAGE_MODEL_ENDPOINTS: tuple[str, ...] = ("images", "chat_image")
+IMAGE_MODEL_PARAMS: tuple[str, ...] = ("images", "n", "size")
+IMAGE_SIZE_FORMS: tuple[str, ...] = ("pixels", "ratio")
+# One line in every request's tool block: bounded so a catalog line cannot grow every prompt prefix.
+IMAGE_MODEL_DESCRIPTION_MAX_CHARS = 80
_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*)?")
@@ -722,6 +731,32 @@ class HostedToolSpec:
return self.declaration["type"]
+@dataclass(frozen=True)
+class ImageModelPrice:
+ """A per-image list price, for the output ``size`` and ``quality`` it applies to (None matches any)."""
+
+ price: HostedToolPrice
+ size: str | None = None
+ quality: str | None = None
+
+
+@dataclass(frozen=True)
+class ImageModelSpec:
+ """One image model a vendor offers to ``image_generate`` (capability model §4).
+
+ ``params`` and ``size_forms`` are sorted, so anything built from them is stable.
+ ``tokens_per_image`` lets the pricing module estimate a model with no per-image price.
+ """
+
+ id: str
+ description: str
+ endpoint: Literal["images", "chat_image"]
+ params: tuple[str, ...]
+ size_forms: tuple[str, ...]
+ prices: tuple[ImageModelPrice, ...] = ()
+ tokens_per_image: int | None = None
+
+
@dataclass(frozen=True)
class ProviderModelOverlay:
"""One model family of a provider; ``wire_efforts`` None defers to models.dev."""
@@ -732,9 +767,38 @@ class ProviderModelOverlay:
hosted_tools: Mapping[str, Mapping[str, HostedToolSpec]]
[email protected]_cache(maxsize=1)
+@dataclass(frozen=True)
+class ProviderVendorOverlay:
+ """One vendor of the ``providers`` section: its model families, executor model and image models."""
+
+ models: tuple[ProviderModelOverlay, ...]
+ executor_model: str | None = None
+ image_models: tuple[ImageModelSpec, ...] = ()
+
+
def bundled_provider_overlay() -> Mapping[str, tuple[ProviderModelOverlay, ...]]:
- """Each vendor's model families from the bundled ``providers`` section.
+ """Each vendor's model families from the bundled ``providers`` section."""
+
+ return MappingProxyType({vendor: entry.models for vendor, entry in bundled_provider_vendors().items()})
+
+
+def provider_executor_model(vendor: str) -> str | None:
+ """The vendor's lightweight model that runs proxied search calls (vibey-hosted-tools.md §6)."""
+
+ entry = bundled_provider_vendors().get(vendor.strip().lower())
+ return entry.executor_model if entry is not None else None
+
+
+def provider_image_models(vendor: str) -> tuple[ImageModelSpec, ...]:
+ """The image models the vendor offers to ``image_generate``, in catalog order."""
+
+ entry = bundled_provider_vendors().get(vendor.strip().lower())
+ return entry.image_models if entry is not None else ()
+
+
[email protected]_cache(maxsize=1)
+def bundled_provider_vendors() -> Mapping[str, ProviderVendorOverlay]:
+ """Each vendor's entry 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
@@ -751,10 +815,10 @@ def bundled_provider_overlay() -> Mapping[str, tuple[ProviderModelOverlay, ...]]
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, ...]] = {}
+ overlay: dict[str, ProviderVendorOverlay] = {}
for vendor, raw_vendor in providers.items():
try:
- overlay[_overlay_vendor_id(vendor)] = _overlay_vendor_models(raw_vendor)
+ overlay[_overlay_vendor_id(vendor)] = _overlay_vendor(raw_vendor)
except ValueError as exc:
logger.warning("Provider overlay entry %r is disabled: %s", vendor, exc)
return MappingProxyType(overlay)
@@ -766,7 +830,8 @@ def provider_overlay_entry(vendor: str, model_id: str) -> ProviderModelOverlay |
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(), ()):
+ vendor_entry = bundled_provider_vendors().get(vendor.strip().lower())
+ for entry in vendor_entry.models if vendor_entry is not None else ():
if (entry.match_kind == "id" and model == entry.match_value) or (
entry.match_kind == "prefix" and model.startswith(entry.match_value)
):
@@ -795,12 +860,68 @@ def _overlay_vendor_id(vendor: str) -> str:
return vendor
-def _overlay_vendor_models(raw: object) -> tuple[ProviderModelOverlay, ...]:
- vendor = _overlay_object(raw, "vendor entry", required=("models",))
+def _overlay_vendor(raw: object) -> ProviderVendorOverlay:
+ vendor = _overlay_object(raw, "vendor entry", required=("models",), optional=("executor_model", "image_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)
+ image_models = vendor.get("image_models", [])
+ if not isinstance(image_models, list):
+ raise ValueError("image_models must be a list")
+ executor_model = vendor.get("executor_model")
+ return ProviderVendorOverlay(
+ models=tuple(_overlay_model(item) for item in models),
+ executor_model=None if executor_model is None else _overlay_token(executor_model, "executor_model"),
+ image_models=tuple(_overlay_image_model(item) for item in image_models),
+ )
+
+
+def _overlay_image_model(raw: object) -> ImageModelSpec:
+ model = _overlay_object(
+ raw,
+ "image model",
+ required=("id", "description", "endpoint", "params", "size_forms"),
+ optional=("prices", "tokens_per_image"),
+ )
+ description = model["description"]
+ if not isinstance(description, str) or not _OVERLAY_TOKEN.fullmatch(description) or (
+ len(description) > IMAGE_MODEL_DESCRIPTION_MAX_CHARS
+ ):
+ raise ValueError(f"image model description must be one line of at most {IMAGE_MODEL_DESCRIPTION_MAX_CHARS} characters")
+ endpoint = model["endpoint"]
+ if endpoint not in IMAGE_MODEL_ENDPOINTS:
+ raise ValueError("image model endpoint is not known")
+ params = _overlay_tokens(model["params"], "image model params")
+ size_forms = _overlay_tokens(model["size_forms"], "image model size_forms")
+ if set(params) - set(IMAGE_MODEL_PARAMS) or set(size_forms) - set(IMAGE_SIZE_FORMS):
+ raise ValueError("image model params or size_forms name an unknown value")
+ if ("size" in params) != bool(size_forms):
+ raise ValueError("image model size_forms are present exactly when it takes size")
+ prices = model.get("prices", [])
+ if not isinstance(prices, list):
+ raise ValueError("image model prices must be a list")
+ tokens = model.get("tokens_per_image")
+ if tokens is not None and (isinstance(tokens, bool) or not isinstance(tokens, int) or tokens <= 0):
+ raise ValueError("image model tokens_per_image must be a positive integer")
+ return ImageModelSpec(
+ id=_overlay_token(model["id"], "image model id"),
+ description=description,
+ endpoint=endpoint,
+ params=tuple(sorted(params)),
+ size_forms=tuple(sorted(size_forms)),
+ prices=tuple(_overlay_image_price(item) for item in prices),
+ tokens_per_image=tokens,
+ )
+
+
+def _overlay_image_price(raw: object) -> ImageModelPrice:
+ entry = _overlay_object(raw, "image model price", required=("price",), optional=("size", "quality"))
+ price = _overlay_price(entry["price"], "image model price", units=_IMAGE_PRICE_UNITS)
+ return ImageModelPrice(
+ price=price,
+ size=None if entry.get("size") is None else _overlay_token(entry["size"], "image model price size"),
+ quality=None if entry.get("quality") is None else _overlay_token(entry["quality"], "image model price quality"),
+ )
def _overlay_model(raw: object) -> ProviderModelOverlay:
@@ -813,7 +934,7 @@ def _overlay_model(raw: object) -> ProviderModelOverlay:
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)
+ tools = _overlay_object(raw_tools, f"hosted_tools.{protocol}", optional=OVERLAY_SEARCH_TOOLS)
hosted_tools[protocol] = MappingProxyType(
{tool: _overlay_hosted_tool(spec, f"{protocol}.{tool}") for tool, spec in tools.items()}
)
@@ -838,8 +959,10 @@ def _overlay_hosted_tool(raw: object, what: str) -> HostedToolSpec:
)
-def _overlay_price(raw: object, what: str) -> HostedToolPrice:
- price = _overlay_object(raw, what, required=("unit", "usd_per_1k", "as_of", "url"), optional=("extra",))
+def _overlay_price(raw: object, what: str, *, units: tuple[str, ...] = _HOSTED_TOOL_PRICE_UNITS) -> HostedToolPrice:
+ # Only a search tool's price has further billed units.
+ extra_allowed = ("extra",) if units == _HOSTED_TOOL_PRICE_UNITS else ()
+ price = _overlay_object(raw, what, required=("unit", "usd_per_1k", "as_of", "url"), optional=extra_allowed)
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):
@@ -847,7 +970,7 @@ def _overlay_price(raw: object, what: str) -> HostedToolPrice:
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)
+ unit, usd_per_1k = _overlay_price_component(price, what, units)
return HostedToolPrice(
unit=unit,
usd_per_1k=usd_per_1k,
@@ -858,6 +981,7 @@ def _overlay_price(raw: object, what: str) -> HostedToolPrice:
*_overlay_price_component(
_overlay_object(item, f"{what}.extra", required=("unit", "usd_per_1k")),
f"{what}.extra",
+ units,
)
)
for item in extra
@@ -874,10 +998,10 @@ def _overlay_date(value: object, what: str) -> date:
raise ValueError(f"{what} must be a YYYY-MM-DD date")
-def _overlay_price_component(price: Mapping[str, Any], what: str) -> tuple[str, float]:
+def _overlay_price_component(price: Mapping[str, Any], what: str, units: tuple[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:
+ if not isinstance(unit, str) or unit not in units:
raise ValueError(f"{what}.unit is not a known price unit")
if (
not isinstance(usd_per_1k, (int, float))
diff --git a/vibe/data/backend_models.json b/vibe/data/backend_models.json
index ec45f39c3..7e9cf09d3 100644
--- a/vibe/data/backend_models.json
+++ b/vibe/data/backend_models.json
@@ -49,6 +49,7 @@
},
"providers": {
"anthropic": {
+ "executor_model": "claude-haiku-5-5",
"models": [
{
"match": {"prefix": "claude-"},
@@ -65,6 +66,7 @@
]
},
"openai": {
+ "executor_model": "gpt-6-luna",
"models": [
{
"match": {"prefix": "gpt-"},
@@ -75,9 +77,6 @@
"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, "output_format": "jpeg", "output_compression": 90}
}
}
}
@@ -85,6 +84,7 @@
]
},
"xai": {
+ "executor_model": "grok-4.20-0309-non-reasoning",
"models": [
{
"match": {"prefix": "grok-4"},
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index fed9e51cb..29757e7ff 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -8,7 +8,6 @@ import httpx
from core.handlers.model_hub import ModelHubError
from vibe import internal_client
-from core.handlers.model_hub.hosted_probe import MODEL_HUB_RPC_TIMEOUT_SECONDS
from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
@@ -18,6 +17,8 @@ _TRANSPORT_ERRORS = (
OSError,
internal_client.InternalServerUnavailable,
)
+# How long the UI process waits for any Model Hub RPC; the Web UI's request deadline stays beyond it.
+MODEL_HUB_RPC_TIMEOUT_SECONDS = 300.0
_REORDER_ORDER_UNSET = object()
@@ -300,8 +301,11 @@ class ModelHubRemoteService:
async def set_hosted_tool(self, tool: str, setting: object) -> dict:
return await _rpc("set_hosted_tool", {"tool": tool, "setting": setting})
- async def probe_hosted_tool(self, tool: str, target: object) -> dict:
- return await _rpc("probe_hosted_tool", {"tool": tool, "target": target})
+ async def clear_hosted_refusals(self, tool: str, target: object) -> dict:
+ return await _rpc("clear_hosted_refusals", {"tool": tool, "target": target})
+
+ async def clear_source_evidence(self, source_id: str, target: object) -> dict:
+ return await _rpc("clear_source_evidence", {"source_id": source_id, "target": target})
def agent_chain(self, backend: str, model_id: str) -> dict:
return _rpc_sync(
diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.py
index 4f678ae9f..aaaec3b2d 100644
--- a/vibe/model_hub_runtime/api_key_vendors.py
+++ b/vibe/model_hub_runtime/api_key_vendors.py
@@ -253,6 +253,19 @@ def official_models_dev_provider(vendor: str, base_url: str | None) -> str | Non
return entry.models_dev_provider
+def is_official_api_key_endpoint(vendor: str, base_url: str) -> bool:
+ """Whether a base URL is its vendor's official endpoint, by the engine's endpoint identity.
+
+ Spellings that differ only by host case, a default port, or the implied ``/v1`` root are the same endpoint.
+ """
+
+ official = official_api_key_base_url(vendor)
+ if official is None:
+ return False
+ identity = _endpoint_identity(base_url)
+ return identity is not None and identity == _endpoint_identity(official)
+
+
def official_api_key_base_urls() -> dict[str, str]:
return {
**{entry.id: entry.official_base_url for entry in api_key_vendor_catalog()},
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index a393d0433..da775dad4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5180,13 +5180,29 @@ async def model_hub_hosted_tool_put(tool: str, starlette_request: FastAPIRequest
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/models/hosted-tools/{tool}/probe", include_in_schema=False)
-async def model_hub_hosted_tool_probe(tool: str, starlette_request: FastAPIRequest):
[email protected]("/api/models/hosted-tools/{tool}/clear", include_in_schema=False)
+async def model_hub_hosted_tool_clear(tool: str, starlette_request: FastAPIRequest):
async def handler():
from core.handlers.model_hub import ModelHubError
try:
- result = await _model_hub_service().probe_hosted_tool(tool, _model_hub_json_object("invalid_parameter"))
+ status = await _model_hub_service().clear_hosted_refusals(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)
+
+
[email protected]("/api/models/sources/{source_id}/evidence/clear", include_in_schema=False)
+async def model_hub_source_evidence_clear(source_id: str, starlette_request: FastAPIRequest):
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ result = await _model_hub_service().clear_source_evidence(
+ source_id, _model_hub_json_object("invalid_parameter"),
+ )
return _model_hub_success(**result)
except ModelHubError as exc:
return _model_hub_error(exc)