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(agent-core): retry once after a stream that dropped after thinking alone (#2462)
Call White88ce63506563
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex b86e16125..002fd2bd1 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -696,6 +696,9 @@ class Agent:retries = 0started = time.monotonic()retry_error: Optional[ProviderError] = None+ # A response that dropped after thinking alone is retried once per request (C-2 ``provider.md``): some+ # prompts drop at the same point every time.+ thinking_retried = Falsewhile True:self._scope.check()if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:@@ -760,6 +763,10 @@ class Agent:if isinstance(terminal, ProviderError) and not relieveelse None)+ if delay is not None and terminal.after_thinking:+ if thinking_retried:+ delay = None+ thinking_retried = Trueif delay is None and not relieve:# Admitted here; the caller commits it inside the scope,# BEFORE aclose. Never retry an accepted terminal.diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex dbef4ec1d..310dd742c 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -37,6 +37,7 @@ from core.agent_core.messages import ()from core.agent_core.ai.provider import (RETRYABLE_ERROR_KINDS,+ THINKING_DROP_RETRY_KINDS,BlockEnd,Done,MediaLoader,@@ -165,6 +166,8 @@ class StreamAssembler:self.usage: Any = Noneself._terminal_seen = Falseself._emitted_output = False+ # Text or a tool call: output past which a dropped response is never retried.+ self._emitted_visible = Falseself._closed_indices: set[int] = set()self._slots: dict[tuple[str, Hashable], int] = {}self._block_kinds: dict[Hashable, str] = {}@@ -322,6 +325,7 @@ class StreamAssembler:buffer.write(value)self._visible_blocks.add(index)self._emitted_output = True+ self._emitted_visible = Truereturn TextDelta(index=index, delta=value)def ensure_text_slot(self, key: Hashable) -> int:@@ -341,6 +345,7 @@ class StreamAssembler:self._text_buffers[index] = _string_buffer(value)self._visible_blocks.add(index)self._emitted_output = True+ self._emitted_visible = Truesuffix = value[len(previous) :] if value.startswith(previous) else ""return TextDelta(index=index, delta=suffix) if suffix else None@@ -610,6 +615,7 @@ class StreamAssembler:)self._visible_blocks.add(state["content_index"])self._emitted_output = True+ self._emitted_visible = Trueself._account_output(BLOCK_SLOT_OVERHEAD_BYTES)self._account_tool_identity_block(state)if native:@@ -730,6 +736,7 @@ class StreamAssembler:if not value or state is None or "content_index" not in state:return Noneself._emitted_output = True+ self._emitted_visible = Truereturn ToolCallDelta(index=state["content_index"], arguments_delta=value)def tool_arguments_snapshot(self, key: Hashable, value: str) -> ToolCallDelta | None:@@ -756,6 +763,7 @@ class StreamAssembler:if not suffix:return Noneself._emitted_output = True+ self._emitted_visible = Truereturn ToolCallDelta(index=state["content_index"], arguments_delta=suffix)def pending_tool_arguments(self, key: Hashable) -> ToolCallDelta | None:@@ -1035,10 +1043,16 @@ class StreamAssembler:if self._terminal_seen:return Noneif isinstance(event, ProviderError):- event = _bounded_partial_error(self._sanitize_error(_partial_with_error(event)))+ event = _bounded_partial_error(self._sanitize_error(_partial_with_error(self._after_thinking(event))))self._terminal_seen = Truereturn event+ def _after_thinking(self, error: ProviderError) -> ProviderError:+ """A response that dropped after streaming thinking alone may be retried once (``provider.md``)."""+ if self._emitted_output and not self._emitted_visible and error.kind in THINKING_DROP_RETRY_KINDS:+ return replace(error, retryable=True, after_thinking=True)+ return error+def _sanitize_error(self, error: ProviderError) -> ProviderError:return redact_provider_error(error,diff --git a/core/agent_core/ai/errors.py b/core/agent_core/ai/errors.pyindex f25c3a554..5164d74f3 100644--- a/core/agent_core/ai/errors.py+++ b/core/agent_core/ai/errors.py@@ -231,6 +231,10 @@ def _classify_kind(if status in {408, 409, 425}:return "server"normalized_code = (code or "").lower().replace("-", "_")+ if normalized_code == "modelhub.errors.stream_interrupted":+ # Model Hub's own frame, the one code of the gateway's that names a cause: the upstream stream ended after+ # output without a terminal.+ return "interrupted"if normalized_code in {"authentication_error","authentication",@@ -265,6 +269,10 @@ def _classify_kind("service_unavailable_error",# A Model Hub relay's own failure, its upstream's status folded away."upstream_error",+ # CLIProxyAPI's codes for an upstream timeout, the 408 rule above: `request_timeout` (an upstream 408, or a+ # stream that closed before its terminal) and its Claude type `timeout_error` (an upstream 408 or 504).+ "request_timeout",+ "timeout_error","internal","api_error","unavailable",diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex b023bcf3c..bd823437d 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -21,12 +21,21 @@ ErrorKind = Literal["network","stalled","server",+ # The provider's stream ended after output without a terminal (Model Hub's ``modelHub.errors.stream_interrupted``).+ "interrupted","auth","invalid_request","aborted","unknown",]-RETRYABLE_ERROR_KINDS: frozenset[str] = frozenset({"rate_limit", "overloaded", "network", "stalled", "server"})+RETRYABLE_ERROR_KINDS: frozenset[str] = frozenset(+ {"rate_limit", "overloaded", "network", "stalled", "server", "interrupted"}+)+#: A response that dropped after streaming thinking alone is retried once for these (owner decision, 2026-10-11):+#: a transient failure, or one nothing classified. Never for a rate limit, an overflow, auth, or a rejected request.+THINKING_DROP_RETRY_KINDS: frozenset[str] = frozenset(+ {"overloaded", "network", "stalled", "server", "interrupted", "unknown"}+)@dataclass(frozen=True)@@ -116,6 +125,9 @@ class ProviderError:retry_after_s: Optional[float] = Nonestatus: Optional[int] = Nonepartial: Optional[AssistantMessage] = None+ #: The response streamed thinking and nothing else before this error (``THINKING_DROP_RETRY_KINDS``): it is+ #: ``retryable``, and the loop retries it at most once per request (``provider.md``).+ after_thinking: bool = FalseProviderEvent = Union[TextDelta, ThinkingDelta, ToolCallStart, ToolCallDelta, BlockEnd, Done, ProviderError]diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex ba6c78053..2e58a62d7 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -25,9 +25,9 @@ rules on top of those mappings.| Cumulative assembled-output bound | `StreamAssembler._account_output` is the only byte-accounting function. It covers text, thinking, signatures, opaque/reasoning details, tool arguments, serialized initial tool inputs, tool-call identities and aliases. Each content slot, tool state, or Anthropic block-kind entry adds a conservative 2048-byte structure allowance; each alias adds 512 bytes, plus its string payload. The cumulative accounting budget is 32 MiB across the stream, not an exact process-RSS promise (transport/parser buffers and transient materialization have separate costs). An over-budget mutation raises one terminal `invalid_request` error, preserving the assembled partial. || Error-body read failure | If a known HTTP error body raises or times out while being read, the shared driver classifies from the already-known status and headers, preserving `Retry-After`; the failure remains one terminal provider error with any partial. || Response cleanup | The shared driver's single `finally` owns the opening task as well as its response. It closes successful results even when cancellation wins the same wait cycle or the bounded join; if opening is detached, that `finally` registers a late-result close callback. Cleanup follows terminal delivery and bounds `response.aclose()` at 10 seconds. A stalled close is cleanup-only and cannot replace or duplicate the terminal outcome. |-| Retry boundary | `ProviderError.retryable` is false once any model content delta or tool-call start/delta was emitted. A Responses `ToolCallStart` therefore makes a later provider failure non-retryable. |+| Retry boundary | `ProviderError.retryable` is false once any text delta or tool-call start/delta was emitted. A Responses `ToolCallStart` therefore makes a later provider failure non-retryable. After thinking deltas alone, a `network`, `stalled`, `server`, `overloaded`, `interrupted`, or `unknown` failure is retryable with `after_thinking` set (`provider.md`); every other kind stays non-retryable. || Partial and abort | The shared `partial_message` policy is used by all three adapters. Usage captured before the first visible delta is retained, and errors/abort carry an assembled `AssistantMessage` whenever visible content or usage exists; empty placeholder slots alone do not count as streamed output, while non-empty terminal snapshots do. Consumer/task cancellation is preserved even if response cleanup fails. |-| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. A retry-admitted usage-only partial is never context: the retry resends the original request, and the attempt's usage is one non-context `ModelAttempt` audit row, in every mode (C-9 `context.md` §10, invariant 4), so per-attempt usage is kept without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_keeps_a_usage_only_partial_out_of_the_context` are the loop proofs. |+| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. It admits at most one `after_thinking` retry per request; that attempt's thinking partial is never context, like any retried attempt's. A retry-admitted usage-only partial is never context: the retry resends the original request, and the attempt's usage is one non-context `ModelAttempt` audit row, in every mode (C-9 `context.md` §10, invariant 4), so per-attempt usage is kept without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_keeps_a_usage_only_partial_out_of_the_context` are the loop proofs. || Tool-call stop normalization | `StreamAssembler.finalize` changes only `stop` with one or more tool calls to canonical `tool_use`, following Pi. The loop admits execution only for `stop_reason="tool_use"`; calls attached to `length`, `safety`, `refusal`, or `error` are settled as `is_error` results explaining the stop reason. || Parallel tool calls | No request turns them off, so a response may carry several calls: Anthropic Messages sends no `tool_choice`, so `disable_parallel_tool_use` keeps its default `false`; Chat Completions and Responses send no `parallel_tool_calls`, which defaults to `true`; a `google` hop is called over Chat Completions at the Model Hub gateway (`modules/agents/vibey/models.py`), whose translation to Gemini sets no `toolConfig` for such a request. No request may send `parallel_tool_calls: false`: Gemini has no switch for it, and the gateway's engine (CLIProxyAPI `c404af96`, `internal/translator/gemini/openai/chat-completions/gemini_openai_request.go`) then turns every tool off. The loop runs neighbouring concurrent calls at the same time and every `edit` or `write` alone (C-3 `loop-control.md` §2), a deviation from Pi, which runs a response's calls at once and serializes mutations only per file path. |@@ -137,13 +137,14 @@ or extracted message/code pair that its wire format makes available.| Anthropic | `authentication_error`, `invalid_api_key`, `permission_error`, `permission` | `rate_limit_error` | `overloaded_error` → `overloaded`; `api_error` → `server` | `invalid_request_error` with context text; `context_length_exceeded` → `overflow` || OpenAI Chat | `authentication_error`, `invalid_api_key`, `permission` | `rate_limit_error`, `too_many_requests` | `server_error`, `api_error` | `context_length_exceeded`, `request_too_large` || OpenAI Responses | `unauthenticated`, `permission_denied`, `invalid_api_key` | `rate_limit`, `rate_limit_error` | `overloaded`, `server_error`, `service_unavailable` | `context_length_exceeded`, `request_too_large` |-| Model Hub relays, any protocol | | | `upstream_error`, `service_unavailable_error` → `server` | |+| Model Hub relays, any protocol | | | `upstream_error`, `service_unavailable_error`; `request_timeout` and `timeout_error` (CLIProxyAPI, Model Hub's engine: `request_timeout` for an upstream `408` or an upstream stream that closed before its terminal, nested under `error` with type `server_error`; `timeout_error`, its Claude type for an upstream `408` or `504`) → `server` | |+| Model Hub's own frame, OpenAI Responses and Chat | | | `modelHub.errors.stream_interrupted` (the gateway's code for an upstream stream that ended after output without a terminal) → `interrupted` | |HTTP `401/403` always map to `auth`, `413` to `overflow`, `429` to`rate_limit` with `Retry-After`, and `5xx` to `server` or `overloaded`. A server code follows the same rule as a`5xx`: it is `overloaded` when its message says overloaded (OpenAI's capacity shed is a `service_unavailable_error`that says so), otherwise `server`.Transport errors map to `network`, and the silence bound to `stalled`. Every classification is non-retryable once-the assembler has emitted visible content or a tool-call event.+the assembler has emitted text or a tool-call event; after thinking alone, see the Retry boundary row.## Endpoint identity and redaction ledger@@ -527,7 +528,7 @@ Anthropic stream events:| `ping` | state | Ignored keepalive. || SSE data-only frame with a known JSON event type | delta/state | Accepted because SSE `event` is optional; this is the documented rule (b) data-loss prevention deviation from Pi's event-name filter. || `error` before deltas | retryable or terminal `ProviderError` | Provider error type selects the kind; `message_start` usage is retained in `partial` when present. |-| `error` after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false`. |+| `error` after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false` after text or tool-call deltas (thinking alone: Retry boundary). || unknown `content_block` type | state | Ignored like Pi; later deltas for an unknown block index are ignored. || malformed JSON, block, delta, or redacted payload | terminal `ProviderError` | `invalid_request` for malformed provider metadata, otherwise `unknown`; never a successful `Done`. || EOF without `message_stop` or response close failure | terminal `ProviderError` | After `message_start`, incomplete/transport failure preserves partial content and early usage regardless of a captured stop reason; close failures retain the same partial. |@@ -570,7 +571,7 @@ Chat stream events:| `choices[0].native_finish_reason` | state | A non-normal native reason such as `safety` or `recitation` overrides `finish_reason="stop"`; this prevents tool execution after a safety stop from a converted Gemini response. || `usage` | state | One `_openai_usage` normalizer for chunk and choice usage. Cache reads use the first non-null nested `cached_tokens`, top-level `prompt_cache_hit_tokens`, or top-level `cached_tokens`; zero is authoritative. Cached read/write tokens are excluded from `input_tokens`; reasoning is already included in output. || top-level `error` frame before deltas | retryable or terminal `ProviderError` | Classified from error type/code. |-| top-level `error` frame after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false`. |+| top-level `error` frame after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false` after text or tool-call deltas (thinking alone: Retry boundary). || `data: [DONE]` | Done or terminal error | Completes the response only after a `finish_reason`; without one it is an incomplete `network` error, retryable only when no model output was emitted. A finish reason may also complete at clean EOF. || malformed tool metadata, JSON, or EOF/close failure | terminal `ProviderError` | Invalid metadata is `invalid_request`; incomplete/transport failures retain partial state. |@@ -617,7 +618,7 @@ Responses stream events:| `response.content_part.added/done`, `response.output_text.done`, reasoning `*.done` | state | Recognized no-op completion markers. || `response.completed.response.usage` | Done | `Usage`; cached read/write tokens are excluded from `input_tokens`. Terminal status is normalized. Function calls and ordinary message/reasoning items listed only in terminal `response.output` are not adopted; existing reasoning signatures are backfilled and refusal status is detected. || `response.incomplete.response.usage` without an error | Done or terminal `ProviderError` | The outer `response.incomplete` event always takes the incomplete path even when nested `response.status` is absent or stale. `max_output_tokens`/length becomes `length`; safety/content filtering becomes `safety`; other, missing, or unknown reasons become terminal `error`. |-| `response.incomplete.response.error` | retryable or terminal `ProviderError` | Error code and usage are retained; after visible deltas `retryable=false`. |+| `response.incomplete.response.error` | retryable or terminal `ProviderError` | Error code and usage are retained; after text or tool-call deltas `retryable=false` (thinking alone: Retry boundary). || `response.failed` / top-level `error` | retryable or terminal `ProviderError` | Error code classification with partial content and usage. || malformed output item, tool metadata, JSON, or EOF/close failure | terminal `ProviderError` | Invalid metadata is `invalid_request`; transport/incomplete failures retain partial state. |diff --git a/docs/plans/agent-core-contracts/provider-event.schema.json b/docs/plans/agent-core-contracts/provider-event.schema.jsonindex d1c8149e3..ac5ed48f8 100644--- a/docs/plans/agent-core-contracts/provider-event.schema.json+++ b/docs/plans/agent-core-contracts/provider-event.schema.json@@ -40,9 +40,10 @@"additionalProperties": false,"properties": {"type": { "const": "error" },- "kind": { "enum": ["overflow", "rate_limit", "overloaded", "network", "stalled", "server", "auth", "invalid_request", "aborted", "unknown"] },+ "kind": { "enum": ["overflow", "rate_limit", "overloaded", "network", "stalled", "server", "interrupted", "auth", "invalid_request", "aborted", "unknown"] },"retryable": { "type": "boolean" },"retry_after_s": { "type": "number", "minimum": 0 },+ "after_thinking": { "type": "boolean", "description": "The response streamed thinking and nothing else before this transient or unknown error; the loop retries it at most once per request (provider.md)." },"status": { "type": "integer", "description": "HTTP status, when there was one." },"message": { "type": "string", "description": "Provider message with credentials removed." },"partial": { "$ref": "message.schema.json#/definitions/AssistantMessage", "description": "What streamed before the error, with stop_reason `error` or `aborted`; never replayed as a valid response." }diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex 9bfa7ce43..312bf3318 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -75,10 +75,19 @@ Error classification is part of the contract because the loop branches on it:| `kind` | Meaning | Loop action || --- | --- | --- || `overflow` | the request exceeded the model's context (Pi's overflow patterns, HTTP 413, `context_length_exceeded`) | overflow recovery (plan §5.2) |-| `rate_limit`, `overloaded`, `network`, `stalled`, `server` | transient (`network`: the provider could not be reached; `stalled`: a connected provider sent nothing for the silence bound) | retry with backoff, honoring `retry_after_s`, only when nothing was streamed (no deltas, no `partial`), at most 3 retries within 120 s; then the run ends with that error. After streamed output the error is terminal for the request, matching Model Hub's first-byte rule |+| `rate_limit`, `overloaded`, `network`, `stalled`, `server`, `interrupted` | transient (`network`: the provider could not be reached; `stalled`: a connected provider sent nothing for the silence bound; `interrupted`: the provider's stream ended after output without a terminal, as Model Hub reports with its own `modelHub.errors.stream_interrupted` frame) | retry with backoff, honoring `retry_after_s`, only when nothing was streamed (no deltas, no `partial`), at most 3 retries within 120 s; then the run ends with that error. After streamed text or a tool call the error is terminal for the request, matching Model Hub's first-byte rule; after thinking alone it is retried once (below) || `auth`, `invalid_request` | not retryable | end the run with the error || `aborted` | cancelled by the caller | end the run as aborted |-| `unknown` | anything else | end the run with the error |+| `unknown` | anything else | end the run with the error; after thinking alone, retry once (below) |++**A stream that dropped after thinking alone** (owner decision, 2026-10-11). When a response fails after it+streamed thinking and nothing else (no text, no tool call), with a `network`, `stalled`, `server`, `overloaded`,+`interrupted`, or `unknown` error, the `ProviderError` has `retryable` and `after_thinking` set. The loop retries such an error at+most once per request, inside the same count and time budget; a second drop ends the run with that error, because+some prompts drop at the same point every time. The dropped attempt's thinking is never context: it stays in the+attempt ledger and its audit (C-9 `context.md` §10, invariant 4), and the retry resends the original request.+A refusal or safety stop is a response, not an error, and `auth`, `invalid_request`, `overflow`, and `rate_limit`+after thinking stay terminal.A `ProviderError` whose `partial` is committed (a response that failed after output) carries the error's text as thatpartial's `error_message`, redacted like the error itself and bounded to 1,000 characters, so the transcript row saysdiff --git a/modules/agents/vibey/errors.py b/modules/agents/vibey/errors.pyindex 85dd20a0e..e13bf9cf1 100644--- a/modules/agents/vibey/errors.py+++ b/modules/agents/vibey/errors.py@@ -33,6 +33,8 @@ _KIND_KEYS: dict[str, str] = {"network": "network","stalled": "stalled","server": "server",+ # The provider's stream broke off before its terminal (Model Hub's own frame), not a run the user stopped.+ "interrupted": "streamInterrupted","auth": "auth","invalid_request": "invalidRequest",# A provider failure C-2 could not classify: an unknown code, or an error frame no rule names.diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.pyindex c44409c3b..7b8769a27 100644--- a/tests/agent_core/agent/test_loop.py+++ b/tests/agent_core/agent/test_loop.py@@ -623,6 +623,118 @@ async def test_retry_obeys_provider_flag_and_allows_usage_only_partial(streamed,assert events[-1].reason == "completed"+# OpenAI Responses streams, as the real adapter reads them: reasoning, then how the response ended.+_REASONING = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"**Checking the catalog**"}\n\n'+)+_TEXT = (+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"message","id":"msg_1"}}\n\n'+ 'data: {"type":"response.output_text.delta","output_index":1,"delta":"Checking"}\n\n'+)+_TOOL = (+ 'data: {"type":"response.output_item.added","output_index":1,'+ '"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"echo","arguments":""}}\n\n'+)+_COMPLETED = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_2"}}\n\n'+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"done"}\n\n'+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'+)+# How a stream drops: a cut connection, or an error frame with a code (Model Hub's own frame names a copy key).+_DROPS = {+ "network": "",+ # CLIProxyAPI's frame, byte for byte, for an upstream stream that closed before its terminal: the class nested+ # under `error` (sdk/api/handlers/openai_responses_stream_error.go). Model Hub forwards it as it is.+ "server": (+ '\nevent: error\ndata: {"type":"error","error":{"code":"request_timeout","message":"stream error: stream '+ 'disconnected before completion: stream closed before response.completed","param":null,"type":"server_error"},'+ '"sequence_number":3}\n\n'+ ),+ "overloaded": 'data: {"type":"error","code":"overloaded","message":"busy"}\n\n',+ "interrupted": 'data: {"type":"error","code":"modelHub.errors.stream_interrupted","message":"中断"}\n\n',+ "unknown": 'data: {"type":"error","code":"a_code_nobody_names","message":"failed"}\n\n',+ "auth": 'data: {"type":"error","code":"invalid_api_key","message":"denied"}\n\n',+ "rate_limit": 'data: {"type":"error","code":"rate_limit_exceeded","message":"slow down"}\n\n',+ "overflow": 'data: {"type":"error","code":"context_length_exceeded","message":"too long"}\n\n',+ "invalid_request": 'data: {"type":"response.failed","response":{"status":"failed","error":"not an object"}}\n\n',+}+++async def _run_responses(bodies, store=None):+ """A run over the real OpenAI Responses adapter; returns its events and the request payloads it sent."""+ import json++ import httpx++ from core.agent_core.ai.openai_responses import OpenAIResponsesAdapter+ from core.agent_core.ai.provider import ModelEndpoint+ from tests.agent_core.fakes import SELECTION++ remaining, sent = list(bodies), []++ def handler(request: httpx.Request) -> httpx.Response:+ sent.append(json.loads(request.content))+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=remaining.pop(0))++ endpoint = ModelEndpoint("openai_responses", "https://model.test/v1", "m", "token")+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ agent = Agent(+ session_id="session",+ models=FakeModelRouter(OpenAIResponsesAdapter(client), (replace(SELECTION, endpoint=endpoint),)),+ tools=(FakeTool("echo"),),+ hooks=(),+ store=store or InMemoryTranscriptStore(),+ jobs=FakeJobHost(),+ cwd="/test-owned",+ retry=RetryPolicy(initial_delay_s=0),+ )+ events = await collect(agent)+ return events, sent++[email protected]("drop", ["network", "server", "overloaded", "interrupted", "unknown"])+async def test_a_stream_that_dropped_after_thinking_alone_is_retried_once_and_the_run_completes(drop):+ store = InMemoryTranscriptStore()++ events, sent = await _run_responses([_REASONING + _DROPS[drop], _COMPLETED], store=store)++ assert events[-1].reason == "completed"+ # The dropped attempt's thinking is never context: the retry resends the original request unchanged.+ assert len(sent) == 2 and sent[1]["input"] == sent[0]["input"]+ responses = [row.message for row in await store.load("session") if row.kind == "response"]+ assert [response.content for response in responses] == [(text("done"),)]+++async def test_a_second_drop_after_thinking_alone_ends_the_run_with_its_kind():+ # Some prompts drop at the same point every time: one retry, never two.+ events, sent = await _run_responses([_REASONING + _DROPS["server"]] * 2 + [_COMPLETED])++ assert len(sent) == 2+ assert events[-1].reason == "error"+ assert (events[-1].cause.kind, events[-1].cause.origin) == ("server", "source")+++ ("streamed", "drop"),+ [+ (_TEXT, "network"),+ (_REASONING + _TEXT, "server"),+ (_TOOL, "network"),+ (_REASONING, "auth"),+ (_REASONING, "rate_limit"),+ (_REASONING, "overflow"),+ (_REASONING, "invalid_request"),+ ],+ ids=["text", "thinking-then-text", "tool-call", "auth", "rate_limit", "overflow", "invalid_request"],+)+async def test_a_drop_after_visible_output_or_of_a_lasting_kind_is_never_retried(streamed, drop):+ events, sent = await _run_responses([streamed + _DROPS[drop], _COMPLETED])++ assert len(sent) == 1+ assert events[-1].reason in {"error", "context_exhausted"}++async def test_retry_keeps_a_usage_only_partial_out_of_the_context():# A usage-only partial is attempt data, never context: the retry resends the original request.store = InMemoryTranscriptStore()diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.pyindex d4dc56a9c..8b654aee6 100644--- a/tests/agent_core/ai/test_provider_adapters.py+++ b/tests/agent_core/ai/test_provider_adapters.py@@ -4461,6 +4461,24 @@ async def test_provider_error_envelope_is_classified_identically_from_every_sour"Our servers are currently overloaded. Please try again later.","overloaded",),+ # CLIProxyAPI, Model Hub's engine, byte for byte: its Claude type for an upstream 408 or 504, and its+ # Responses class for an upstream stream that closed before its terminal.+ (+ AnthropicAdapter,+ "anthropic",+ 'event: error\ndata: {"type":"error","error":{"type":"timeout_error","message":"upstream timeout"}}\n\n',+ "upstream timeout",+ "server",+ ),+ (+ OpenAIResponsesAdapter,+ "openai_responses",+ '\nevent: error\ndata: {"type":"error","error":{"code":"request_timeout","message":"stream error: stream '+ 'disconnected before completion: stream closed before response.completed","param":null,'+ '"type":"server_error"},"sequence_number":1}\n\n',+ "stream error: stream disconnected before completion: stream closed before response.completed",+ "server",+ ),],)async def test_a_relay_failure_frame_before_output_is_a_retryable_server_failure(@@ -4514,11 +4532,96 @@ async def test_a_failed_response_keeps_its_error_on_the_partial_it_commits(messaevents = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))error = events[-1]- assert isinstance(error, ProviderError) and error.kind == "unknown"+ assert isinstance(error, ProviderError) and error.kind == "interrupted"assert error.partial is not None and error.partial.stop_reason == "error"assert error.partial.error_message == kept+# Model Hub's frame for an upstream stream that ended after output without a terminal: its code is the gateway's+# copy key, its message localized copy (``stream_wire.py`` renders the Responses and Chat frames).+ ("adapter_type", "protocol", "frame"),+ [+ (+ OpenAIResponsesAdapter,+ "openai_responses",+ {"type": "error", "code": "modelHub.errors.stream_interrupted", "message": "供应商响应已中断。", "param": None},+ ),+ (+ OpenAIChatAdapter,+ "openai_chat",+ {+ "object": "chat.completion.chunk",+ "type": "error",+ "error": {"type": "server_error", "code": "modelHub.errors.stream_interrupted", "message": "中断"},+ "choices": [],+ },+ ),+ ],+)+async def test_model_hubs_stream_interrupted_frame_is_the_interrupted_kind(adapter_type, protocol, frame) -> None:+ body = f"event: error\ndata: {json.dumps(frame, ensure_ascii=False)}\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(adapter_type(client), _request(protocol))++ error = events[-1]+ assert isinstance(error, ProviderError)+ assert (error.kind, error.retryable) == ("interrupted", True)+++# CLIProxyAPI nests the class under `error`; OpenAI's reference carries it at the root.+_SERVER_ERROR_FRAMES = {+ "cpa-nested": 'data: {"type":"error","error":{"code":"request_timeout","message":"stream error: stream '+ 'disconnected before completion: stream closed before response.completed","param":null,"type":"server_error"},'+ '"sequence_number":3}\n\n',+ "root": 'data: {"type":"error","code":"server_error","message":"failed"}\n\n',+}++[email protected]("frame", sorted(_SERVER_ERROR_FRAMES))+ ("streamed", "flagged"),+ [+ ("", False),+ ('data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"plan"}\n\n', True),+ (+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"plan"}\n\n'+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"message","id":"msg_1"}}\n\n'+ 'data: {"type":"response.output_text.delta","output_index":1,"delta":"Hi"}\n\n',+ False,+ ),+ ],+ ids=["nothing", "thinking-alone", "thinking-then-text"],+)+async def test_only_a_drop_after_thinking_alone_is_marked_after_thinking(+ streamed: str, flagged: bool, frame: str+) -> None:+ """C-2: ``after_thinking`` marks a transient drop after thinking alone, which is then ``retryable`` once."""+ body = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'+ + streamed+ + _SERVER_ERROR_FRAMES[frame]+ )++ 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(OpenAIResponsesAdapter(client), _request("openai_responses"))++ error = events[-1]+ assert isinstance(error, ProviderError) and error.kind == "server"+ assert error.after_thinking is flagged+ # Before any output a server error was always retryable; after text it never is.+ assert error.retryable is (flagged or not streamed)++@pytest.mark.asyncio@pytest.mark.parametrize(("adapter_type", "protocol", "body", "outcome", "stop_reason", "error_kind", "partial"),diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex ad30e60fb..5c83f9e3d 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -2244,6 +2244,60 @@ async def test_a_turn_runs_through_the_real_provider_registry(engine, session, tassert harness.controller.im_client.sent == ["hi"]+# How a stream breaks off: the connection simply ends, or CLIProxyAPI (Model Hub's engine) reports the upstream+# closing before its terminal in its own frame, byte for byte, which Model Hub forwards as it is.+_THINKING_DROPS = {+ "eof": ("", "network"),+ "engine-frame": (+ '\nevent: error\ndata: {"type":"error","error":{"code":"request_timeout","message":"stream error: stream '+ 'disconnected before completion: stream closed before response.completed","param":null,"type":"server_error"},'+ '"sequence_number":2}\n\n',+ "server",+ ),+}++[email protected]("drop", sorted(_THINKING_DROPS))[email protected]("drops", [1, 2])+async def test_a_stream_that_drops_after_thinking_alone_gets_one_retry_then_its_own_copy(+ engine, session, tmp_path, published, drops, drop+) -> None:+ """Owner decision 2026-10-11: one retry after a stream that carried only thinking; a second drop shows the+ drop's own copy, never the generic line."""+ import httpx++ from modules.agents.vibey.models import registry_providers++ served = json.dumps({"provider": "upstream", "api": "openai_responses", "model": "served-model"}, separators=(",", ":"))+ ending, copy = _THINKING_DROPS[drop]+ thinking_then_cut = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"**Checking the catalog**"}\n\n'+ + ending+ )+ bodies = [thinking_then_cut] * drops + [_TEXT_STREAMS["openai_responses"][1]]+ sent: list[dict] = []++ def gateway(request: httpx.Request) -> httpx.Response:+ sent.append(json.loads(request.content))+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=bodies.pop(0)+ )++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(+ engine, tmp_path, "telegram", [], providers=registry_providers(media_loader=None, client=client)+ )+ harness.controller.hub_protocol = "openai_responses"+ await harness.agent.handle_message(harness.request("hello"))++ assert len(sent) == 2 and sent[1]["input"] == sent[0]["input"]+ if drops == 1:+ assert harness.controller.im_client.sent == ["hi"]+ else:+ assert harness.controller.im_client.sent == [f"❌ {i18n_t(f'vibeyAgent.error.{copy}', 'en')}"]++async def test_a_turn_runs_bash_through_the_real_job_host(engine, session, tmp_path, published) -> None:command = "printf 'hi from bash'"call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex a92bae50f..e1c0b9583 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1693,6 +1693,7 @@"network": "The model provider could not be reached. Check the network and the Model Hub source.","stalled": "The model provider sent no new data for more than {minutes} minutes, so this turn was stopped. Try again, or choose another model.","server": "The model provider returned a server error. Try again in a moment.",+ "streamInterrupted": "The model provider's response broke off before it finished. Try again.","auth": "The model provider rejected the credentials of this route. Check the Model Hub source.","invalidRequest": "The model provider rejected the request.","modelError": "The model stopped with an error.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex bf3f0a2ea..638e32c6b 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1693,6 +1693,7 @@"network": "无法连接模型服务商。请检查网络和 Model Hub 来源。","stalled": "模型服务商超过 {minutes} 分钟没有返回新数据,本轮已中止。可以重试,或换一个模型。","server": "模型服务商返回了服务器错误,请稍后重试。",+ "streamInterrupted": "模型服务商的回复中途断开了。可以重试。","auth": "模型服务商拒绝了此路由的凭据。请检查 Model Hub 来源。","invalidRequest": "模型服务商拒绝了这个请求。","modelError": "模型因错误而停止。",