Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): value a proxied hosted call with the pricing module's cost (#2579)
Call Whiteff66a125e4d1
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.pyindex 22bbeab72..4d0f98d12 100644--- a/core/handlers/model_hub/hosted_executor.py+++ b/core/handlers/model_hub/hosted_executor.py@@ -19,14 +19,16 @@ import base64import binasciiimport jsonimport re-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom typing import Any, Callable, Final, Mappingfrom config.v2_config import ModelHubSourceConfig+from core.agent_core.ai.hosted import reported_countsfrom core.agent_core.ai.sse import SSEParserfrom vibe.backend_model_catalog import HostedToolSpecfrom .events import bounded_diagnostic_detail+from .pricing import usd_from_xai_ticksfrom .request import ModelHubRequestEXECUTOR_TOOLS: Final = ("web_search", "x_search", "image_generation")@@ -289,11 +291,30 @@ class ResponsesStreamReader:@dataclass(frozen=True)class ExecutorResult:- """The record for the call, plus an image's resolved facts and bytes (base64)."""+ """The record for the call, plus an image's resolved facts and bytes (base64).++ ``usage`` is the response's own ``usage`` section, as the provider sent it,+ which the call's cost is read from.+ """record: dict[str, Any]generation: dict[str, str] | None = Noneimages: tuple[dict[str, str], ...] = ()+ usage: Mapping[str, Any] | None = None+++def provider_charges(protocol: str, usage: Mapping[str, Any] | None) -> tuple[dict[str, int], float | None]:+ """What a response's provider reported charging for: its hosted counters and, from xAI, its own cost."""++ if usage is None:+ return {}, None+ counters = usage.get("server_tool_use") if protocol == "anthropic" else usage.get("server_side_tool_usage_details")+ return reported_counts(counters), usd_from_xai_ticks(usage.get("cost_in_usd_ticks"))+++def _usage_section(response: Any) -> Mapping[str, Any] | None:+ usage = response.get("usage") if isinstance(response, Mapping) else None+ return usage if isinstance(usage, Mapping) else Nonedef responses_result(tool: str, readout: ResponsesReadout, say: Say, *, failure: str | None = None) -> ExecutorResult:@@ -304,6 +325,10 @@ def responses_result(tool: str, readout: ResponsesReadout, say: Say, *, failure:keeps. A call the provider marked failed is failed too."""+ return replace(_responses_record(tool, readout, say, failure), usage=_usage_section(readout.response))+++def _responses_record(tool: str, readout: ResponsesReadout, say: Say, failure: str | None) -> ExecutorResult:response = readout.response or {}calls = [item for item in readout.items if _responses_call_tool(item) == tool]if tool == "image_generation":@@ -531,6 +556,10 @@ def anthropic_result(body: bytes | bytearray, say: Say) -> ExecutorResult:message = json.loads(body)except (ValueError, RecursionError):return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable")))+ return replace(_anthropic_record(message, say), usage=_usage_section(message))+++def _anthropic_record(message: Any, say: Say) -> ExecutorResult:content = message.get("content") if isinstance(message, dict) else Noneblocks = [block for block in content if isinstance(block, dict)] if isinstance(content, list) else []if not any(block.get("type") == "server_tool_use" and block.get("name") == "web_search" for block in blocks):diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 22e814dd0..bfc39267c 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -126,6 +126,7 @@ from .hosted_executor import (executor_streams,failed_record,parse_call,+ provider_charges,responses_result,)from .hosted_tools import (@@ -716,6 +717,13 @@ def _pin_unavailable() -> ModelHubError:return ModelHubError(PIN_UNAVAILABLE_CODE, status=409)+def _call_usage(outcome: RawCallOutcome | None, observed: ProtocolSSEState | None) -> ProtocolUsageReport | None:+ """The tokens one upstream call reported: its outcome's, else what was observed on the wire."""++ usage = outcome.usage if outcome is not None else None+ return observed.usage if usage is None and observed is not None else usage++def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *, refused: str | None) -> str | None:"""How a proxied hosted call failed, in the user's language; None when it succeeded.@@ -6174,12 +6182,6 @@ class ModelHubService:raise cancelledif not admitted:return unavailable- execution = {- "mode": "proxy",- "executor_origin": {"provider": source.vendor, "api": source.protocol, "model": model_id},- "executor_source_id": source.id,- "executor_billing": source.billing,- }failure = _executor_failure(outcome, say, refused=refused)if reader is not None:result = await asyncio.to_thread(responses_result, tool, reader.readout, say, failure=failure)@@ -6188,6 +6190,21 @@ class ModelHubService:else:# The bytearray itself goes to the worker: no copy of up to the response budget on the loop.result = await asyncio.to_thread(anthropic_result, body, say)+ execution: dict[str, Any] = {+ "mode": "proxy",+ "executor_origin": {"provider": source.vendor, "api": source.protocol, "model": model_id},+ "executor_source_id": source.id,+ "executor_billing": source.billing,+ }+ # The call's cost is the pricing module's, from what the meter saw and what the provider reported.+ counts, reported_usd = provider_charges(source.protocol, result.usage if result is not None else None)+ cost = self.hosted_call_cost(+ source, model_id, (tool,),+ usage=_call_usage(outcome, handle.observed if handle is not None else cancelled_observed),+ counts=counts, reported_usd=reported_usd,+ )+ if cost is not None:+ execution["cost"] = {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}if result is None:return {"record": failed_record(failure or say("modelHub.hostedTools.unreadable")), "execution": execution}answer: dict[str, Any] = {"record": result.record, "execution": execution}@@ -9324,9 +9341,7 @@ class ModelHubService:without putting an unresponsive disk in front of the next failover hop."""- usage = outcome.usage if outcome is not None else None- if usage is None and observed is not None:- usage = observed.usage+ usage = _call_usage(outcome, observed)reached_model = (outcome is not Noneand (outcome.kind is RawOutcomeKind.SUCCESS or outcome.stream_started)diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.mdindex 69b02bd7a..e267cd34a 100644--- a/docs/plans/agent-core-contracts/model-hub-consumer.md+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md@@ -134,7 +134,11 @@ consumer's requirements, and the Model Hub lane lands the change in both places.1 MiB), 401, 404 for an unknown tool, or 409 `executor_not_bound`, as`{"type": "error", "error": {"type", "code"}}`.- A search call is bounded at 180 s and an image at 300 s. The call is metered on the executor Source and never- changes Source health. `execution.cost` is absent until the pricing module values it.+ changes Source health.+ - `execution.cost` is the pricing module's value of the executor's response (`hosted_call_cost`): `included`+ on a monthly Source, the provider's own figure as `reported` (xAI `cost_in_usd_ticks`), else `list` from the+ call's metered tokens and the provider's hosted counters (`usage.server_tool_use`,+ `usage.server_side_tool_usage_details`). It is absent when the call cannot be valued, never zero.## 3. Not requireddiff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 818bb7ba5..84937e421 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -322,8 +322,8 @@ as a half-open code-point range into `text`.`CitationBadge` (numbered sources, UTF-16 ranges, `body_sha256`). Adapters only parse; IM gets the Markdown links.**`ToolResultMessage.hosted`** (optional): `{record, execution?}`.-- `execution` is a `ProxyExecution`, every field required: `mode: "proxy"`, `executor_origin`,- `executor_source_id`, `executor_billing`, `cost`. It is present exactly when an executor ran. A call that never+- `execution` is a `ProxyExecution`: `mode: "proxy"`, `executor_origin`, `executor_source_id`,+ `executor_billing`, and `cost` when the pricing module can value the call. It is present exactly when an executor ran. A call that neverreached one (none verified, or the bound Source removed) has none, and its `record.status` is `failed`.- `is_error` is `true` exactly when `record.status` is `failed` or `incomplete`.- So a proxied call renders like a native one, and the card names the exact Source even when two Sources share andiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 984c9edf7..90714ecc9 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -2216,7 +2216,7 @@ scenarios:layer: e2e-autotest: tests/e2e/test_model_hub_service_acceptance.py::test_fresh_install_serves_vibey_and_claude_through_the_hub_and_reaps_an_orphaned_engine- id: MH-HOSTED-GATEWAY-004- name: A proxied hosted call runs one native request on its bound executor, without an effort, and answers its canonical record and execution+ name: A proxied hosted call runs one native request on its bound executor, without an effort, and answers its canonical record and execution with the pricing module's coststatus: coveredkind: contractlayer: contract@@ -2225,6 +2225,7 @@ scenarios:- 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-005name: A proxied hosted call that cannot complete is a failed record, with an execution only when an executor ran; only a malformed call is an error statusstatus: covereddiff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.pyindex 58044f33a..2c0181705 100644--- a/tests/test_model_hub_hosted_executor.py+++ b/tests/test_model_hub_hosted_executor.py@@ -20,15 +20,17 @@ import aiohttpimport pytestfrom config.v2_config import ModelHubHostedToolConfig, ModelHubRouteHopConfig-from core.agent_core.messages import message_from_dict+from core.agent_core.messages import HostedCost, message_from_dictfrom core.handlers.model_hub import hosted_executor as executor_modulefrom core.handlers.model_hub import service as service_modulefrom core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKindfrom core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digestfrom core.handlers.model_hub.hosted_executor import excerptfrom core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp+from core.handlers.model_hub.pricing import PriceTablefrom core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReportfrom core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.handlers.model_hub.usage import UsageWriterfrom modules.agents.model_hub import ModelHubRuntimeRouterfrom core.run_settlement import SETTLED_BY_STOPPEDfrom tests.test_model_hub_l3 import (@@ -261,6 +263,65 @@ async def test_an_anthropic_executor_is_buffered_and_keeps_the_providers_results}+ANTHROPIC_SEARCH = {+ "type": "message", "role": "assistant", "stop_reason": "end_turn",+ "content": [+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": [+ {"type": "web_search_result", "url": PAGE_A, "title": "Releases", "encrypted_content": "opaque"},+ ]},+ {"type": "text", "text": "See the releases page."},+ ],+ "usage": {"input_tokens": 2000, "output_tokens": 100, "server_tool_use": {"web_search_requests": 2}},+}++[email protected](("tool", "executor", "billing", "response", "cost"), [+ # xAI's own figure for the whole response, in ticks of 1e-10 USD.+ (+ "x_search", (XAI, "grok-4.6"), "metered",+ _responses(X_CALL, X_ANSWER, usage={"input_tokens": 2000, "output_tokens": 100, "cost_in_usd_ticks": 1_234_000_000}),+ {"basis": "reported", "usd": 0.1234},+ ),+ # The list price: 2,000 input and 100 output tokens at $1 and $5 per million,+ # plus the two searches Anthropic counted at $10 per thousand.+ ("web_search", (ANTHROPIC, "claude-haiku-4-5"), "metered", ANTHROPIC_SEARCH, {"basis": "list", "usd": 0.0225}),+ ("web_search", (ANTHROPIC, "claude-haiku-4-5"), "monthly", ANTHROPIC_SEARCH, {"basis": "included"}),+ # OpenAI reports no search counter, so its per-call fee, and so the call, cannot be valued.+ (+ "web_search", (OPENAI, "gpt-6-astra"), "metered",+ _responses(WEB_CALL, WEB_ANSWER, usage={"input_tokens": 2000, "output_tokens": 100}),+ None,+ ),+])+async def test_a_proxied_call_carries_the_pricing_modules_cost(tmp_path, tool, executor, billing, response, cost):+ """MH-HOSTED-GATEWAY-004: the cost is included, the provider's own figure, or the list price; absent when unknown."""++ sources = [replace(source, billing=billing) if source.id == executor[0] else source for source in _sources()]+ frames = response if isinstance(response, tuple) else (json.dumps(response).encode(),)+ tokens = ProtocolUsageReport.of(input_tokens=2000, cached_input_tokens=0, output_tokens=100)+ service = _vibey_service(tmp_path, sources, handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=executor[0], usage=tokens), frames),+ ])+ prices = PriceTable(+ catalog={"anthropic": {"models": {"claude-haiku-4-5": {"cost": {"input": 1, "output": 5}}}},+ "openai": {"models": {"gpt-6-astra": {"cost": {"input": 1, "output": 5}}}}},+ vendor_map={"families": [{"prefix": "claude-", "vendor_id": "anthropic"}, {"prefix": "gpt-", "vendor_id": "openai"}]},+ overrides={}, price_table_date="2026-10-13",+ )+ service.usage_writer = UsageWriter(service.usage, price_table=lambda: prices)+ _bind(service, tool, executor)+ status, answer = await _call(service, tool, {+ "arguments": {"query": "CLIProxyAPI latest release"},+ "executor": {"source_id": executor[0], "model_id": executor[1]},+ })+ assert status == 200, answer+ assert answer["record"]["status"] == "completed"+ assert answer["execution"].get("cost") == cost+ assert _hosted_result(tool, answer).execution.cost == (HostedCost(**cost) if cost else None)++@pytest.mark.asyncioasync 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.