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
fix(agent-core): preserve converted route context identity (#2978)
Call White1d3347f8425a
diff --git a/core/agent_core/ai/errors.py b/core/agent_core/ai/errors.pyindex dbacfc82f..919d3a806 100644--- a/core/agent_core/ai/errors.py+++ b/core/agent_core/ai/errors.py@@ -64,6 +64,12 @@ _OVERFLOW_PATTERNS = (_OVERFLOW_RE = tuple(re.compile(pattern, re.IGNORECASE) for pattern in _OVERFLOW_PATTERNS)_NON_OVERFLOW_RE = (re.compile(r"^(?:throttling error|service unavailable):", re.IGNORECASE),+ # Only an explicit throttling marker suppresses overflow. The first form covers provider message prefixes; the+ # second covers JSON error type/code fields without turning a generic 400 containing "too many tokens" into one.+ re.compile(r"(?im)^\s*(?:[\w.-]+\.)?ThrottlingException\b"),+ re.compile(+ r'''(?ix)["'](?:__type|type|code|name|error_type|error_code)["']\s*:\s*["'][^"'\r\n]*\bThrottlingException\b'''+ ),re.compile(r"rate limit", re.IGNORECASE),re.compile(r"too many requests", re.IGNORECASE),)diff --git a/core/agent_core/ai/openai_chat.py b/core/agent_core/ai/openai_chat.pyindex fcb782b78..bf064e5e2 100644--- a/core/agent_core/ai/openai_chat.py+++ b/core/agent_core/ai/openai_chat.py@@ -817,6 +817,7 @@ def _normalize_stop(normalized = {"length": "length","max_tokens": "length",+ "model_context_window_exceeded": "length","content_filter": "safety","recitation": "safety","refusal": "refusal",diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex e8e48f3be..edc0559c9 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -120,6 +120,9 @@ class ModelEndpoint:hosted_tools: Mapping[str, HostedToolRoute] = field(default_factory=dict)#: The models ``image_generate`` may call; None when the tool is off or no model is available.image_models: Optional[ImageModels] = None+ #: The upstream protocol whose response origin and tokenizer anchor C-9 for a converted hop; ``None`` when the+ #: wire protocol is also the served protocol.+ origin_api: Optional[ProtocolName] = None@dataclass(frozen=True)diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 9f6f39954..aed434fcb 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -34,6 +34,7 @@ from core.agent_core.messages import (HostedToolBlock,ImageBlock,Message,+ Origin,TextBlock,ThinkingBlock,ToolCallBlock,@@ -524,6 +525,14 @@ def checkpoint_max_tokens(capabilities: ModelCapabilities, configured: int) -> ireturn min(CHECKPOINT_MAX_TOKENS, output_tokens(capabilities, configured))+def _anchor_origin(endpoint: ModelEndpoint) -> Origin:+ """The served origin that anchors C-9 usage for this request, including converted routes."""+ target = endpoint_origin(endpoint)+ if endpoint.origin_api is None:+ return target+ return Origin(provider=target.provider, api=endpoint.origin_api, model=target.model)++def _estimate(request: ModelRequest, transcript: Sequence[Message], anchor: Optional[Anchor]) -> int:"""The anchored usage while it holds, grown by the ``tokens()`` of what changed since; else ``tokens()`` of therequest (section 2).@@ -536,7 +545,7 @@ def _estimate(request: ModelRequest, transcript: Sequence[Message], anchor: Optiremoved is a local estimate taken from a provider count."""whole = sent_tokens(request)- if anchor is None or anchor.response.origin != endpoint_origin(request.endpoint):+ if anchor is None or anchor.response.origin != _anchor_origin(request.endpoint):return wholesent = len(anchor.transcript)if len(transcript) <= sent or transcript[sent] != anchor.response:diff --git a/modules/agents/vibey/models.py b/modules/agents/vibey/models.pyindex cd1f8a1ea..c4c3bb54d 100644--- a/modules/agents/vibey/models.py+++ b/modules/agents/vibey/models.py@@ -185,10 +185,12 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strcontext_price_steps=tuple(sorted(steps)),)base_url = hop["base_url"]+ original_protocol = protocolif protocol == "google":if not gateway_base_url:raise HopResolutionError("a google hop needs the gateway prefix to call Chat Completions")protocol, base_url = "openai_chat", f"{gateway_base_url.rstrip('/')}/v1"+ origin_api = original_protocol if original_protocol != protocol else Noneendpoint = ModelEndpoint(protocol=protocol,base_url=base_url,@@ -200,6 +202,7 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strsource_identity=hop["source_identity"],hosted_tools=hosted_tools,image_models=image_models,+ origin_api=origin_api,)return ModelSelection(endpoint=endpoint, capabilities=capabilities)diff --git a/tests/agent_core/agent/test_context.py b/tests/agent_core/agent/test_context.pyindex 04b581a18..7fd480e99 100644--- a/tests/agent_core/agent/test_context.py+++ b/tests/agent_core/agent/test_context.py@@ -105,6 +105,7 @@ from core.agent_core.messages import (HostedSummary,HostedToolBlock,ImageBlock,+ Origin,TextBlock,ThinkingBlock,ToolCallBlock,@@ -327,17 +328,17 @@ def _usage(total: int) -> Usage:CAPABILITIES = ModelCapabilities(context_window=32_000, max_output_tokens=4_096)-def _anchored_rows(billed: int = 5_000):+def _anchored_rows(billed: int = 5_000, *, endpoint=ENDPOINT, origin=ORIGIN):"""A read, then a response R billed ``billed`` whose row records its request (1,106 tokens), R's result, and alater reply."""rows = Rows()rows.input("x" * 400)rows.tool("read", "w" * 4_000, call_id="before", path="a")read = ToolCallBlock("r", "read", {"path": "f"})- sent = make_request(context_view(rows.rows).messages)+ sent = make_request(context_view(rows.rows).messages, endpoint=endpoint)anchored = rows.add("response",- AssistantMessage((read,), ORIGIN, "tool_use", usage=_usage(billed)),+ AssistantMessage((read,), origin, "tool_use", usage=_usage(billed)),payload={"request": request_facts(sent)},)result = rows.result(read, "y" * 4_000)@@ -463,6 +464,41 @@ def test_a_stored_request_size_the_transcript_cannot_explain_hides_at_most_its_eassert _est(rows, grown(rows, 40_000)) == 12_000 + after + 40_000 - excess # over it: all but the excess+def test_a_converted_route_anchor_uses_the_served_api_without_widening_identity():+ from modules.agents.vibey.models import selection_from_hop++ endpoint = selection_from_hop(+ {+ "backend": "vibey",+ "protocol": "google",+ "base_url": "http://hub.invalid/v1beta",+ "token": "token",+ "runtime_model": "test-model",+ "provider": "test-provider",+ "source_id": "src_google2501",+ "source_identity": "sha256:test-google",+ "request_headers": {},+ "capabilities": {},+ "hosted_tools": {},+ },+ gateway_base_url="http://hub.invalid/vibey",+ ).endpoint+ assert (endpoint.protocol, endpoint.origin_api) == ("openai_chat", "google")+ rows, _, result = _anchored_rows(+ endpoint=endpoint,+ origin=Origin("test-provider", "google", "test-model"),+ )+ request = make_request(context_view(rows.rows).messages, endpoint=endpoint)+ after = message_tokens(result.message) + message_tokens(request.messages[-1])+ assert _est(rows, request) == 5_000 + after+ assert _est(rows, request) > _whole(rows, request)++ # The same provider/model on an ordinary Chat route is not treated as the converted Google route.+ plain_endpoint = replace(endpoint, origin_api=None)+ plain_request = replace(request, endpoint=plain_endpoint)+ assert _est(rows, plain_request) == _whole(rows, plain_request)++def test_a_checkpoint_or_another_route_invalidates_the_anchor():rows, anchored, result = _anchored_rows()other_route = ModelEndpoint("anthropic", "http://model.invalid", "other-model", "", provider="test-provider")diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.pyindex 76ae1d641..998a2fc3c 100644--- a/tests/agent_core/ai/test_provider_adapters.py+++ b/tests/agent_core/ai/test_provider_adapters.py@@ -2444,6 +2444,24 @@ async def test_chat_finish_reason_end_maps_to_stop() -> None:assert events[-1].message.stop_reason == "stop"+ ("finish_reason", "expected"),+ [("model_context_window_exceeded", "length"), ("stop", "stop"), ("content_filter", "safety")],+)+async def test_chat_context_window_finish_reason_maps_only_the_named_reason(finish_reason: str, expected: str) -> None:+ body = f'data: {{"choices":[{{"delta":{{"content":"ok"}},"finish_reason":"{finish_reason}"}}]}}\n\ndata: [DONE]\n\n'++ def handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))++ assert isinstance(events[-1], Done)+ assert events[-1].message.stop_reason == expected++@pytest.mark.asyncioasync def test_anthropic_abort_after_message_start_keeps_usage_in_partial() -> None:stream = _StalledStream(diff --git a/tests/agent_core/ai/test_transform_sse_errors.py b/tests/agent_core/ai/test_transform_sse_errors.pyindex 668a91627..91d7482f4 100644--- a/tests/agent_core/ai/test_transform_sse_errors.py+++ b/tests/agent_core/ai/test_transform_sse_errors.py@@ -357,6 +357,24 @@ def test_overflow_classifies_cerebras_bodyless_status() -> None:assert classify_error(status=400, body="400 status code (no body)").kind == "overflow"+ "body",+ [+ 'ThrottlingException: too many tokens',+ '{"error":{"type":"ThrottlingException","message":"too many tokens"}}',+ '{"error":{"message":"ThrottlingException: too many tokens"}}',+ ],+)+def test_http_400_throttling_is_excluded_from_overflow_without_becoming_rate_limit(body: str) -> None:+ error = classify_error(status=400, body=body)+ assert error.kind == "invalid_request"+ assert error.kind != "overflow"+++def test_generic_http_400_too_many_tokens_remains_overflow() -> None:+ assert classify_error(status=400, body="too many tokens").kind == "overflow"++@pytest.mark.parametrize("status", [401, 403])def test_auth_statuses_are_not_retryable(status: int) -> None:error = classify_error(status=status, body="denied")