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): surface upstream error text for request-level failures (#2127)

Call White1c4b160ba129
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 480c1eac1..f4933f580 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -11,7 +11,7 @@ orchestrator and land with every affected consumer on the same tested head.
from __future__ import annotations
import asyncio
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
@@ -141,6 +141,10 @@ class RawCallOutcome:
# Recognized model output or protocol success, independently of permissive
# forwarding. An unrecognized HTTP 200 alone cannot prove Source recovery.
recovery_verified: bool = False
+ # Upstream's own human-readable error text, credential-redacted and bounded
+ # by L1. Display-only: classification never reads it, it is never persisted
+ # into events or provenance, and it stays out of repr so logs cannot echo it.
+ upstream_detail: str | None = field(default=None, repr=False)
class ObservationOutcome(str, Enum):
diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.py
index 9125e2b38..c415d6848 100644
--- a/core/handlers/model_hub/events.py
+++ b/core/handlers/model_hub/events.py
@@ -113,6 +113,31 @@ def redact_credential_material(value: str) -> str:
return redacted
+# Everything after a secret-like label (``token=…``, ``client_secret: "…"``,
+# ``password: `a b c` ``, serialized ``{"api_key": "…"}``) in free text Avibe
+# republishes. The value's extent is
+# deliberately not parsed: quoting, backticks, and escapes vary per upstream, and a
+# parser that misjudges the end leaks the rest of the value, so the remainder of the
+# message is dropped instead. The label needs no word boundary (``client_secret``
+# still matches on ``secret``) and has no nested quantifier, so matching stays linear
+# on hostile input. ``contains_credential_material`` keeps the narrower shape-based
+# patterns so benign labels such as ``max token: 4096`` in a model name are not
+# rejected.
+_LABELED_SECRET_PATTERN = re.compile(
+ r"(?i)(?:token|secret|password|passwd|pwd|key|credential|cookie|session|signature)[\"'`]?\s*[:=]\s*"
+)
+
+
+def redact_untrusted_text(value: str) -> str:
+ """Redact credential shapes, then everything after the first labeled secret."""
+
+ redacted = redact_credential_material(value)
+ match = _LABELED_SECRET_PATTERN.search(redacted)
+ if match is None:
+ return redacted
+ return redacted[: match.end()] + "[redacted]"
+
+
def contains_credential_material(value: object) -> bool:
rendered = json.dumps(value, ensure_ascii=False, sort_keys=True)
return any(pattern.search(rendered) for pattern in _CREDENTIAL_PATTERNS)
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index b6f715d00..78c547ad0 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -165,7 +165,10 @@ TURN_OUTCOME_RENDERING_AUTHORITY: dict[str, TurnOutcomeRenderingRule] = {
"turn.request_nonfallback": TurnOutcomeRenderingRule(
outcome="failed_terminal",
discriminator="request_nonfallback",
- copy_keys=(("default", "modelHub.launch.request_incompatible"),),
+ copy_keys=(
+ ("default", "modelHub.launch.request_incompatible"),
+ ("upstream_detail", "modelHub.launch.request_incompatible_detail"),
+ ),
),
"turn.engine_down": TurnOutcomeRenderingRule(
outcome="failed_terminal",
@@ -215,6 +218,8 @@ class TurnOutcomeProjectionInput:
stream_started: bool = False
next_current_changed: bool = False
source_transition_persisted: bool | None = None
+ # Redacted, bounded upstream error text for this turn's reply only.
+ upstream_detail: str | None = None
class TurnOutcomeProductionError(ValueError):
@@ -251,6 +256,8 @@ def _turn_outcome_variant(
return "next_current"
if projection.stream_started and "stream_started" in copy_keys:
return "stream_started"
+ if projection.upstream_detail and "upstream_detail" in copy_keys:
+ return "upstream_detail"
if (
projection.supply_facts is not None
and projection.supply_facts.supply_state == "waiting"
@@ -274,6 +281,7 @@ def produce_turn_outcome(
attempted_hop: tuple[str, str] | None = None,
stream_started: bool = False,
source_transition_persisted: bool | None = None,
+ upstream_detail: str | None = None,
) -> TurnOutcomeProjectionInput:
"""Produce complete terminal facts from one authoritative matrix row."""
@@ -340,6 +348,11 @@ def produce_turn_outcome(
stream_started=stream_started,
next_current_changed=next_current_changed,
source_transition_persisted=source_transition_persisted,
+ upstream_detail=(
+ upstream_detail
+ if "upstream_detail" in variants and upstream_detail
+ else None
+ ),
)
if _turn_outcome_variant(projection, rule) not in dict(rule.copy_keys):
raise TurnOutcomeProductionError(
@@ -480,6 +493,7 @@ def project_turn_outcome_copy(
"source": facts.source if facts is not None else "",
"retry_at": facts.retry_at if facts is not None else "",
"blockers": facts.blockers if facts is not None else (),
+ "detail": projection.upstream_detail or "",
},
)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 8ae61ccc2..6fb5947dd 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -6876,7 +6876,10 @@ class ModelHubService:
if category == "served":
return produce_turn_outcome("turn.served")
if category == "request_nonfallback":
- return produce_turn_outcome("turn.request_nonfallback")
+ return produce_turn_outcome(
+ "turn.request_nonfallback",
+ upstream_detail=outcome.upstream_detail,
+ )
if category == "upstream_protocol":
# The Gateway's existing protocol-error copy is the positive row;
# a request-incompatible projection would misclassify the failure.
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index f072a76d7..282bf3bb6 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -446,6 +446,8 @@ class ProtocolObservation:
error_type_candidates: tuple[str, ...] = ()
error_code_candidates: tuple[str, ...] = ()
recovery_verified: bool = False
+ # Raw upstream text, for bounded redacted display only; never in reprs.
+ error_message: str | None = field(default=None, repr=False)
@dataclass(frozen=True)
@@ -873,7 +875,9 @@ def _protocol_projection_paths(protocol: str) -> frozenset[JSONPath]:
if envelope.required_error_code_path is not None:
paths.add(envelope.required_error_code_path)
for error_path in _protocol_error_paths(taxonomy):
- paths.update((error_path, (*error_path, "type"), (*error_path, "code")))
+ paths.update(
+ (error_path, (*error_path, "type"), (*error_path, "code"), (*error_path, "message"))
+ )
if taxonomy.sequence_number_path is not None:
paths.add(taxonomy.sequence_number_path)
for container_path in taxonomy.usage.container_paths:
@@ -994,6 +998,7 @@ class ProtocolFactProjector:
return ProtocolObservation(
outcome="failed_terminal" if matched_paths else "served",
error_envelope_paths=matched_paths,
+ error_message=self._error_message(matched_paths),
usage=usage,
error_type_candidates=(type_candidates if matched_paths else ()),
error_code_candidates=(code_candidates if matched_paths else ()),
@@ -1037,6 +1042,7 @@ class ProtocolFactProjector:
),
sequence_number=sequence_number,
usage=usage,
+ error_message=self._error_message(error_paths),
error_type_candidates=(
type_candidates
if envelope.terminal_outcome == "failed_terminal"
@@ -1149,6 +1155,13 @@ class ProtocolFactProjector:
candidates.append(value)
return tuple(candidates)
+ def _error_message(self, error_paths: tuple[ErrorEnvelopePath, ...]) -> str | None:
+ for error_path in error_paths:
+ value = self._scalars.get((*error_path, "message"))
+ if isinstance(value, str) and value.strip():
+ return value
+ return None
+
def _selector_matches(
self,
envelope: ProtocolTerminalEnvelope | ProtocolModelOutputEnvelope,
@@ -1300,6 +1313,7 @@ class ProtocolSSEState:
usage: ProtocolUsageReport | None = None
error_type_candidates: tuple[str, ...] = ()
error_code_candidates: tuple[str, ...] = ()
+ error_message: str | None = field(default=None, repr=False)
def __post_init__(self) -> None:
self.tokenizer = SSEObservationTokenizer(self.protocol)
@@ -1364,6 +1378,8 @@ class ProtocolSSEState:
self.error_type_candidates = observation.error_type_candidates
if observation.error_code_candidates:
self.error_code_candidates = observation.error_code_candidates
+ if observation.error_message is not None:
+ self.error_message = observation.error_message
if observation.sequence_number is not None:
self.last_sequence_number = max(
self.last_sequence_number,
@@ -1389,6 +1405,7 @@ class ProtocolSSEState:
error_type_candidates=self.error_type_candidates,
error_code_candidates=self.error_code_candidates,
recovery_verified=self.reached_model,
+ error_message=self.error_message,
)
return None
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 306e3cc3a..40ddd1a2d 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -35,6 +35,7 @@ from core.message_output import (
HARNESS_TRIGGER_KINDS,
MessageOutput,
communication_type_for_output,
+ neutralize_mentions,
output_for_message,
)
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
@@ -73,19 +74,6 @@ HARNESS_PROMPT_ECHO_TRIGGER_KINDS = HARNESS_TRIGGER_KINDS - {"activity_recovery"
# (``harness_display_prompt``) and stays silent when none can be resolved; the
# Workbench transcript still renders the full prompt for the operator.
HARNESS_PROMPT_ECHO_INSTRUCTION_ONLY_KINDS = frozenset({"watch", "webhook", "hook"})
-# Mention neutralizers for the echoed prompt. The echo repeats text an operator wrote
-# for an agent, into a channel: quoting it does not stop a renderer from resolving a
-# broadcast, a username, or an id mention, and the Discord adapter sends without
-# ``allowed_mentions``, so an echoed ``@everyone`` would really ping the channel
-# (Codex P2). A zero-width space after the sigil keeps the text readable while
-# leaving nothing for any renderer to resolve. Deliberately platform-agnostic: every
-# adapter renders the same body, so ``@`` before a word character covers the
-# Slack/Discord broadcasts AND a bare Telegram ``@username`` (which
-# ``TelegramFormatter.render`` HTML-escapes without defusing), and a new adapter
-# inherits the guard instead of needing its own.
-_HARNESS_ECHO_MENTION_SIGIL_PATTERN = re.compile(r"@(?=\w)")
-_HARNESS_ECHO_ID_MENTION_PATTERN = re.compile(r"<(?=[@!#&])")
-_HARNESS_ECHO_MENTION_BREAK = "\u200b"
# Cap for the definition name in the echo label. The prompt has its own cap, but the
# label is appended after it and task/watch names are never length-validated at
# creation, so an unbounded name could push the body past Discord's 2,000-char or
@@ -101,22 +89,6 @@ _HARNESS_PROMPT_ECHO_I18N_KEYS = {
}
-def _neutralize_mentions(text: str) -> str:
- """Make every mention in *text* inert without changing how it reads.
-
- Used for the Harness prompt echo, which republishes text an operator wrote for an
- agent into a shared channel. Covers every ``@`` sigil — the broadcast words
- (``@everyone`` / ``@here`` / ``@channel``) and a bare ``@username``, which Telegram
- resolves into a real notification — plus the bracketed id forms both Slack
- (``<@U…>``, ``<!here>``, ``<#C…>``) and Discord (``<@id>``, ``<@&role>``) resolve.
- """
-
- neutralized = _HARNESS_ECHO_MENTION_SIGIL_PATTERN.sub(
- "@" + _HARNESS_ECHO_MENTION_BREAK, text or ""
- )
- return _HARNESS_ECHO_ID_MENTION_PATTERN.sub("<" + _HARNESS_ECHO_MENTION_BREAK, neutralized)
-
-
class ActivityOutputDeliveryError(RuntimeError):
"""An Activity result did not complete its local output boundary."""
@@ -2054,7 +2026,7 @@ class ConsolidatedMessageDispatcher:
quoted = "\n".join(f"> {line}" for line in prompt.splitlines())
# Both halves are neutralized: the label carries the definition NAME, which a
# user typed too and can hold a mention just as easily as the prompt.
- return _neutralize_mentions(f"{label}\n{quoted}")
+ return neutralize_mentions(f"{label}\n{quoted}")
def _refresh_runtime_config(self) -> None:
"""Best-effort, mtime-guarded reload of ``controller.config`` from disk.
diff --git a/core/message_output.py b/core/message_output.py
index cf888808b..3e1f1b4a6 100644
--- a/core/message_output.py
+++ b/core/message_output.py
@@ -7,6 +7,7 @@ dispatcher fallback preserves older callers that still use terminal ``result``.
from __future__ import annotations
+import re
from dataclasses import dataclass, field, replace
from typing import Any, Mapping
@@ -121,6 +122,64 @@ class MessageOutput:
return f"agent-output:{backend or 'unknown'}:{lineage}:{key}"
+# Mention neutralizers for text Avibe republishes into a channel on someone else's
+# behalf (a Harness prompt echo, an upstream provider's error message). Quoting does
+# not stop a renderer from resolving a broadcast, a username, or an id mention, and
+# the Discord adapter sends without ``allowed_mentions``, so an echoed ``@everyone``
+# would really ping the channel. A zero-width space after the sigil keeps the text
+# readable while leaving nothing for any renderer to resolve. Deliberately
+# platform-agnostic: every adapter renders the same body, so ``@`` before a word
+# character covers the Slack/Discord broadcasts AND a bare Telegram ``@username``
+# (which ``TelegramFormatter.render`` HTML-escapes without defusing), and a new
+# adapter inherits the guard instead of needing its own.
+# A handle only at a word start, so ``[email protected]`` stays a usable address;
+# a broadcast word anywhere, since a renderer may resolve ``x@everyone`` too.
+_MENTION_SIGIL_PATTERN = re.compile(r"@(?=(?:everyone|here|channel)\b)|(?<![\w.+-])@(?=\w)", re.IGNORECASE)
+_ID_MENTION_PATTERN = re.compile(r"<(?=[@!#&])")
+_MENTION_BREAK = "\u200b"
+
+
+def neutralize_mentions(text: str) -> str:
+ """Make every mention in *text* inert without changing how it reads.
+
+ Covers every ``@`` sigil — the broadcast words (``@everyone`` / ``@here`` /
+ ``@channel``) and a bare ``@username``, which Telegram resolves into a real
+ notification — plus the bracketed id forms both Slack (``<@U…>``, ``<!here>``,
+ ``<#C…>``) and Discord (``<@id>``, ``<@&role>``) resolve.
+ """
+
+ neutralized = _MENTION_SIGIL_PATTERN.sub("@" + _MENTION_BREAK, text or "")
+ return _ID_MENTION_PATTERN.sub("<" + _MENTION_BREAK, neutralized)
+
+
+# Link defusers for text an untrusted party wrote but Avibe republishes under its own
+# copy (an upstream provider's error message). A masked link lets the label dress an
+# attacker-chosen URL as Avibe's own call to action: Markdown ``[label](url)`` on
+# Discord, Telegram (``TelegramFormatter`` renders it to ``<a>``), and the Web UI, and
+# Slack's ``<url|label>``. Parsing destinations is a losing game (balanced parens,
+# escapes, angle-bracket forms), so the syntax itself is broken instead: a zero-width
+# space between ``]`` and ``(`` and after every ``<`` leaves no renderer a link to
+# build, and the text, destination included, still reads exactly as written.
+_MARKDOWN_LINK_JOIN_PATTERN = re.compile(r"\](?=\s*\()")
+# A lone surrogate (``\ud800`` in upstream JSON) survives parsing but cannot be
+# encoded, so the notification would fail to persist; U+FFFD keeps the rest.
+_LONE_SURROGATE_PATTERN = re.compile(r"[\ud800-\udfff]")
+
+
+def plain_untrusted_text(text: str) -> str:
+ """Make untrusted *text* render as the plain words it holds on every platform.
+
+ Mentions are neutralized, masked links defused, and unencodable code points
+ replaced, so the result can be sent and persisted under Avibe's own copy.
+ """
+
+ text = _LONE_SURROGATE_PATTERN.sub("\ufffd", text or "")
+ text = _MARKDOWN_LINK_JOIN_PATTERN.sub("]" + _MENTION_BREAK, text)
+ text = _MENTION_SIGIL_PATTERN.sub("@" + _MENTION_BREAK, text)
+ # Every ``<``, not only the id-mention forms: Slack also builds ``<url|label>``.
+ return text.replace("<", "<" + _MENTION_BREAK)
+
+
def output_for_message(message_type: str, output: MessageOutput | None) -> MessageOutput:
"""Normalize output semantics at the legacy dispatcher boundary.
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 480c1eac1..f4933f580 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -11,7 +11,7 @@ orchestrator and land with every affected consumer on the same tested head.
from __future__ import annotations
import asyncio
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
@@ -141,6 +141,10 @@ class RawCallOutcome:
# Recognized model output or protocol success, independently of permissive
# forwarding. An unrecognized HTTP 200 alone cannot prove Source recovery.
recovery_verified: bool = False
+ # Upstream's own human-readable error text, credential-redacted and bounded
+ # by L1. Display-only: classification never reads it, it is never persisted
+ # into events or provenance, and it stays out of repr so logs cannot echo it.
+ upstream_detail: str | None = field(default=None, repr=False)
class ObservationOutcome(str, Enum):
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index beb5fa07c..05b560fb6 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1259,7 +1259,7 @@ switch, remedy, or message branch absent from it.
| --- | --- | --- | --- | --- |
| `turn.served` | `served` | any, including a transparent fallback | the turn completed; any switch is only a pull-surface record | silent: no Error, warning, info notice, or appended action tail |
| `turn.exhausted` | `exhausted` | final model `supply_state` from the §4.5 taxonomy | fallback walked to the end; no attempt completed | `waiting` renders `models.launch.waiting`; `interrupted` renders `models.launch.interrupted` with the classified blockers |
-| `turn.request_nonfallback` | `failed_terminal` | any non-fallback request-level failure | the attempted Source remains runnable and no switch occurred | `models.launch.request_incompatible`: this request is incompatible; switching Sources will not help |
+| `turn.request_nonfallback` | `failed_terminal` | any non-fallback request-level failure, plus optional `upstream_detail`: the upstream error envelope's `message`, credential-redacted, whitespace-collapsed, and bounded to 400 characters by L1 | the attempted Source remains runnable and no switch occurred | without `upstream_detail`: `models.launch.request_incompatible`: this request is incompatible; switching Sources will not help. With it: `models.launch.request_incompatible_detail`, the same claim followed by the upstream text verbatim so the user can act on the real cause (for example a client-version floor) |
| `turn.engine_down` | `failed_terminal` | local `engine_down` at any request phase, including after an upstream attempt or streamed output | no Source is blamed or mutated; no replay or next-hop walk occurs | `models.errors.engine_down`; after output began it also states that this turn's output may be incomplete |
| `turn.streamed_fallback` | `failed_terminal` | streamed fallback-class Source failure, plus `source_transition_persisted: boolean` recording whether its cooldown or `needs_action` transition was committed | replay is forbidden. When `source_transition_persisted=true`, render `models.launch.retry` only when live inspection of the same effective chain makes a different hop current for the next turn; otherwise no switch exists. When `false`, attempt history remains committed, no switch/current change is claimed, and the existing config-recovery warning owns remediation | persisted with a different current hop: “The next turn has switched Sources; retry.” Persisted with no runnable hop: use the same `waiting`/`interrupted` rendering selected for `exhausted`. Not persisted: `modelHub.errors.stream_interrupted`, with no route-change or new-remedy claim |
| `turn.no_candidate.unconfigured` | `no_candidate` | configured chain is empty | no Source was attempted because no hop is configured | `models.launch.route_unconfigured`, naming the requested model and pointing to Models |
@@ -1272,6 +1272,10 @@ checked mechanically against both `vibe/i18n` locale files. A new outcome, discr
or supply message ships as one new matrix row plus its enum/key/mirror fixtures; none may
land as standalone prose.
+`upstream_detail` is display-only reply text. It is never read by classification,
+never written to resolution events, probes, or persisted provenance, and lives only on
+the in-memory turn projection that renders this turn's reply.
+
`source_transition_persisted` is an optional backend projection fact whose presence is
required only for `turn.streamed_fallback`. UI consumers deliberately do not consume it:
the selected copy key already carries the complete user-visible truth, following the
diff --git a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
index 62b9a3e3d..281927bf7 100644
--- a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
@@ -187,6 +187,8 @@ def _projection_for_copy_variant(
kwargs.update(config=config, resolution=resolution)
elif variant == "transition_unpersisted":
kwargs["source_transition_persisted"] = False
+ elif variant == "upstream_detail":
+ kwargs["upstream_detail"] = "claude-code version too old"
elif variant == "next_current":
menu_model = fixed_model("claude")
supplied = source("src_copynext", [menu_model])
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 120be0252..4a6eb4c63 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -584,6 +584,8 @@ def test_every_turn_outcome_matrix_variant_projects_or_stays_silent(
producer_kwargs["source_transition_persisted"] = True
elif variant == "transition_unpersisted":
producer_kwargs = {"source_transition_persisted": False}
+ elif variant == "upstream_detail":
+ producer_kwargs = {"upstream_detail": "Upstream rejected this request."}
elif variant == "waiting_without_retry":
source = _source("src_matrix_ready", "Recovered source")
config = _config([source])
@@ -620,6 +622,32 @@ def test_every_turn_outcome_matrix_variant_projects_or_stays_silent(
assert (rendered is None) == (expected_key is None)
+def test_request_nonfallback_renders_upstream_detail_verbatim() -> None:
+ detail = "Claude Code 2.1.261 does not support this model; {model} needs 2.1.280."
+ projection = produce_turn_outcome(
+ "turn.request_nonfallback",
+ upstream_detail=detail,
+ )
+
+ assert projection.upstream_detail == detail
+ for language in ("en", "zh"):
+ rendered = render_turn_outcome_copy(projection, language)
+ assert rendered is not None and rendered.endswith(detail)
+ assert render_turn_outcome_copy(
+ produce_turn_outcome("turn.request_nonfallback", upstream_detail=""),
+ "en",
+ ) == i18n_t("modelHub.launch.request_incompatible", "en")
+
+
+def test_upstream_detail_is_ignored_outside_request_nonfallback() -> None:
+ projection = produce_turn_outcome(
+ "turn.engine_down",
+ upstream_detail="engine said something",
+ )
+
+ assert projection.upstream_detail is None
+
+
def test_turn_outcome_producer_rejects_missing_streamed_fallback_facts() -> None:
with pytest.raises(TurnOutcomeProductionError, match="missing"):
produce_turn_outcome("turn.streamed_fallback")
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 9c2c7c5f4..cfc9bdfed 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -650,6 +650,47 @@ def test_machine_permission_denial_precedes_every_status_heuristic(
assert BoundedEventLog(tmp_path / "events.json").list() == []
+def test_request_nonfallback_surfaces_upstream_detail_without_persisting_it(tmp_path):
+ source = _source("src_route031", ("upstream-first",))
+ config = _config([source])
+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "upstream-first"),)
+ )
+ detail = "Claude Code 2.1.261 does not support this model; 2.1.280 is required."
+ adapter = FakeAdapter()
+ adapter.outcomes.append(
+ RawCallOutcome(
+ kind=RawOutcomeKind.HTTP_ERROR,
+ http_status=400,
+ error_code=None,
+ error_type="invalid_request_error",
+ redacted_message="upstream returned HTTP 400",
+ stream_started=False,
+ model_id="upstream-first",
+ source_id=source.id,
+ upstream_detail=detail,
+ )
+ )
+ service, store, _ = _service(tmp_path, config, adapter)
+
+ with pytest.raises(ModelHubError) as exc:
+ asyncio.run(
+ service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
+ )
+
+ assert exc.value.turn_outcome is not None
+ assert exc.value.turn_outcome.upstream_detail == detail
+ copy = project_turn_outcome_copy(exc.value.turn_outcome)
+ assert copy is not None
+ assert copy.key == "modelHub.launch.request_incompatible_detail"
+ assert copy.params["detail"] == detail
+ assert store.load().sources[0].state.status == "standby"
+ persisted = "".join(
+ path.read_text(encoding="utf-8") for path in tmp_path.rglob("*.json")
+ )
+ assert detail not in persisted
+
+
def test_runtime_skips_later_hops_after_a_source_global_failure(tmp_path):
first = _source("src_route022", ("upstream-first", "upstream-second"))
second = _source("src_route023", ("upstream-third",))
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index e6e4b8545..08b7b6810 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -36,8 +36,13 @@ from core.handlers.model_hub.classification import (
classify_outcome,
terminal_outcome_category,
)
+from core.handlers.model_hub.events import redact_untrusted_text
from core.handlers.model_hub.request import ModelHubRequest
-from core.handlers.model_hub.stream_wire import ProtocolUsageReport
+from core.handlers.model_hub.stream_wire import (
+ ProtocolObservation,
+ ProtocolUsageReport,
+ observe_buffered_protocol_response,
+)
from vibe.model_hub_runtime import adapter as runtime_adapter_module
from vibe.model_hub_runtime import client as client_module
from vibe.model_hub_runtime import installer as runtime_installer_module
@@ -6201,6 +6206,195 @@ def test_engine_error_fields_preserve_nested_candidates(
assert decision.reason == "server_error"
+def _detail_source() -> SourceRecord:
+ return SourceRecord(
+ source_id="src_fixture123",
+ vendor="custom",
+ protocol="anthropic",
+ base_url="https://api.example.test",
+ credential_ref="cred_fixture123",
+ allowed_origins=(),
+ model_ids=("model-a",),
+ prefix="source-fixture123",
+ )
+
+
+def test_engine_http_error_carries_redacted_upstream_detail_apart_from_classification() -> None:
+ message = (
+ "Claude Code 2.1.261 does not support this model;\n version 2.1.280 or newer "
+ "is required. key=sk-live_abcdefghijklmnop"
+ )
+ payload = json.dumps(
+ {
+ "type": "error",
+ "error": {
+ "type": "invalid_request_error",
+ "message": message,
+ "details": {"error_code": "claude_code_version_too_old"},
+ },
+ }
+ ).encode()
+
+ outcome = client_module._reduce_protocol_observation(
+ ProtocolObservation(
+ outcome="failed_terminal",
+ error_payload=payload,
+ error_envelope_paths=(("error",),),
+ message="upstream returned HTTP 400",
+ ),
+ source=_detail_source(),
+ model_id="model-a",
+ http_status=400,
+ stream_started=False,
+ )
+
+ assert outcome is not None
+ assert outcome.redacted_message == "upstream returned HTTP 400"
+ assert outcome.upstream_detail == (
+ "Claude Code 2.1.261 does not support this model; version 2.1.280 or newer "
+ "is required. key=[redacted]"
+ )
+ assert "sk-live" not in outcome.upstream_detail
+ assert classify_outcome(outcome).error_code == "upstream_request_invalid"
+
+
+def test_engine_streamed_error_event_carries_upstream_detail() -> None:
+ state = client_module.ProtocolSSEState("anthropic")
+ state.observe(
+ b'event: error\ndata: {"type":"error","error":{"type":"invalid_request_error",'
+ b'"message":"Claude Code 2.1.261 is too old; key=sk-live_abcdefghijklmnop"}}\n\n'
+ )
+
+ observation = state.terminal_observation()
+ assert observation is not None
+ assert "sk-live" not in repr(observation)
+ outcome = client_module._reduce_protocol_observation(
+ observation,
+ source=_detail_source(),
+ model_id="model-a",
+ http_status=200,
+ stream_started=False,
+ )
+
+ assert outcome is not None
+ assert outcome.upstream_detail == "Claude Code 2.1.261 is too old; key=[redacted]"
+
+
+def test_engine_buffered_2xx_error_envelope_carries_upstream_detail() -> None:
+ body = json.dumps(
+ {"type": "error", "error": {"type": "invalid_request_error", "message": "model retired"}}
+ ).encode()
+
+ observation = observe_buffered_protocol_response("anthropic", io.BytesIO(body))
+ outcome = client_module._reduce_protocol_observation(
+ observation,
+ source=_detail_source(),
+ model_id="model-a",
+ http_status=200,
+ stream_started=False,
+ )
+
+ assert observation.outcome == "failed_terminal"
+ assert outcome is not None
+ assert outcome.upstream_detail == "model retired"
+
+
+ "payload",
+ [
+ b"",
+ b"not json",
+ json.dumps({"error": {"type": "invalid_request_error"}}).encode(),
+ json.dumps({"error": {"message": {"nested": "x"}}}).encode(),
+ json.dumps({"error": {"message": " "}}).encode(),
+ json.dumps({"message": "outside the trusted envelope"}).encode(),
+ ],
+)
+def test_engine_upstream_detail_is_absent_without_an_envelope_message(payload: bytes) -> None:
+ assert client_module._upstream_error_detail(payload, (("error",),)) is None
+
+
+def test_engine_upstream_detail_is_bounded_and_keeps_non_ascii_text() -> None:
+ payload = json.dumps({"error": {"message": "模型不可用" * 200}}, ensure_ascii=False).encode()
+
+ detail = client_module._upstream_error_detail(payload, (("error",),))
+
+ assert detail is not None
+ assert len(detail) == client_module._UPSTREAM_DETAIL_CHARS
+ assert detail.startswith("模型不可用") and detail.endswith("…")
+
+
+ ("message", "expected"),
+ [
+ ("refresh failed: token=abc123opaque", "refresh failed: token=[redacted]"),
+ ("bad secret: xyz", "bad secret: [redacted]"),
+ ('client_secret="two words" rejected', "client_secret=[redacted]"),
+ ("session_key=s1, password='p w'", "session_key=[redacted]"),
+ ("password: `correct horse battery staple`", "password: [redacted]"),
+ ('bad token=\\"a\\" b\\" c', "bad token=[redacted]"),
+ ('rejected {"token":"opaquevalue123456789"}', 'rejected {"token":[redacted]'),
+ ("""echo {'password': 'correct horse battery staple'}""", "echo {'password': [redacted]"),
+ ('{"api_key" : "opaque"}', '{"api_key" : [redacted]'),
+ ("max_tokens: 4096 exceeds the limit", "max_tokens: 4096 exceeds the limit"),
+ ],
+)
+def test_engine_upstream_detail_redacts_labeled_opaque_secrets(message: str, expected: str) -> None:
+ assert client_module._bounded_upstream_detail(message) == expected
+
+
+def test_engine_upstream_detail_redaction_stays_linear_on_hostile_labels() -> None:
+ started = time.monotonic()
+ redact_untrusted_text("a-" * 8000 + "x")
+ redact_untrusted_text("key " * 4000 + "x")
+ assert time.monotonic() - started < 0.5
+
+
+def test_engine_upstream_detail_cannot_ping_the_channel_it_is_rendered_into() -> None:
+ detail = client_module._bounded_upstream_detail(
+ "ask @everyone or @ops_lead, <@123> <@&456> <!here> <#C1>"
+ )
+
+ assert detail is not None
+ for mention in ("@everyone", "@ops_lead", "<@123>", "<@&456>", "<!here>", "<#C1>"):
+ assert mention not in detail
+ assert detail.replace("\u200b", "") == "ask @everyone or @ops_lead, <@123> <@&456> <!here> <#C1>"
+
+
+ "message",
+ [
+ "[Update required](https://attacker.example/fix) to continue",
+ "[Update required](https://attacker.example/fix_(now)) to continue",
+ "[Update required] (<https://attacker.example/fix>)",
+ "see <https://attacker.example|the docs>",
+ ],
+)
+def test_engine_upstream_detail_cannot_hide_a_link_behind_trusted_copy(message: str) -> None:
+ detail = client_module._bounded_upstream_detail(message)
+
+ assert detail is not None
+ assert "](" not in detail.replace(" ", "")
+ assert "<h" not in detail
+ # Only zero-width breaks were inserted: the destination still reads as written.
+ assert detail.replace("\u200b", "") == message
+
+
+def test_engine_upstream_detail_keeps_email_addresses_usable() -> None:
+ assert client_module._bounded_upstream_detail("Contact [email protected], cc @ops or x@everyone") == (
+ "Contact [email protected], cc @\u200bops or x@\u200beveryone"
+ )
+
+
+def test_engine_upstream_detail_replaces_lone_surrogates_so_it_can_persist() -> None:
+ payload = b'{"error": {"message": "bad \\ud800 byte"}}'
+
+ detail = client_module._upstream_error_detail(payload, (("error",),))
+
+ assert detail == "bad \ufffd byte"
+ detail.encode("utf-8")
+
+
def test_engine_error_fields_ignore_machine_codes_outside_the_trusted_envelope() -> None:
payload = json.dumps(
{
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 229e422cc..a0d4eedb9 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1035,7 +1035,8 @@
"waiting_without_retry": "This request could not complete. Automatic recovery has ended. You can retry model {model} or choose another model.",
"interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.",
"route_unconfigured": "Model {model} has no configured route. Open Models to configure one.",
- "request_incompatible": "This request is incompatible; switching Sources will not help."
+ "request_incompatible": "This request is incompatible; switching Sources will not help.",
+ "request_incompatible_detail": "This request was rejected upstream and switching Sources will not help. Upstream said: {detail}"
}
},
"remote_access": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 9c0cd4d8d..73912e8af 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1035,7 +1035,8 @@
"waiting_without_retry": "本次请求未完成,自动恢复已结束。你可以重试模型 {model} 或切换模型。",
"interrupted": "模型 {model} 当前不可用:{blockers}。请前往「模型」页处理。",
"route_unconfigured": "模型 {model} 尚未配置路由。请前往「模型」页配置。",
- "request_incompatible": "此请求不兼容;切换模型供应商也无法解决。"
+ "request_incompatible": "此请求不兼容;切换模型供应商也无法解决。",
+ "request_incompatible_detail": "上游拒绝了此请求,切换模型供应商也无法解决。上游返回:{detail}"
}
},
"remote_access": {
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 1ccdbc405..d7e5bcbc9 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -29,12 +29,14 @@ from core.handlers.model_hub.adapter import (
)
from core.handlers.model_hub.async_owner import run_owned_in_thread
from core.handlers.model_hub.classification import UPSTREAM_MACHINE_ERROR_CODES
+from core.handlers.model_hub.events import redact_untrusted_text
from core.handlers.model_hub.json_wire import (
JSONEvent,
JSONPath,
JSONScope,
project_json_reader,
)
+from core.message_output import plain_untrusted_text
from core.handlers.model_hub.stream_wire import (
ErrorEnvelopePath,
ProtocolObservation,
@@ -47,6 +49,8 @@ from vibe.model_hub_runtime.state import SourceRecord
_STREAM_CHUNK_BYTES = 64 * 1024
+# Upper bound on upstream error text shown to the user in a terminal message.
+_UPSTREAM_DETAIL_CHARS = 400
# This threshold only selects memory or a temporary file; it never rejects or
# truncates upstream response bytes.
_PRELUDE_MEMORY_BYTES = 256 * 1024
@@ -1507,6 +1511,14 @@ def _reduce_protocol_observation(
stream_started=stream_started,
usage=observation.usage,
recovery_verified=observation.recovery_verified,
+ upstream_detail=(
+ _bounded_upstream_detail(observation.error_message)
+ if observation.error_message is not None
+ else _upstream_error_detail(
+ observation.error_payload or b"",
+ observation.error_envelope_paths or (("error",),),
+ )
+ ),
)
return _outcome(
kind=RawOutcomeKind.PROTOCOL_ERROR,
@@ -1582,6 +1594,7 @@ def _outcome(
stream_started: bool = False,
usage: ProtocolUsageReport | None = None,
recovery_verified: bool = False,
+ upstream_detail: str | None = None,
) -> RawCallOutcome:
return RawCallOutcome(
kind=kind,
@@ -1595,6 +1608,7 @@ def _outcome(
error_candidates=error_candidates,
usage=usage,
recovery_verified=recovery_verified,
+ upstream_detail=upstream_detail,
)
@@ -1615,6 +1629,45 @@ def _raw_error_fields(
return _project_raw_error_fields(io.BytesIO(payload), envelope_paths)
+def _upstream_error_detail(
+ payload: bytes,
+ envelope_paths: tuple[ErrorEnvelopePath, ...],
+) -> str | None:
+ """Project the first envelope's ``message`` as bounded, redacted display text."""
+
+ message_paths = tuple((*path, "message") for path in envelope_paths)
+ values: dict[JSONPath, str] = {}
+
+ def visit(
+ path: JSONPath,
+ event: JSONEvent,
+ value: object | None,
+ _scope: JSONScope,
+ ) -> None:
+ if event == "replace":
+ values.pop(path, None)
+ elif event == "scalar" and isinstance(value, str):
+ values[path] = value
+
+ if not payload or not project_json_reader(io.BytesIO(payload), message_paths, visit):
+ return None
+ for path in message_paths:
+ text = _bounded_upstream_detail(values.get(path, ""))
+ if text:
+ return text
+ return None
+
+
+def _bounded_upstream_detail(message: str) -> str | None:
+ text = " ".join(message.split())
+ if not text:
+ return None
+ text = plain_untrusted_text(redact_untrusted_text(text))
+ if len(text) > _UPSTREAM_DETAIL_CHARS:
+ text = text[: _UPSTREAM_DETAIL_CHARS - 1].rstrip() + "…"
+ return text
+
+
def _safe_error_code(value: object) -> str | None:
if not isinstance(value, str) or value not in UPSTREAM_MACHINE_ERROR_CODES:
return None