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.

fix(model-hub): keep Claude hub streams alive while resolving (#2222)

Call White16b28b89fbc4
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 2893976cd..f7bf73771 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -9,8 +9,8 @@ import math
import socket
import tempfile
from collections import deque
-from collections.abc import Callable, Mapping
-from contextlib import AsyncExitStack, contextmanager, suppress
+from collections.abc import AsyncIterator, Callable, Mapping
+from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import BinaryIO, Final, Optional
@@ -69,6 +69,24 @@ from .service import (
_MAX_REQUEST_BYTES: Final = 128 * 1024 * 1024
_BUFFERED_RESPONSE_MEMORY_BYTES: Final = 256 * 1024
_RESPONSE_CHUNK_BYTES: Final = 64 * 1024
+# Claude Code aborts a stream whose response headers miss its first-byte window
+# and treats a byte-silent body as stalled. Resolution can outlast both through
+# recovery waits, Source failover, or an upstream that sends nothing before its
+# first model output, so a Claude stream commits its headers once resolution is
+# slow and then sends SSE comments, which carry no event, until it resolves.
+_EARLY_STREAM_COMMIT_SECONDS: Final = 2.0
+# Below the CLI's 10s heartbeat so every tick observes bytes.
+_STREAM_KEEPALIVE_SECONDS: Final = 5.0
+_STREAM_KEEPALIVE_FRAME: Final = b": keepalive\n\n"
+_SSE_RESPONSE_HEADERS: Final = {
+ "Cache-Control": "no-store",
+ "Content-Type": "text/event-stream",
+ "X-Accel-Buffering": "no",
+ "X-Content-Type-Options": "nosniff",
+}
+# The ending a local error response carries, so a stream whose headers already
+# left can still deliver it as the protocol's terminal event.
+_LOCAL_ENDING: Final = "model_hub_local_ending"
_SUPPORTED_PATHS: Final = frozenset(
{
"messages",
@@ -185,6 +203,9 @@ class _TurnExecution:
# OpenCode owns its public tool names; the gateway may use collision-free
# upstream aliases, but those names must never escape back to OpenCode.
response_tool_aliases: Mapping[str, str] = field(default_factory=dict)
+ # The downstream event stream once its headers left before resolution
+ # finished. From then on every ending of this turn travels inside it.
+ stream_response: web.StreamResponse | None = None
@property
def upstream_observation(self) -> ProtocolSSEState | None:
@@ -906,27 +927,35 @@ class ModelHubTurnGateway:
decision=decision,
)
+ protocol = _REQUEST_PROTOCOLS[endpoint]
try:
protocol_headers = {
name.lower(): value for name, value in request.headers.items() if name.lower() in _PROTOCOL_HEADERS
}
- if backend == "opencode" and _REQUEST_PROTOCOLS[endpoint] == "openai_chat":
+ if backend == "opencode" and protocol == "openai_chat":
translation = translate_opencode_tool_names(payload)
payload = translation.request
execution.response_tool_aliases = translation.response_aliases
- resolved = await self.service.resolve_with_recovery(
- backend=backend,
- model_id=resolution_model,
- request=ModelHubRequest(
- payload,
- protocol=_REQUEST_PROTOCOLS[endpoint],
- headers=protocol_headers,
- ),
- stream=stream,
- supply_channel="hub",
- attempt_observer=observe_attempt,
- recovery_observer=terminalizer.update_recovery,
- )
+ async with self._stream_kept_alive(request, execution, protocol=protocol, stream=stream):
+ resolved = await self.service.resolve_with_recovery(
+ backend=backend,
+ model_id=resolution_model,
+ request=ModelHubRequest(
+ payload,
+ protocol=protocol,
+ headers=protocol_headers,
+ ),
+ stream=stream,
+ supply_channel="hub",
+ attempt_observer=observe_attempt,
+ recovery_observer=terminalizer.update_recovery,
+ )
+ # Owned before the keepalive stops, so a cancellation while it
+ # stops still closes and meters a Source stream already won.
+ execution.resolved = resolved
+ if resolved.handle is not None and resolved.handle.stream is not None:
+ execution.handle = resolved.handle
+ resources.push_async_callback(resolved.handle.close_stream)
except ModelHubError as exc:
turn_outcome = exc.turn_outcome
if turn_outcome is None and exc.code == "engine_down":
@@ -939,7 +968,7 @@ class ModelHubTurnGateway:
self._commit_and_render_turn_outcome(execution, terminalizer, turn_outcome)
# Native compatibility is keyed by the caller backend. Keep its
# transport result separate from actual upstream provenance.
- return web.json_response(
+ response = web.json_response(
{
"type": "error",
"error": {
@@ -951,33 +980,110 @@ class ModelHubTurnGateway:
status=400 if backend == "codex" else 424,
headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
)
- return self._terminal_error_response(
+ response[_LOCAL_ENDING] = _RenderedTurnOutcome(RECOVERY_EXHAUSTED_CODE, RECOVERY_EXHAUSTED_MESSAGE)
+ return await self._through_committed_stream(execution, protocol, response)
+ return await self._through_committed_stream(
execution,
- terminalizer,
- status=exc.status,
- code=exc.code,
- turn_outcome=turn_outcome,
+ protocol,
+ self._terminal_error_response(
+ execution,
+ terminalizer,
+ status=exc.status,
+ code=exc.code,
+ turn_outcome=turn_outcome,
+ ),
)
- execution.resolved = resolved
- if resolved.handle is not None and resolved.handle.stream is not None:
- execution.handle = resolved.handle
- resources.push_async_callback(resolved.handle.close_stream)
+ if execution.handle is not None:
# The execution boundary must own cleanup before an awaited health
# write: cancellation here still settles and meters this handle.
await self.service._observe_handle_recovery(
resolved.source_id, resolved.settlement_generation, resolved.handle,
backend=resolved.backend, model_id=resolved.requested_model_id,
)
- return await self._resolved_response(
- request,
- resolved,
- protocol=_REQUEST_PROTOCOLS[endpoint],
- stream=stream,
- terminalizer=terminalizer,
- execution=execution,
+ return await self._through_committed_stream(
+ execution,
+ protocol,
+ await self._resolved_response(
+ request,
+ resolved,
+ protocol=protocol,
+ stream=stream,
+ terminalizer=terminalizer,
+ execution=execution,
+ ),
)
+ @asynccontextmanager
+ async def _stream_kept_alive(
+ self,
+ request: web.Request,
+ execution: _TurnExecution,
+ *,
+ protocol: str,
+ stream: bool,
+ ) -> AsyncIterator[None]:
+ """Keep a Claude stream visibly alive while its resolution is slow.
+
+ Codex and OpenCode key recovery handling on the HTTP status, so only
+ Claude streams trade it for a connection kept alive. Resolution still
+ runs in the caller with its own cancellation semantics; the keepalive
+ only writes while it waits, and it has stopped before anything else
+ writes to the response.
+ """
+
+ if not stream or protocol != "anthropic":
+ yield
+ return
+ resolution_ended = asyncio.get_running_loop().create_future()
+ keepalive = asyncio.create_task(self._write_keepalive(request, execution, resolution_ended))
+ try:
+ yield
+ finally:
+ resolution_ended.set_result(None)
+ await keepalive
+
+ async def _write_keepalive(
+ self,
+ request: web.Request,
+ execution: _TurnExecution,
+ resolution_ended: asyncio.Future[None],
+ ) -> None:
+ delay = _EARLY_STREAM_COMMIT_SECONDS
+ # A lost client cancels the request itself, and whatever writes next
+ # reports the disconnect at its own boundary.
+ with suppress(_DownstreamDisconnected):
+ while not (await asyncio.wait({resolution_ended}, timeout=delay))[0]:
+ delay = _STREAM_KEEPALIVE_SECONDS
+ if execution.stream_response is None:
+ response = web.StreamResponse(status=200, headers=_SSE_RESPONSE_HEADERS)
+ await self._downstream_io(response.prepare(request))
+ execution.stream_response = response
+ else:
+ await self._downstream_io(execution.stream_response.write(_STREAM_KEEPALIVE_FRAME))
+
+ async def _through_committed_stream(
+ self,
+ execution: _TurnExecution,
+ protocol: str,
+ response: web.StreamResponse,
+ ) -> web.StreamResponse:
+ """Deliver a local ending inside a stream whose headers already left.
+
+ The status line already promised an event stream, so the ending the
+ response would have carried travels as the protocol's terminal event.
+ """
+
+ committed = execution.stream_response
+ if committed is None or response is committed:
+ return response
+ ending = response.get(_LOCAL_ENDING)
+ if ending is not None:
+ frame = self._terminal_frame(protocol, ending.key, ending.message, ProtocolSSEState(protocol))
+ await self._downstream_io(committed.write(frame))
+ await self._downstream_io(committed.write_eof())
+ return committed
+
async def _resolved_response(
self,
request: web.Request,
@@ -1071,16 +1177,10 @@ class ModelHubTurnGateway:
if rewritten_payload is not None:
await run_owned_in_thread(rewritten_payload.close)
- response = web.StreamResponse(
- status=200,
- headers={
- "Cache-Control": "no-store",
- "Content-Type": "text/event-stream",
- "X-Accel-Buffering": "no",
- "X-Content-Type-Options": "nosniff",
- },
- )
- await self._downstream_io(response.prepare(request))
+ response = execution.stream_response
+ if response is None:
+ response = web.StreamResponse(status=200, headers=_SSE_RESPONSE_HEADERS)
+ await self._downstream_io(response.prepare(request))
wire_state = ProtocolSSEState(protocol)
execution.wire_state = wire_state
tool_name_rewriter = StreamingToolNameRewriter(execution.response_tool_aliases)
@@ -1192,18 +1292,23 @@ class ModelHubTurnGateway:
return
if rendered.key is None or rendered.message is None:
return
+ frame = self._terminal_frame(protocol, rendered.key, rendered.message, wire_state)
+ await self._downstream_io(response.write(frame))
+
+ @staticmethod
+ def _terminal_frame(protocol: str, key: str, message: str, wire_state: ProtocolSSEState) -> bytes:
frame_prefix = wire_state.invalidate_partial_frame()
payload = json.dumps(
render_protocol_terminal_event(
protocol,
- rendered.key,
- rendered.message,
+ key,
+ message,
wire_state.next_sequence_number,
),
ensure_ascii=False,
separators=(",", ":"),
).encode("utf-8")
- await self._downstream_io(response.write(frame_prefix + render_protocol_terminal_frame(protocol, payload)))
+ return frame_prefix + render_protocol_terminal_frame(protocol, payload)
@staticmethod
async def _downstream_io(operation):
@@ -1474,7 +1579,7 @@ class ModelHubTurnGateway:
headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"}
if retry_after is not None and status in {429, 503}:
headers["Retry-After"] = str(max(1, retry_after))
- return web.json_response(
+ response = web.json_response(
{
"error": {
"type": code,
@@ -1485,3 +1590,5 @@ class ModelHubTurnGateway:
status=status,
headers=headers,
)
+ response[_LOCAL_ENDING] = _RenderedTurnOutcome(code, message)
+ return response
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 04cecd2ca..8f84d5c99 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -227,6 +227,9 @@ def claude_settings_for_launch(base_settings: str, launch: ModelHubLaunch | None
# must not become launch-settings overrides of native project/local choices.
connection_env.pop("CLAUDE_CODE_MAX_CONTEXT_TOKENS", None)
connection_env.pop("CLAUDE_CODE_MAX_OUTPUT_TOKENS", None)
+ # Timeout defaults likewise yield to an explicit native choice.
+ for key in _CLAUDE_HUB_TIMEOUT_DEFAULTS:
+ connection_env.pop(key, None)
settings["env"] = {**settings.get("env", {}), **connection_env}
settings["apiKeyHelper"] = ""
return json.dumps(settings)
@@ -314,6 +317,14 @@ def _localized_launch_error(
)
+# The Hub resolves, waits out recovery, and fails over before a stream's first
+# model output, so Claude's pre-output windows are raised to the CLI's maximum.
+_CLAUDE_HUB_TIMEOUT_DEFAULTS = {
+ "API_TIMEOUT_MS": "1800000",
+ "CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS": "1800000",
+}
+
+
def build_claude_hub_env(
base_env: dict[str, str],
launch: ModelHubLaunch,
@@ -346,6 +357,11 @@ def build_claude_hub_env(
result["ANTHROPIC_AUTH_TOKEN"] = launch.gateway_token
result["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
result["CLAUDE_CODE_MAX_RETRIES"] = "0"
+ # The Hub owns retry and failover. A stream error must not make the CLI
+ # replay the whole turn as a second, non-streaming request.
+ result["CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK"] = "1"
+ for key, value in _CLAUDE_HUB_TIMEOUT_DEFAULTS.items():
+ result.setdefault(key, value)
else:
# A native_cli hop keeps the user's official CLI authentication.
result = dict(base_env)
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 0c65de089..7aadbeb77 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -520,6 +520,14 @@ scenarios:
kind: timeout_cancel
layer: contract
test: tests/test_model_hub_inference_wait.py::test_connected_inference_waits_for_its_owner
+ - id: MH-RUNTIME-010
+ name: A slow Claude stream resolution keeps its connection alive and ends inside the stream
+ status: covered
+ kind: timeout_cancel
+ layer: contract
+ test: tests/test_model_hub_retry_lifecycle.py::test_slow_stream_resolution_keeps_claude_connected
+ related_tests:
+ - tests/test_model_hub_injection.py::test_claude_hub_waits_out_resolution_as_one_streaming_request
- id: MH-USAGE-001
name: Tokens an upstream reported before the turn ended are still metered
status: covered
diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yaml
index 3f59a457a..ee464476c 100644
--- a/tests/scenarios/model_hub/observations.yaml
+++ b/tests/scenarios/model_hub/observations.yaml
@@ -1,6 +1,11 @@
version: 2
capability: model_hub
observations:
+ - id: MH-OBS-011
+ source: claude-cli-2.1.280-hub-request-timeouts-2026-09-26
+ summary: Claude hub turns failed with "Request timed out" while the Hub was still resolving. The CLI aborts a stream whose headers miss its first-byte window (300s by default for non-Anthropic base URLs) or whose body stays byte-silent, and the Hub withheld headers until the first model output. Claude streams now commit headers early and send SSE comments during resolution, and Claude hub launches raise the first-byte and API timeouts to the CLI maximum.
+ affects:
+ - MH-RUNTIME-010
- id: MH-OBS-010
source: local-regression-persisted-migration-2026-09-20
summary: Already-Hub backends were all disabled because inherited process authentication was represented as migration blockers. Saved Claude AUTH_TOKEN was mislabeled as permission failure. Migration must inventory persisted files independently of runtime injection, and preserve Bearer transport for supported custom Anthropic endpoints rather than treating it as x-api-key or OAuth.
diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.py
index efdae5aa4..7c847d1d9 100644
--- a/tests/test_model_hub_injection.py
+++ b/tests/test_model_hub_injection.py
@@ -236,6 +236,27 @@ def test_claude_catalog_limits_fill_only_absent_environment_values(channel, expl
assert explicit == original
+ "explicit", [{}, {"API_TIMEOUT_MS": "900000"}, {"CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS": ""}],
+)
+def test_claude_hub_waits_out_resolution_as_one_streaming_request(explicit):
+ """MH-RUNTIME-010: the Hub owns pre-output waits, so the CLI neither aborts nor replays them."""
+ timeouts = ("API_TIMEOUT_MS", "CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS")
+ native = {**explicit, "CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK": "0"}
+ launch = hub_launch()
+
+ env = build_claude_hub_env(native, launch)
+ assert {key: env[key] for key in timeouts} == {key: explicit.get(key, "1800000") for key in timeouts}
+ assert env["CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK"] == "1"
+
+ settings = json.loads(claude_settings_for_launch(json.dumps({"env": native}), launch))
+ assert {key: settings["env"].get(key) for key in timeouts} == {key: explicit.get(key) for key in timeouts}
+ assert settings["env"]["CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK"] == "1"
+
+ official = hub_launch(channel="native_cli", gateway_base_url=None, gateway_token=None)
+ assert build_claude_hub_env(native, official) == native
+
+
def test_hub_connection_settings_preserve_explicit_limits_without_promoting_catalog_defaults():
launch = hub_launch(context_window=128_000, max_output_tokens=32_000)
settings = json.loads(claude_settings_for_launch(
diff --git a/tests/test_model_hub_retry_lifecycle.py b/tests/test_model_hub_retry_lifecycle.py
index 9aa8af3ae..dfa96c38e 100644
--- a/tests/test_model_hub_retry_lifecycle.py
+++ b/tests/test_model_hub_retry_lifecycle.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import copy
+import json
from contextlib import asynccontextmanager
from dataclasses import replace
from datetime import timedelta
@@ -17,6 +18,7 @@ from config.v2_config import ModelHubConfig, ModelHubRouteConfig, ModelHubRouteH
from core.handlers.model_hub.adapter import RawOutcomeKind
from core.handlers.model_hub.retry import RECOVERY_EXHAUSTED_CODE, RECOVERY_EXHAUSTED_MESSAGE
from core.handlers.model_hub.service import ModelHubError
+from core.handlers.model_hub import turn_gateway
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
from modules.agents.model_hub import ModelHubRuntimeRouter, bind_launch
@@ -637,3 +639,100 @@ def test_expiry_after_mixed_real_failures_keeps_the_action_blocker_terminal(tmp_
assert admissions == [(source_id, "shared-model") for source_id in [first.id, second.id] * 2]
assert service.agent_chain(backend, models[backend])["supply_state"] == "interrupted"
asyncio.run(run())
+
+
+KEEPALIVE = b": keepalive\n\n"
+
+
[email protected]("backend", BACKENDS)
[email protected]("ending", ["served", "recovered", "exhausted", "disconnect"])
+def test_slow_stream_resolution_keeps_claude_connected(monkeypatch, tmp_path, backend, ending):
+ """MH-RUNTIME-010: Claude sees headers and keepalives while the Hub resolves.
+
+ Claude Code aborts a stream whose headers or bytes stay silent past its
+ watchdogs, so its streams commit early and carry every ending inside the
+ stream. Codex and OpenCode key recovery on the HTTP status and keep it.
+ """
+ monkeypatch.setattr(turn_gateway, "_EARLY_STREAM_COMMIT_SECONDS", 0.05)
+ monkeypatch.setattr(turn_gateway, "_STREAM_KEEPALIVE_SECONDS", 0.02)
+ exhausted_event = b"event: error\ndata: " + json.dumps(
+ {"type": "error", "error": {"type": "api_error", "message": RECOVERY_EXHAUSTED_MESSAGE}},
+ separators=(",", ":"),
+ ).encode() + b"\n\n"
+
+ async def run() -> None:
+ endpoint, protocol = BACKENDS[backend]
+ source = _source(
+ "src_patient1", "Patient", vendor="anthropic" if backend == "claude" else "openai", protocol=protocol,
+ )
+ service, clock, models = configured_service(tmp_path, sources=[source])
+ metadata, output, terminal, _buffered = WIRE[protocol]
+ held, release, upstream_cancelled = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ calls = []
+
+ async def respond(request: web.Request) -> web.Response:
+ calls.append(await request.json())
+ if len(calls) == 1:
+ # An upstream that sends nothing until its first model output.
+ held.set()
+ try:
+ await release.wait()
+ except asyncio.CancelledError:
+ upstream_cancelled.set()
+ raise
+ elif ending == "exhausted":
+ clock.advance(121)
+ if ending == "served" or (ending == "recovered" and len(calls) == 2):
+ return web.Response(body=metadata + output + terminal, content_type="text/event-stream")
+ return web.json_response({"error": {"type": "server_error"}}, status=503)
+
+ try:
+ async with loopback_engine(tmp_path, service, respond) as (adapter, _engine_client):
+ async with gateway_client(service, backend, models[backend]) as (_gateway, client, url, headers):
+ post = asyncio.create_task(
+ client.post(url, headers=headers, json={"model": "shared-model", "stream": True}),
+ )
+ try:
+ await asyncio.wait_for(held.wait(), timeout=2)
+ if backend == "claude":
+ response = await asyncio.wait_for(post, timeout=2)
+ assert response.status == 200
+ assert response.content_type == "text/event-stream"
+ first = response.content.readexactly(len(KEEPALIVE))
+ assert await asyncio.wait_for(first, timeout=2) == KEEPALIVE
+ else:
+ done, _pending = await asyncio.wait({post}, timeout=0.2)
+ assert not done, "a status-keyed stream committed before resolution ended"
+ if ending == "disconnect":
+ if backend == "claude":
+ response.close()
+ else:
+ post.cancel()
+ await asyncio.wait_for(upstream_cancelled.wait(), timeout=2)
+ else:
+ release.set()
+ if backend != "claude":
+ response = await asyncio.wait_for(post, timeout=2)
+ body = await asyncio.wait_for(response.read(), timeout=2)
+ while body.startswith(KEEPALIVE):
+ body = body[len(KEEPALIVE):]
+ if ending != "exhausted":
+ assert response.status == 200
+ assert body == metadata + output + terminal
+ elif backend == "claude":
+ assert response.status == 200
+ assert body == exhausted_event
+ else:
+ assert response.status == (400 if backend == "codex" else 424)
+ assert RECOVERY_EXHAUSTED_CODE.encode() in body
+ finally:
+ if not post.done():
+ post.cancel()
+ await asyncio.gather(post, return_exceptions=True)
+ assert adapter._active_transports == 0
+ finally:
+ release.set()
+ assert len(calls) == (1 if ending in {"served", "disconnect"} else 2)
+ assert clock.delays == ([] if ending in {"served", "disconnect"} else [30])
+
+ asyncio.run(run())