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(vibey): record why a run failed and give every failure kind its own copy (#2448)

Call Whitec37d6318816c
diff --git a/core/agent_core/agent/events.py b/core/agent_core/agent/events.py
index f11cf19d8..3811eeb07 100644
--- a/core/agent_core/agent/events.py
+++ b/core/agent_core/agent/events.py
@@ -9,7 +9,10 @@ The adapter maps events onto existing Avibe outputs (``loop-control.md`` section
from __future__ import annotations
from dataclasses import dataclass
-from typing import Literal, Optional, Union
+from typing import Literal, Optional, Union, get_args
+
+from core.agent_core.ai.provider import ErrorKind
+from core.agent_core.messages import StopReason
RunEndReason = Literal["completed", "aborted", "error", "ended_by_hook", "context_exhausted"]
CompactionReason = Literal["threshold", "overflow"]
@@ -18,6 +21,25 @@ CompactionMode = Literal["normal", "rolling", "dropped"]
#: rejected, a response the transcript cannot hold); ``local`` is everything else (a Stop, an overflow or context
#: exhaustion, a hook, tool, or store error).
ErrorOrigin = Literal["source", "local"]
+#: The kinds the loop names itself (C-3 section 6), beside a provider error's C-2 ``ErrorKind`` and a failed
+#: response's ``StopReason``: an empty reply, what does not fit the context (C-9 section 8 d), a cancelled dependency,
+#: a failed stream cleanup, and the two exceptions that have copy of their own.
+LoopErrorKind = Literal[
+ "empty_response",
+ "context_exhausted",
+ "tool_output_too_large",
+ "input_too_large",
+ "step_too_large",
+ "dependency_cancelled",
+ "stream_cleanup",
+ "UnsupportedModelRoute",
+ "ProviderProtocolViolation",
+]
+#: Every kind an ``AgentError`` can name (``tool_use`` never ends a run). Any other kind is the class name of an
+#: exception the loop did not expect, and that error is local.
+NAMED_ERROR_KINDS: frozenset[str] = frozenset(
+ (*get_args(ErrorKind), *get_args(StopReason), *get_args(LoopErrorKind))
+) - {"tool_use"}
@dataclass(frozen=True)
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index cd71dff78..b86e16125 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -595,10 +595,14 @@ class Agent:
reason = "aborted" if self._outcome.reason == "aborted" or self._ctx.cancel.cancelled else "killed"
await self.jobs.kill_foreground(self.session_id, reason=reason)
except Exception as error:
- self._outcome.foreground_leaked()
+ decided = self._outcome.foreground_leaked()
if self._consumer_closed:
raise
- self._outcome.diagnostic(type(error).__name__, str(error))
+ if decided:
+ # It decided the outcome, so it is the cause ``RunEnded`` names (C-3 section 6).
+ await self._error(emit, type(error).__name__, str(error), "local", cause=True)
+ else:
+ self._outcome.diagnostic(type(error).__name__, str(error))
await self._flush_diagnostics(emit)
@staticmethod
diff --git a/core/agent_core/agent/outcome.py b/core/agent_core/agent/outcome.py
index 9a9e32d3e..800fa40b8 100644
--- a/core/agent_core/agent/outcome.py
+++ b/core/agent_core/agent/outcome.py
@@ -26,10 +26,13 @@ class OutcomeOwner:
raise RuntimeError("the run has no primary outcome")
return self._reason
- def foreground_leaked(self) -> None:
- # The sole cleanup exception to first-cause ownership.
+ def foreground_leaked(self) -> bool:
+ """The sole cleanup exception to first-cause ownership: a completed run whose foreground job cannot be
+ released ends ``error``. True when this decided the outcome, which makes the leak the run's cause."""
if self._reason == "completed":
self._reason = "error"
+ return True
+ return False
def diagnostic(self, kind: str, message: str) -> None:
self.diagnostics.append((kind, message))
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.py
index e33c13853..dbef4ec1d 100644
--- a/core/agent_core/ai/_common.py
+++ b/core/agent_core/ai/_common.py
@@ -1035,7 +1035,7 @@ class StreamAssembler:
if self._terminal_seen:
return None
if isinstance(event, ProviderError):
- event = self._sanitize_error(event)
+ event = _bounded_partial_error(self._sanitize_error(_partial_with_error(event)))
self._terminal_seen = True
return event
@@ -1839,6 +1839,27 @@ def assistant_message(
)
+#: A failed response's committed partial keeps the error it ended with (C-1 ``error_message``), so its transcript row
+#: says why the response ended. Bounded after redaction: a non-JSON error body can be a whole page.
+PARTIAL_ERROR_MESSAGE_CHARS = 1000
+
+
+def _partial_with_error(error: ProviderError) -> ProviderError:
+ """The provider's error text on the partial it leaves; a Stop's partial needs none."""
+ partial = error.partial
+ if partial is None or partial.error_message is not None or error.kind == "aborted" or not error.message:
+ return error
+ return replace(error, partial=replace(partial, error_message=error.message))
+
+
+def _bounded_partial_error(error: ProviderError) -> ProviderError:
+ partial = error.partial
+ if partial is None or partial.error_message is None or len(partial.error_message) <= PARTIAL_ERROR_MESSAGE_CHARS:
+ return error
+ text = partial.error_message[: PARTIAL_ERROR_MESSAGE_CHARS - 1] + "…"
+ return replace(error, partial=replace(partial, error_message=text))
+
+
def partial_message(
content: list[AssistantContent],
*,
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index a2f8bbb9a..71ac633a3 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -145,8 +145,8 @@ sent with that request gets the error result `Tool <name> is not available.`
| `steer_applied` | the steer delivery is accepted into the running Turn |
| `compaction_started`, `compaction_finished`, `compaction_failed` | none: compaction is invisible (C-9 `context.md` §10); a finished one lowers the session's token snapshot |
| `context_exhausted` | the run's stop message, from the error's kind (C-9 `context.md` §8 d): `context_exhausted`, the conversation has grown too long to continue reliably, start a new session with `/new`; `tool_output_too_large`, the latest tool output does not fit even shortened, ask for a smaller part or use a larger model; `input_too_large`, the message does not fit, send a shorter one or use a larger model; `step_too_large`, the latest step (its tool-call arguments or text) is too large, ask for smaller steps or use a larger model. The parts are diagnostic |
-| `run_ended` | `MessageOutput` settles the Turn; `cause` is the error that decided the outcome, from which the adapter takes the failure's kind, text, and Model Hub attribution (a diagnostic is never the cause) |
-| `error` | `notify` / `error` row; the text shown is the adapter's localized copy for the event's `kind` (`vibe/i18n`), and `message` is diagnostic detail, never display copy; `origin` (`source` or `local`, set where the loop raises the error) decides whether Model Hub records the failure against the route (C-9 `context.md` §9) |
+| `run_ended` | `MessageOutput` settles the Turn; `cause` is the error that decided the outcome, from which the adapter takes the failure's kind, text, and Model Hub attribution (a diagnostic is never the cause). A completed run whose foreground job cannot be released ends `error`, and that cleanup error is its cause |
+| `error` | `notify` / `error` row; the text shown is the adapter's localized copy for the event's `kind` (`vibe/i18n`), and `message` is diagnostic detail, never display copy; `origin` (`source` or `local`, set where the loop raises the error) decides whether Model Hub records the failure against the route (C-9 `context.md` §9). A `kind` is one of `NAMED_ERROR_KINDS` (`agent/events.py`: C-2's `ErrorKind`, a failed `StopReason`, and the loop's own `LoopErrorKind`), each with copy of its own, or the class name of an exception the loop did not expect, which reads as an internal error. The adapter logs every failed run once (session, Turn, kind, origin, the hop that served the last response, and the redacted `message`) and records the kind, never the message, on the failure notice row |
## 7. Snapshot and fork
diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.md
index b65439061..9bfa7ce43 100644
--- a/docs/plans/agent-core-contracts/provider.md
+++ b/docs/plans/agent-core-contracts/provider.md
@@ -80,5 +80,9 @@ Error classification is part of the contract because the loop branches on it:
| `aborted` | cancelled by the caller | end the run as aborted |
| `unknown` | anything else | end the run with the error |
+A `ProviderError` whose `partial` is committed (a response that failed after output) carries the error's text as that
+partial's `error_message`, redacted like the error itself and bounded to 1,000 characters, so the transcript row says
+why the response ended. A Stop's partial carries none.
+
The `ai` lane adds a conversion table per protocol (request fields, stream events, stop reasons, usage fields) to this
directory with its first PR; its tests enumerate the tables.
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index 42d8b70c2..feae086e7 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -28,6 +28,7 @@ import os
import secrets
import shutil
import time
+import traceback
from contextlib import asynccontextmanager
from dataclasses import dataclass, field, replace
from pathlib import Path
@@ -128,6 +129,18 @@ def _relative_to(cwd: str) -> Callable[[str], str]:
#: ``Agent.max_tokens`` for every Turn: the resolved hop's budgeted maximum decides the output (``budgeted``).
_NO_OUTPUT_CAP = 1 << 30
+#: A failure's diagnostic in the service log: one redacted line, bounded, never a payload.
+_LOGGED_DIAGNOSTIC_CHARS = 500
+#: The served hop names what the gateway's ``x-avibe-served-hop`` header said, so it is bounded and kept on the line.
+_LOGGED_HOP_CHARS = 200
+
+
+def _loggable(text: str, limit: int = _LOGGED_DIAGNOSTIC_CHARS) -> str:
+ """``text`` as one redacted log field: whitespace collapsed, so it cannot start a line of its own, and bounded."""
+ from core.agent_core.ai.errors import redact_provider_text
+
+ line = " ".join(redact_provider_text(text).split())
+ return line if len(line) <= limit else line[: limit - 1] + "…"
@dataclass
@@ -234,7 +247,7 @@ class VibeyAgent(BaseAgent):
turn_id = str(payload.get("turn_token") or "").strip()
input_id = str(payload.get("delivery_id") or "").strip()
if not session_id or not turn_id or not input_id:
- await self._fail(request, "generic", f"{display_name_for_backend(BACKEND)} turn has no Session, Turn, or input identity.")
+ await self._fail(request, None, f"{display_name_for_backend(BACKEND)} turn has no Session, Turn, or input identity.")
return
turn = _Run(request, session_id, turn_id, self._instance)
async with self._held(session_id, run=turn) as runtime:
@@ -245,9 +258,13 @@ class VibeyAgent(BaseAgent):
# Raised during or after settlement (its emits, or a failure notice): the
# shared owner's fallback releases the runtime gate, so it must see it.
raise
- logger.exception("Vibey turn failed for Session %s", session_id)
turn.settled = True
- await self._fail(request, "generic", f"turn failed: {error}", cause=error)
+ self._log_failure(turn, "error", type(error).__name__, "local", f"turn failed: {error}")
+ # Where it was raised, for debugging only: the WARNING above is the failure's one line.
+ logger.debug(
+ "Vibey turn %s raised in:\n%s", turn_id, "".join(traceback.format_tb(error.__traceback__))
+ )
+ await self._fail(request, type(error).__name__, f"turn failed: {error}", cause=error)
finally:
await self._admit_returned_inputs(turn)
self.store.bind_agent(session_id, None)
@@ -599,6 +616,7 @@ class VibeyAgent(BaseAgent):
cause = run.cause
kind = cause.kind if cause is not None else None
diagnostic = cause.message if cause is not None else run.errors[0].message if run.errors else reason
+ origin = cause.origin if cause is not None else None
source = cause is not None and cause.origin == "source"
final = run.responses.get(run.final_row) if run.final_row else None
if final is not None:
@@ -606,6 +624,8 @@ class VibeyAgent(BaseAgent):
reason = "completed"
run_failed_after_commit = reason not in _COMPLETED
failed = final_outcome(final) == "failed" or run_failed_after_commit
+ if failed:
+ self._log_failure(run, reason, kind, origin, diagnostic)
body = self._display_source(final, final=True)
if failed and not body.strip():
# A silent final whose run failed after the commit: like a final without text
@@ -642,8 +662,27 @@ class VibeyAgent(BaseAgent):
context, "result", "", level="silent", output=terminal_output_for(request)
)
return
+ self._log_failure(run, reason, kind, origin, diagnostic)
await self._fail(request, kind, diagnostic, reason=reason, refusal=run.refusal, source=source)
+ @staticmethod
+ def _log_failure(
+ run: _Run, reason: str, kind: Optional[str], origin: Optional[str], diagnostic: str
+ ) -> None:
+ """One WARNING for a failed run, so a failed Turn can be diagnosed from the log: its kind, who produced it,
+ the hop that served the last response, and the diagnostic, which is never display copy (``errors.py``)."""
+ served = next((message.origin for message in reversed(run.responses.values())), None)
+ logger.warning(
+ "Vibey run failed: session=%s turn=%s reason=%s kind=%s origin=%s served=%s diagnostic=%s",
+ run.session_id,
+ run.turn_id,
+ reason,
+ kind or "-",
+ origin or "-",
+ _loggable(f"{served.provider}/{served.api}/{served.model}", _LOGGED_HOP_CHARS) if served else "-",
+ _loggable(diagnostic or ""),
+ )
+
async def _continuing_input(self, run: _Run) -> Optional[AgentInput]:
"""The input that continues a Turn whose run ended by design with inputs it accepted.
@@ -1153,6 +1192,10 @@ class VibeyAgent(BaseAgent):
"""
if source:
await self.record_model_hub_native_failure(request.context, diagnostic or (kind or "error"))
+ output = terminal_output_for(request)
+ if kind:
+ # The kind, never the diagnostic, so a failed Turn can be diagnosed from its notice row.
+ output = replace(output, metadata={**output.metadata, "error_kind": kind})
await emit_backend_failure(
self.controller,
request.context,
@@ -1160,6 +1203,7 @@ class VibeyAgent(BaseAgent):
diagnostic or (kind or "error"),
display_text=f"❌ {refusal or error_text(kind, self._language(), reason=reason)}",
request=request,
+ output=output,
cause=cause,
)
@@ -1172,7 +1216,7 @@ class VibeyAgent(BaseAgent):
refusal = (
await asyncio.to_thread(hub_supply_refusal, self.controller, BACKEND, language)
or launch_refusal_copy(self.controller, error)
- or error_text("generic", language)
+ or error_text(None, language)
)
# Recorded on every start failure, as the other backends do: a no-op unless a launch is bound.
await self.record_model_hub_native_failure(request.context, str(error))
diff --git a/modules/agents/vibey/errors.py b/modules/agents/vibey/errors.py
index bd64b974c..85dd20a0e 100644
--- a/modules/agents/vibey/errors.py
+++ b/modules/agents/vibey/errors.py
@@ -9,11 +9,13 @@ from __future__ import annotations
from typing import Optional
+from core.agent_core.agent.events import NAMED_ERROR_KINDS
from core.agent_core.ai._common import PROVIDER_SILENCE_TIMEOUT_S
from modules.agents.catalog import display_name_for_backend
from vibe.i18n import t as i18n_t
-# Engine and provider kinds (C-2 error classification, C-3 run outcomes) with their own copy.
+# Every named engine and provider kind (``NAMED_ERROR_KINDS``: C-2 error classification, C-3 run outcomes) has copy
+# of its own; a contract test holds the two sets equal.
_KIND_KEYS: dict[str, str] = {
"refusal": "refusal",
"safety": "safety",
@@ -33,7 +35,14 @@ _KIND_KEYS: dict[str, str] = {
"server": "server",
"auth": "auth",
"invalid_request": "invalidRequest",
+ # A provider failure C-2 could not classify: an unknown code, or an error frame no rule names.
+ "unknown": "unclassified",
"error": "modelError",
+ # The model kept truncating a tool call at its output limit (C-3 section 2).
+ "length": "outputLimit",
+ # Tool calls under a stop reason that cannot carry them.
+ "stop": "providerProtocol",
+ "stream_cleanup": "internal",
# The loop refuses a route that declares no tool support before any request.
"UnsupportedModelRoute": "toolsUnsupported",
# A provider answer the canonical transcript cannot hold.
@@ -47,8 +56,14 @@ _REASON_KEYS: dict[str, str] = {
def error_key(kind: Optional[str], *, reason: Optional[str] = None) -> str:
- """The i18n key for an error kind, falling back to the run reason, then to generic copy."""
- name = _KIND_KEYS.get(kind or "") or _REASON_KEYS.get(reason or "") or "generic"
+ """The i18n key for an error kind, falling back to the run reason, then to generic copy.
+
+ A kind outside ``NAMED_ERROR_KINDS`` names an exception the loop did not expect: an internal error.
+ """
+ name = _KIND_KEYS.get(kind or "")
+ if name is None and kind and kind not in NAMED_ERROR_KINDS:
+ name = "internal"
+ name = name or _REASON_KEYS.get(reason or "") or "generic"
return f"vibeyAgent.error.{name}"
diff --git a/tests/agent_core/agent/test_outcomes.py b/tests/agent_core/agent/test_outcomes.py
index f556997f0..5f5edc2da 100644
--- a/tests/agent_core/agent/test_outcomes.py
+++ b/tests/agent_core/agent/test_outcomes.py
@@ -153,6 +153,9 @@ async def test_primary_outcome_cross_cleanup_keeps_reason_rows_and_event_order(
events = await collect(agent)
assert isinstance(events[-1], RunEnded)
assert events[-1].reason == ("error" if cleanup == "kill" and reason == "completed" else reason)
+ if cleanup == "kill" and reason == "completed":
+ # The leak decided the outcome, so it is the cause ``RunEnded`` names (C-3 section 6).
+ assert (events[-1].cause.kind, events[-1].cause.origin) == ("ForegroundCleanupError", "local")
assert hook_outcomes == [reason]
assert [event.seq for event in events] == list(range(len(events)))
rows = await store.load("session")
diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.py
index 45f6f9713..d4dc56a9c 100644
--- a/tests/agent_core/ai/test_provider_adapters.py
+++ b/tests/agent_core/ai/test_provider_adapters.py
@@ -4479,6 +4479,46 @@ async def test_a_relay_failure_frame_before_output_is_a_retryable_server_failure
assert error.message == message
+# Reasoning streamed, then the response ended in an error frame: the shape Model Hub writes when an upstream stream
+# breaks after output (its code is a copy key, its message localized copy).
+_REASONING_THEN = (
+ 'event: response.output_item.added\ndata: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"reasoning","id":"rs_1","summary":[]}}\n\n'
+ 'event: response.reasoning_summary_text.delta\ndata: {"type":"response.reasoning_summary_text.delta",'
+ '"output_index":0,"delta":"**Checking catalog model metadata**"}\n\n'
+ "event: error\ndata: {}\n\n"
+)
+
+
+ ("message", "kept"),
+ [
+ (
+ "The upstream stream was interrupted. Authorization: Bearer sk-proj-partial0secret0value",
+ "The upstream stream was interrupted. Authorization: Bearer [redacted]",
+ ),
+ ("x" * 5000, "x" * 999 + "\u2026"),
+ ],
+ ids=["redacted", "bounded"],
+)
+async def test_a_failed_response_keeps_its_error_on_the_partial_it_commits(message: str, kept: str) -> None:
+ """C-1 ``error_message``: the committed partial says why the response ended, redacted, then bounded."""
+ frame = json.dumps({"type": "error", "code": "modelHub.errors.stream_interrupted", "message": message})
+ body = _REASONING_THEN.replace("{}", 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 == "unknown"
+ assert error.partial is not None and error.partial.stop_reason == "error"
+ assert error.partial.error_message == kept
+
+
@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.py
index c65c4cb81..fde3029ef 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import asyncio
import json
+import logging
import os
import struct
import time
@@ -32,6 +33,7 @@ from typing import Any, Optional
import pytest
from sqlalchemy import select, update
+from core.agent_core.agent.events import NAMED_ERROR_KINDS
from core.agent_core.agent.recovery import UNRECORDED_EFFECT
from core.agent_core.ai.provider import Done
from core.agent_core.harness.projection import project
@@ -39,6 +41,7 @@ from core.agent_core.messages import (
AssistantMessage,
ImageBlock,
TextBlock,
+ ThinkingBlock,
ToolCallBlock,
ToolResultMessage,
UserMessage,
@@ -1129,13 +1132,25 @@ async def test_a_google_hop_is_called_over_chat_at_the_gateway_prefix(engine, se
assert harness.controller.terminals[-1]["is_error"] is False
[email protected]("kind", sorted({*_KIND_KEYS, "unknown", "context_exhausted"}))
-def test_every_error_kind_has_english_and_chinese_copy(kind: str) -> None:
[email protected]("kind", sorted(NAMED_ERROR_KINDS | set(_KIND_KEYS)))
+def test_every_kind_the_engine_names_has_copy_of_its_own(kind: str) -> None:
+ """Closure: every C-2 ``ErrorKind``, failed ``StopReason`` and loop kind (``NAMED_ERROR_KINDS``) has its own copy,
+ so no failure reads as the bare "run failed" line."""
+ assert kind in _KIND_KEYS
key = error_key(kind)
english, chinese = i18n_t(key, "en"), i18n_t(key, "zh")
+ assert key != "vibeyAgent.error.generic"
assert english != key and chinese != key and english != chinese
+def test_an_unclassified_provider_failure_and_an_unexpected_exception_each_say_what_they_are() -> None:
+ # C-2's ``unknown``: an unrecognized code, or an error frame no rule names (Model Hub's own included).
+ assert error_key("unknown") == "vibeyAgent.error.unclassified"
+ # Any kind outside the named set is the class of an exception the loop did not expect.
+ assert error_key("HookStateError") == "vibeyAgent.error.internal"
+ assert error_key(None, reason="error") == "vibeyAgent.error.generic"
+
+
@pytest.mark.parametrize("language", ["en", "zh"])
async def test_a_failed_run_shows_localized_copy_and_a_refusal_shows_its_explanation_once(
engine, session, tmp_path, published, language
@@ -1186,6 +1201,35 @@ async def test_a_provider_stall_is_not_shown_as_a_connection_failure(
assert stalled_copy != i18n_t("vibeyAgent.error.network", language)
+async def test_a_failed_run_logs_its_kind_and_redacted_diagnostic_and_its_notice_keeps_the_kind(
+ engine, session, tmp_path, published, caplog
+) -> None:
+ """The diagnostic is never display copy, but it is recorded: one WARNING (redacted, one bounded line, no payload),
+ and the failure notice row names the kind, never the text."""
+ from core.agent_core.ai.provider import ProviderError
+
+ secret = "sk-proj-incident0secret0value"
+ partial = AssistantMessage((ThinkingBlock("**Checking catalog model metadata**"),), ORIGIN, "error")
+ failure = ProviderError(
+ "unknown", f"upstream refused\nAuthorization: Bearer {secret}", False, partial=partial
+ )
+ harness = _Harness(engine, tmp_path, "telegram", [[failure]], language="zh")
+ request = harness.request("dispatch it")
+
+ with caplog.at_level(logging.WARNING, logger="modules.agents.vibey.agent"):
+ await harness.agent.handle_message(request)
+
+ [line] = [record.getMessage() for record in caplog.records if record.getMessage().startswith("Vibey run failed")]
+ assert f"session={harness.session_id} turn={_turn(request.context)} " in line
+ assert " reason=error kind=unknown origin=source served=test-provider/anthropic/test-model " in line
+ assert line.endswith("diagnostic=upstream refused Authorization: Bearer [redacted]")
+ assert secret not in caplog.text
+ [notice] = harness.rows("notify")
+ assert json.loads(notice["metadata_json"])["error_kind"] == "unknown"
+ assert secret not in notice["metadata_json"] and "upstream refused" not in notice["metadata_json"]
+ assert harness.controller.im_client.sent == [f"❌ {i18n_t('vibeyAgent.error.unclassified', 'zh', backend='Vibey')}"]
+
+
async def test_a_run_failure_is_reported_to_model_hub_like_the_other_backends(engine, session, tmp_path, published) -> None:
from core.agent_core.ai.provider import ProviderError
@@ -1420,7 +1464,7 @@ async def test_a_refused_model_route_fails_before_the_input_is_written(
# --- settlement and run shape -----------------------------------------------------------
-async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_path, published) -> None:
+async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_path, published, caplog) -> None:
class _LeakyJobs(FakeJobHost):
async def kill(self, job_id, *, reason="killed") -> None:
raise RuntimeError("the job's process group cannot be signalled")
@@ -1438,7 +1482,8 @@ async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_pa
harness = _Harness(engine, tmp_path, "avibe", _tool_turn(), suite=suite)
harness.controller.config.show_duration = True
- await harness.agent.handle_message(harness.request("start it"))
+ with caplog.at_level(logging.WARNING, logger="modules.agents.vibey.agent"):
+ await harness.agent.handle_message(harness.request("start it"))
# The reply committed before cleanup failed, so only settlement knows the run failed: the
# dispatcher writes the failed outcome into that row, as for any failed terminal result.
@@ -1447,6 +1492,90 @@ async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_pa
assert json.loads(result["content_json"])["result_footer"] == "❌ failed"
assert (await harness.context_rows())[-1].row_id == result["id"]
assert harness.controller.terminals[-1]["is_error"] is True
+ # The cleanup failure decided the outcome without being its cause; the log still names it.
+ [line] = [record.getMessage() for record in caplog.records if record.getMessage().startswith("Vibey run failed")]
+ assert " reason=error kind=ForegroundCleanupError origin=local " in line
+
+
+ ("break_turn", "kind", "copy"),
+ [("identity", None, "generic"), ("raise", "RuntimeError", "internal")],
+)
+async def test_a_turn_that_fails_before_settlement_names_its_kind_or_none(
+ engine, session, tmp_path, published, caplog, break_turn, kind, copy
+) -> None:
+ secret = "sk-proj-runtime0secret0value"
+ harness = _Harness(engine, tmp_path, "telegram", [])
+ request = harness.request("hello")
+ if break_turn == "identity":
+ # No Turn identity: a deliberate generic failure, with no kind to record.
+ request.context.platform_specific.pop("turn_token")
+ else:
+
+ async def broken_turn(*_args, **_kwargs):
+ raise RuntimeError(f"the turn's runtime broke: Bearer {secret}")
+
+ harness.agent._run_turn = broken_turn
+
+ with caplog.at_level(logging.WARNING, logger="modules.agents.vibey.agent"):
+ await harness.agent.handle_message(request)
+
+ assert harness.controller.im_client.sent == [f"❌ {i18n_t(f'vibeyAgent.error.{copy}', 'en', backend='Vibey')}"]
+ [notice] = harness.rows("notify")
+ assert json.loads(notice["metadata_json"]).get("error_kind") == kind
+ if break_turn == "raise":
+ # A failure before settlement takes the same structured, redacted line as any failed run, and only that one.
+ warnings = [record for record in caplog.records if record.levelno >= logging.WARNING]
+ [line] = [record.getMessage() for record in warnings if record.name == "modules.agents.vibey.agent"]
+ assert line.startswith("Vibey run failed")
+ assert f"turn={_turn(request.context)} reason=error kind=RuntimeError origin=local served=- " in line
+ assert line.endswith("diagnostic=turn failed: the turn's runtime broke: Bearer [redacted]")
+ assert secret not in caplog.text
+
+
+async def test_the_failure_log_keeps_a_crafted_served_hop_on_its_line(engine, session, tmp_path, published, caplog) -> None:
+ """The served hop is what the gateway's header said: it cannot start a log line of its own or grow unbounded."""
+ from core.agent_core.ai.provider import ProviderError
+ from core.agent_core.messages import Origin
+
+ crafted = Origin("hub\nWARNING forged line", "anthropic", "m" * 5000)
+ partial = AssistantMessage((ThinkingBlock("**Checking**"),), crafted, "error")
+ harness = _Harness(engine, tmp_path, "telegram", [[ProviderError("server", "failed", False, partial=partial)]])
+
+ with caplog.at_level(logging.WARNING, logger="modules.agents.vibey.agent"):
+ await harness.agent.handle_message(harness.request("hello"))
+
+ [record] = [record for record in caplog.records if record.getMessage().startswith("Vibey run failed")]
+ line = record.getMessage()
+ assert "\n" not in line
+ served = line.split(" served=", 1)[1].split(" diagnostic=", 1)[0]
+ assert served.startswith("hub WARNING forged line/anthropic/mmm") and len(served) == 200
+
+
+async def test_a_silent_final_whose_cleanup_fails_shows_the_internal_error(engine, session, tmp_path, published) -> None:
+ """The leak decided the outcome, so it is the cause: never the empty-reply copy for a reply that was silent."""
+
+ class _LeakyJobs(FakeJobHost):
+ async def kill(self, job_id, *, reason="killed") -> None:
+ raise RuntimeError("the job's process group cannot be signalled")
+
+ def tools(tracking, sink):
+ async def start_and_leave(arguments, ctx):
+ await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, call=ctx.call)
+ return ToolResult((text("started"),))
+
+ return [FakeTool("echo", execute=start_and_leave)]
+
+ call = ToolCallBlock(id="call_1", name="echo", arguments={"path": "src"})
+ scripts = [[Done(assistant("Listing.", calls=(call,)))], [Done(assistant("<silent>nothing to add</silent>"))]]
+ suite = ToolSuite(jobs=_LeakyJobs(), create_tools=tools, render_recovered=_unused_renderer, find_job=lambda *a: None)
+ harness = _Harness(engine, tmp_path, "avibe", scripts, suite=suite)
+
+ await harness.agent.handle_message(harness.request("start it"))
+
+ [result] = harness.rows("error")
+ assert result["content_text"] == i18n_t("vibeyAgent.error.internal", "en", backend="Vibey")
+ assert harness.controller.terminals[-1]["is_error"] is True
@pytest.mark.parametrize("platform", ["avibe", "telegram"])
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 3cc882876..a3f565f78 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1571,6 +1571,9 @@
"modelError": "The model stopped with an error.",
"toolsUnsupported": "The selected model does not support tools, which {backend} needs. Choose another model.",
"providerProtocol": "The model provider sent a reply {backend} cannot use.",
+ "unclassified": "The request to the model failed with an error {backend} could not classify. Try again, or choose another model.",
+ "outputLimit": "The model kept running out of output space while writing a tool call. Ask for smaller steps, or choose a model with a larger output limit.",
+ "internal": "{backend} stopped because of an internal error. Try again; if it happens again, the service log names the cause.",
"generic": "{backend}'s run failed."
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 8a4bb3848..9084eb0f0 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1571,6 +1571,9 @@
"modelError": "模型因错误而停止。",
"toolsUnsupported": "所选模型不支持工具,而 {backend} 需要工具。请换一个模型。",
"providerProtocol": "模型服务商返回的回复 {backend} 无法使用。",
+ "unclassified": "请求模型时出现了 {backend} 无法归类的错误。可以重试,或换一个模型。",
+ "outputLimit": "模型在写工具调用时多次超出输出上限。请让它分成更小的步骤,或换用输出上限更大的模型。",
+ "internal": "{backend} 因内部错误而停止。可以重试;如果再次出现,服务日志里记录了原因。",
"generic": "{backend} 运行失败。"
}
}