Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(app): surface reply errors to the frontend (#2133)
DavdGaoa5ae309607f7
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.jsonindex 5b586d704..4eeff8a91 100644--- a/examples/web_ui/frontend/package.json+++ b/examples/web_ui/frontend/package.json@@ -11,7 +11,7 @@"preview": "vite preview"},"dependencies": {- "@agentscope-ai/agentscope": "^0.0.13",+ "@agentscope-ai/agentscope": "^0.0.14","@fontsource-variable/geist": "^5.2.8","@tailwindcss/vite": "^4.3.0","class-variance-authority": "^0.7.1",diff --git a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsxindex eb319406b..0b1a3f680 100644--- a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx+++ b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx@@ -1,3 +1,4 @@+import { ReplyFinishedReason } from '@agentscope-ai/agentscope/event';import type {ContentBlock,DataBlock,@@ -17,6 +18,7 @@ import {Copy,Loader2,MessageSquareQuote,+ TriangleAlert,Wrench,} from 'lucide-react';import { useEffect, useRef, useState } from 'react';@@ -28,6 +30,7 @@ import { FileAttachment } from './FileAttachment';import { renderToolCall } from './tool-renderers';import { countDiffStats, DiffStats, getResultDiff } from './tool-renderers/_shared';import type { TFunction, ToolCallWithResult } from './tool-renderers/types';+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import {@@ -629,6 +632,14 @@ export function MessageBubble({ message, onUserConfirm }: MessageBubbleProps) {const showBody = hasBodyContent;const showFooter = !isUser;+ // A fatal error terminated this reply. ``finished_reason`` / ``error`` are+ // reply-level fields set by ``appendEvent`` on a ``REPLY_END`` with+ // ``finished_reason === ReplyFinishedReason.ERROR`` — they are NOT content+ // blocks, so the body above is always genuine agent output. Rendered as a+ // separate alert below the body.+ const errorInfo = message.error;+ const isError = message.finished_reason === ReplyFinishedReason.ERROR || !!errorInfo;+const startMs = new Date(message.created_at).getTime();const endMs = isRunning ? now : new Date(message.finished_at!).getTime();const elapsedSeconds = Math.max(0, (endMs - startMs) / 1000);@@ -661,6 +672,20 @@ export function MessageBubble({ message, onUserConfirm }: MessageBubbleProps) {)}</div>)}+ {isError && (+ <Alert+ variant="destructive"+ className="m-2 w-[calc(100%-1rem)] border-red-200 bg-red-50 text-destructive dark:border-red-900 dark:bg-red-950 dark:text-red-50"+ >+ <TriangleAlert />+ <AlertTitle>{t('messageBubble.error.title')}</AlertTitle>+ <AlertDescription>+ {t(`messageBubble.error.${errorInfo?.type ?? 'unknown'}`, {+ defaultValue: errorInfo?.message ?? t('messageBubble.error.unknown'),+ })}+ </AlertDescription>+ </Alert>+ )}{showFooter && (<div className="flex flex-row items-center text-muted-foreground gap-x-4 px-2 w-full"><Badgediff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 41ca3ce62..4c87e248b 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -107,6 +107,17 @@"tool_output": "Tool Output","team_message": "Team Message","schedule": "Schedule"+ },+ "error": {+ "title": "Reply failed",+ "authentication": "Authentication failed — check the model's API key or credential.",+ "permission": "Request not allowed — the credential lacks permission for this model or endpoint.",+ "rate_limit": "Rate limit or quota exceeded — please try again later.",+ "invalid_request": "The request to the model was rejected as invalid.",+ "upstream": "The upstream model service returned an error.",+ "connection": "Could not reach the model service — network error or timeout.",+ "internal": "An unexpected internal error occurred.",+ "unknown": "The reply failed with an unknown error."}},"chat": {diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 252fa7000..a061f2fa5 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -107,6 +107,17 @@"tool_output": "工具输出","team_message": "团队消息","schedule": "定时任务"+ },+ "error": {+ "title": "回复失败",+ "authentication": "鉴权失败 —— 请检查模型的 API key 或凭证。",+ "permission": "请求被拒绝 —— 当前凭证没有访问该模型或端点的权限。",+ "rate_limit": "触发限流或额度用尽 —— 请稍后重试。",+ "invalid_request": "发往模型的请求被判定为非法。",+ "upstream": "上游模型服务返回了错误。",+ "connection": "无法连接模型服务 —— 网络错误或超时。",+ "internal": "发生了未预期的内部错误。",+ "unknown": "回复因未知错误失败。"}},"chat": {diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yamlindex e70e38356..73c8ae8f0 100644--- a/examples/web_ui/pnpm-lock.yaml+++ b/examples/web_ui/pnpm-lock.yaml@@ -58,8 +58,8 @@ importers:frontend:dependencies:'@agentscope-ai/agentscope':- specifier: ^0.0.13- version: 0.0.13+ specifier: ^0.0.14+ version: 0.0.14'@fontsource-variable/geist':specifier: ^5.2.8version: 5.2.8@@ -159,7 +159,7 @@ importers:devDependencies:'@eslint/js':specifier: ^10.0.1+ version: 10.0.1([email protected]([email protected]))'@tailwindcss/typography':specifier: ^0.5.19version: 0.5.19([email protected])@@ -180,16 +180,16 @@ importers:eslint:specifier: ^10.3.0- version: 10.3.0([email protected])([email protected])+ version: 10.3.0([email protected])eslint-plugin-import-x:specifier: ^4.16.2- version: 4.16.2(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected]))([email protected]([email protected])([email protected]))([email protected])+ version: 4.16.2(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])eslint-plugin-react-hooks:specifier: ^7.1.1+ version: 7.1.1([email protected]([email protected]))eslint-plugin-react-refresh:specifier: ^0.5.2+ version: 0.5.2([email protected]([email protected]))globals:specifier: ^17.6.0version: 17.6.0@@ -198,7 +198,7 @@ importers:version: 6.0.3typescript-eslint:specifier: ^8.59.2- version: 8.59.3([email protected]([email protected])([email protected]))([email protected])([email protected])vite:specifier: ^8.0.12@@ -208,8 +208,8 @@ importers:packages:- '@agentscope-ai/[email protected]':- resolution: {integrity: sha512-SUNKypyVR8ANu6mSiQ0cPaD2GuFzTJmTxj0FqFjjGR+gIy0J44L+46dOxbwfOoZS/2Cl60gMqV33A/K+XPcJVw==}+ '@agentscope-ai/[email protected]':+ resolution: {integrity: sha512-ZS2kv+lC8anT4R8PlL3L5jn2l4RTIqOEkvA3o9xJsR/8/++1Z/GsAFsNzTxbchnywWx/aULAsBN81xtdObCo+w==}'@babel/[email protected]':resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}@@ -4477,7 +4477,7 @@ packages:snapshots:- '@agentscope-ai/[email protected]':+ '@agentscope-ai/[email protected]':dependencies:'@cfworker/json-schema': 4.1.1'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])@@ -4723,11 +4723,6 @@ snapshots:tslib: 2.8.1optional: true- dependencies:- eslint: 10.3.0([email protected])([email protected])- eslint-visitor-keys: 3.4.3-dependencies:eslint: 10.3.0([email protected])@@ -4735,7 +4730,7 @@ snapshots:'@eslint-community/[email protected]': {}- '@eslint/[email protected]([email protected])':+ '@eslint/[email protected]':dependencies:'@eslint/object-schema': 3.0.5debug: 4.4.3([email protected])@@ -4751,9 +4746,9 @@ snapshots:dependencies:'@types/json-schema': 7.0.15optionalDependencies:- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])'@eslint/[email protected]': {}@@ -6110,15 +6105,15 @@ snapshots:'@types/[email protected]': {}- '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])':+ '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@eslint-community/regexpp': 4.12.2- '@typescript-eslint/parser': 8.59.3([email protected]([email protected])([email protected]))([email protected])([email protected])+ '@typescript-eslint/parser': 8.59.3([email protected]([email protected]))([email protected])([email protected])'@typescript-eslint/scope-manager': 8.59.3- '@typescript-eslint/type-utils': 8.59.3([email protected]([email protected])([email protected]))([email protected])([email protected])- '@typescript-eslint/utils': 8.59.3([email protected]([email protected])([email protected]))([email protected])+ '@typescript-eslint/type-utils': 8.59.3([email protected]([email protected]))([email protected])([email protected])'@typescript-eslint/visitor-keys': 8.59.3- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])ignore: 7.0.5natural-compare: 1.4.0ts-api-utils: 2.5.0([email protected])@@ -6126,14 +6121,14 @@ snapshots:transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected])':+ '@typescript-eslint/[email protected]([email protected]([email protected]))([email protected])([email protected])':dependencies:'@typescript-eslint/scope-manager': 8.59.3'@typescript-eslint/types': 8.59.3'@typescript-eslint/typescript-estree': 8.59.3([email protected])'@typescript-eslint/visitor-keys': 8.59.3debug: 4.4.3([email protected])- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])typescript: 6.0.3transitivePeerDependencies:- supports-color@@ -6156,13 +6151,13 @@ snapshots:dependencies:typescript: 6.0.3- '@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected])':+ '@typescript-eslint/[email protected]([email protected]([email protected]))([email protected])([email protected])':dependencies:'@typescript-eslint/types': 8.59.3'@typescript-eslint/typescript-estree': 8.59.3([email protected])- '@typescript-eslint/utils': 8.59.3([email protected]([email protected])([email protected]))([email protected])debug: 4.4.3([email protected])- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])ts-api-utils: 2.5.0([email protected])typescript: 6.0.3transitivePeerDependencies:@@ -6185,13 +6180,13 @@ snapshots:transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])':dependencies:+ '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))'@typescript-eslint/scope-manager': 8.59.3'@typescript-eslint/types': 8.59.3'@typescript-eslint/typescript-estree': 8.59.3([email protected])- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])typescript: 6.0.3transitivePeerDependencies:- supports-color@@ -6691,13 +6686,13 @@ snapshots:optionalDependencies:unrs-resolver: 1.11.1- [email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected]))([email protected]([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:'@package-json/types': 0.0.12'@typescript-eslint/types': 8.59.3comment-parser: 1.4.6debug: 4.4.3([email protected])- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])eslint-import-context: 0.1.9([email protected])is-glob: 4.0.3minimatch: 10.2.5@@ -6705,7 +6700,7 @@ snapshots:stable-hash-x: 0.2.0unrs-resolver: 1.11.1optionalDependencies:- '@typescript-eslint/utils': 8.59.3([email protected]([email protected])([email protected]))([email protected])transitivePeerDependencies:- supports-color@@ -6718,20 +6713,20 @@ snapshots:optionalDependencies:eslint-config-prettier: 10.1.8([email protected]([email protected]))dependencies:'@babel/core': 7.29.0'@babel/parser': 7.29.3- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])hermes-parser: 0.25.1zod: 4.4.3zod-validation-error: 4.0.2([email protected])transitivePeerDependencies:- supports-colordependencies:- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])dependencies:@@ -6748,44 +6743,7 @@ snapshots:dependencies:'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))'@eslint-community/regexpp': 4.12.2- '@eslint/config-array': 0.23.5([email protected])- '@eslint/config-helpers': 0.5.5- '@eslint/core': 1.2.1- '@eslint/plugin-kit': 0.7.1- '@humanfs/node': 0.16.8- '@humanwhocodes/module-importer': 1.0.1- '@humanwhocodes/retry': 0.4.3- '@types/estree': 1.0.9- ajv: 6.15.0- cross-spawn: 7.0.6- debug: 4.4.3([email protected])- escape-string-regexp: 4.0.0- eslint-scope: 9.1.2- eslint-visitor-keys: 5.0.1- espree: 11.2.0- esquery: 1.7.0- esutils: 2.0.3- fast-deep-equal: 3.1.3- file-entry-cache: 8.0.0- find-up: 5.0.0- glob-parent: 6.0.2- ignore: 5.3.2- imurmurhash: 0.1.4- is-glob: 4.0.3- json-stable-stringify-without-jsonify: 1.0.1- minimatch: 10.2.5- natural-compare: 1.4.0- optionator: 0.9.4- optionalDependencies:- jiti: 2.7.0- transitivePeerDependencies:- - supports-color-- dependencies:- '@eslint-community/regexpp': 4.12.2- '@eslint/config-array': 0.23.5([email protected])+ '@eslint/config-array': 0.23.5'@eslint/config-helpers': 0.5.5'@eslint/core': 1.2.1'@eslint/plugin-kit': 0.7.1@@ -8785,13 +8743,13 @@ snapshots:media-typer: 1.1.0mime-types: 3.0.2- [email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]):dependencies:- '@typescript-eslint/eslint-plugin': 8.59.3(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])- '@typescript-eslint/parser': 8.59.3([email protected]([email protected])([email protected]))([email protected])([email protected])+ '@typescript-eslint/eslint-plugin': 8.59.3(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])+ '@typescript-eslint/parser': 8.59.3([email protected]([email protected]))([email protected])([email protected])'@typescript-eslint/typescript-estree': 8.59.3([email protected])- '@typescript-eslint/utils': 8.59.3([email protected]([email protected])([email protected]))([email protected])- eslint: 10.3.0([email protected])([email protected])+ eslint: 10.3.0([email protected])typescript: 6.0.3transitivePeerDependencies:- supports-colordiff --git a/examples/web_ui/pnpm-workspace.yaml b/examples/web_ui/pnpm-workspace.yamlindex a117085b3..c81ec1162 100644--- a/examples/web_ui/pnpm-workspace.yaml+++ b/examples/web_ui/pnpm-workspace.yaml@@ -9,3 +9,8 @@ allowBuilds:ignoredBuiltDependencies:- msw++# Exempt our own first-party package from pnpm's minimumReleaseAge+# supply-chain gate, so freshly published versions install immediately.+minimumReleaseAgeExclude:+ - '@agentscope-ai/agentscope'diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex 555a1276a..d85ce1c91 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -52,7 +52,7 @@ from ..event import (DataBlockDeltaEvent,DataBlockEndEvent,ExceedMaxItersEvent,- ReplyEndReason,+ ReplyFinishedReason,UserInterruptEvent,)from ..exception import AgentOrientedException@@ -715,7 +715,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.INTERRUPTED,+ finished_reason=ReplyFinishedReason.INTERRUPTED,)return@@ -775,7 +775,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.COMPLETED,+ finished_reason=ReplyFinishedReason.COMPLETED,)yield evtreturn@@ -792,7 +792,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.INTERRUPTED,+ finished_reason=ReplyFinishedReason.INTERRUPTED,)return@@ -846,7 +846,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.INTERRUPTED,+ finished_reason=ReplyFinishedReason.INTERRUPTED,)return@@ -883,7 +883,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.EXCEED_MAX_ITERS,+ finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,)yield AssistantMsg(@@ -899,7 +899,7 @@ class Agent:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyEndReason.INTERRUPTED,+ finished_reason=ReplyFinishedReason.INTERRUPTED,)if self.react_config.interruption_raise_cancelled_error:@@ -907,7 +907,10 @@ class Agent:finally:if end_event is not None:- if end_event.finished_reason == ReplyEndReason.INTERRUPTED:+ if (+ end_event.finished_reason+ == ReplyFinishedReason.INTERRUPTED+ ):# Handle the context when interruptionasync for _ in self._close_unfinished_tool_calls():yield _diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 655c9aecb..7935973d3 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -46,10 +46,13 @@ from ...agent import Agent, ModelConfigfrom ...event import (AgentEvent,ReplyStartEvent,+ ReplyEndEvent,+ ReplyFinishedReason,UserConfirmResultEvent,ExternalExecutionResultEvent,UserInterruptEvent,)+from ._errors import _classify_errorfrom ...message import AssistantMsg, Msg, ToolCallStatefrom ...permission import AdditionalWorkingDirectory@@ -635,6 +638,33 @@ class ChatService:if current is not None:current.cancel()+ except Exception as e: # pylint: disable=broad-except+ # The reply stream died before emitting its terminating+ # ReplyEndEvent. Synthesize one so the reply is closed on+ # both channels (publish → live SSE stops loading;+ # append_event → persisted reply gets finished_at/reason/+ # error for refresh), then re-raise for logging + the+ # finally-persist. CancelledError is a BaseException, so+ # interrupts are unaffected; reply_msg is None only when we+ # failed before REPLY_START (nothing to close). The+ # finished_reason guard skips the case where the agent+ # already closed the reply and the failure is downstream+ # (publish/projection) — don't overwrite a completed reply.+ if reply_msg is not None and reply_msg.finished_reason is None:+ end_event = ReplyEndEvent(+ session_id=session_id,+ reply_id=reply_msg.id,+ finished_reason=ReplyFinishedReason.ERROR,+ error=_classify_error(e),+ )+ reply_msg.append_event(end_event)+ await publish_session_event(+ self._message_bus,+ session_id,+ end_event.model_dump(mode="json"),+ )+ raise+finally:# All persistence in a single coroutine, shielded from# outer cancellation. Must complete BEFORE the sessiondiff --git a/src/agentscope/app/_service/_errors.py b/src/agentscope/app/_service/_errors.pynew file mode 100644index 000000000..850be8f3b--- /dev/null+++ b/src/agentscope/app/_service/_errors.py@@ -0,0 +1,136 @@+# -*- coding: utf-8 -*-+"""Classify a fatal reply exception into a UI-facing :class:`ErrorInfo`.++Provider-agnostic: classification keys off HTTP status codes and exception+class names, walking the ``__cause__`` / ``__context__`` chain (AgentScope+often wraps a provider error one layer deep). No provider SDK is imported;+matching is by class name so httpx / openai / anthropic / aiohttp are all+covered whether or not they are installed."""+from typing import Iterator++from ...exception import DeveloperOrientedException+from ...types import ErrorType, ErrorInfo+++_STATUS_MAP: dict[int, ErrorType] = {+ 401: ErrorType.AUTHENTICATION,+ 403: ErrorType.PERMISSION,+ 429: ErrorType.RATE_LIMIT,+ 400: ErrorType.INVALID_REQUEST,+ 404: ErrorType.INVALID_REQUEST,+ 422: ErrorType.INVALID_REQUEST,+}++# Connection/timeout failures identified by MRO class name, so we catch+# httpx.TransportError subclasses and provider connection wrappers without+# importing (and thus requiring) those packages.+_NETWORK_EXC_NAMES: frozenset[str] = frozenset(+ {+ "TransportError", # httpx base for Connect/Read/Write/Pool errors+ "APIConnectionError", # openai / anthropic+ "APITimeoutError", # openai / anthropic+ "ClientConnectionError", # aiohttp+ "ClientConnectorError", # aiohttp+ },+)++_GENERIC_MESSAGE: dict[ErrorType, str] = {+ ErrorType.AUTHENTICATION: (+ "Authentication failed — check the model's API key / credential."+ ),+ ErrorType.PERMISSION: (+ "Request not allowed — the credential lacks permission for this "+ "model or endpoint."+ ),+ ErrorType.RATE_LIMIT: "Rate limit or quota exceeded — try again later.",+ ErrorType.INVALID_REQUEST: (+ "The request to the model was rejected as invalid."+ ),+ ErrorType.UPSTREAM: "The upstream model service returned an error.",+ ErrorType.CONNECTION: (+ "Could not reach the model service — network error or timeout."+ ),+ ErrorType.INTERNAL: "An unexpected internal error occurred.",+ ErrorType.UNKNOWN: "The reply failed with an unknown error.",+}+++def _causes(e: BaseException) -> Iterator[BaseException]:+ """Yield ``e`` then its ``__cause__`` / ``__context__`` chain, guarding+ against cycles."""+ seen: set[int] = set()+ exc: BaseException | None = e+ while exc is not None and id(exc) not in seen:+ seen.add(id(exc))+ yield exc+ exc = exc.__cause__ or exc.__context__+++def _extract_status(e: BaseException) -> int | None:+ """Pull an HTTP status code from anywhere in the exception chain.++ Different clients expose it differently: openai/anthropic promote+ ``status_code`` onto the exception, aiohttp uses ``status``, and raw+ httpx keeps it on ``response.status_code``.+ """+ for exc in _causes(e):+ for src in (+ getattr(exc, "status_code", None),+ getattr(exc, "status", None),+ getattr(getattr(exc, "response", None), "status_code", None),+ ):+ if isinstance(src, int):+ return src+ return None+++def _is_network_error(e: BaseException) -> bool:+ """Detect a connection/timeout failure anywhere in the chain, by+ builtin type or by provider class name."""+ for exc in _causes(e):+ if isinstance(exc, (TimeoutError, ConnectionError)):+ return True+ if any(c.__name__ in _NETWORK_EXC_NAMES for c in type(exc).__mro__):+ return True+ return False+++def _classify_type(e: Exception) -> ErrorType:+ """Map an exception to an :class:`ErrorType` without importing any+ provider SDK."""+ status = _extract_status(e)+ if status is not None:+ if status in _STATUS_MAP:+ return _STATUS_MAP[status]+ if status >= 500:+ return ErrorType.UPSTREAM+ return ErrorType.INVALID_REQUEST++ if _is_network_error(e):+ return ErrorType.CONNECTION+ if isinstance(e, DeveloperOrientedException):+ return ErrorType.INTERNAL+ return ErrorType.UNKNOWN+++def _classify_error(e: Exception) -> ErrorInfo:+ """Classify a fatal reply exception into a structured+ :class:`ErrorInfo` for the frontend.++ The ``message`` is a generic per-type string (not the raw exception+ text) so no provider-internal details or credentials leak to the UI;+ the frontend localizes off the stable ``type`` key.++ Args:+ e (`Exception`):+ The exception that terminated the reply.++ Returns:+ `ErrorInfo`:+ The structured, UI-facing error description.+ """+ error_type = _classify_type(e)+ return ErrorInfo(+ type=error_type,+ message=_GENERIC_MESSAGE[error_type],+ )diff --git a/src/agentscope/event/__init__.py b/src/agentscope/event/__init__.pyindex a7b0b55ac..51632a731 100644--- a/src/agentscope/event/__init__.py+++ b/src/agentscope/event/__init__.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The event module of agentscope."""+from ..types import ReplyFinishedReasonfrom ._event import (EventType,EventBase,@@ -42,6 +43,7 @@ __all__ = ["EventType","EventBase","ReplyStartEvent",+ "ReplyFinishedReason","ReplyEndReason","ReplyEndEvent","ModelCallStartEvent",diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.pyindex 2104b69e3..68ee5e189 100644--- a/src/agentscope/event/_event.py+++ b/src/agentscope/event/_event.py@@ -5,6 +5,7 @@ from enum import StrEnumfrom typing import Any, Dict, Literal, List, TypeAliasfrom pydantic import BaseModel, Field, ConfigDict+from typing_extensions import deprecatedfrom .._utils._common import _generate_idfrom ..message import (@@ -14,6 +15,10 @@ from ..message import (ToolResultBlock,ToolResultState,)+from ..types import (+ ReplyFinishedReason,+ ErrorInfo,+)from ..model import FinishedReasonfrom ..permission import PermissionRule@@ -90,8 +95,14 @@ class ReplyStartEvent(EventBase):"""Role of the agent."""+@deprecated(+ "ReplyEndReason is deprecated and will be removed; "+ "use agentscope.types.ReplyFinishedReason instead.",+)class ReplyEndReason(StrEnum):- """The reason for reply ended."""+ """Deprecated alias of :class:`~agentscope.types.ReplyFinishedReason`,+ kept for backward compatibility. Value-compatible (both ``StrEnum``),+ so existing code that constructs or compares against it keeps working."""COMPLETED = "completed"INTERRUPTED = "interrupted"@@ -107,8 +118,11 @@ class ReplyEndEvent(EventBase):"""ID of the session this reply belongs to."""reply_id: str"""ID of the reply message produced by this reply."""- finished_reason: ReplyEndReason = ReplyEndReason.COMPLETED+ finished_reason: ReplyFinishedReason = ReplyFinishedReason.COMPLETED"""The finished reason of this reply."""+ error: ErrorInfo | None = None+ """Structured error info, populated only when+ ``finished_reason == ReplyFinishedReason.ERROR``."""class ModelCallStartEvent(EventBase):diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.pyindex 241fb09cc..543842bed 100644--- a/src/agentscope/message/_base.py+++ b/src/agentscope/message/_base.py@@ -21,6 +21,7 @@ from ._block import (ContentBlock,ContentBlockTypes,)+from ..types import ReplyFinishedReason, ErrorInfofrom .._logging import loggerif TYPE_CHECKING:@@ -81,6 +82,12 @@ class Msg(BaseModel):"""The creation time of the message"""finished_at: str | None = Field(default=None)"""The finished time of the message"""+ finished_reason: ReplyFinishedReason | None = Field(default=None)+ """Terminal reason of this reply (error / interrupted /+ exceed_max_iters). ``None`` until a ``REPLY_END`` event is applied."""+ error: ErrorInfo | None = Field(default=None)+ """Structured error info, populated only when+ ``finished_reason == ReplyFinishedReason.ERROR``."""usage: Usage | None = Field(default=None)"""The token usage information of the message"""@@ -238,6 +245,13 @@ class Msg(BaseModel):match event.type:case EventType.REPLY_END:self.finished_at = event.created_at+ # ``event.finished_reason`` is a bare string (EventBase sets+ # ``use_enum_values``); coerce back to the enum so this+ # field serializes cleanly.+ self.finished_reason = ReplyFinishedReason(+ event.finished_reason,+ )+ self.error = event.errorcase EventType.MODEL_CALL_END:if self.usage is None:diff --git a/src/agentscope/types/__init__.py b/src/agentscope/types/__init__.pyindex 03ff21f23..db1ab4091 100644--- a/src/agentscope/types/__init__.py+++ b/src/agentscope/types/__init__.py@@ -10,6 +10,11 @@ from ._json import (JSONPrimitive,JSONSerializableObject,)+from ._reply import (+ ReplyFinishedReason,+ ErrorType,+ ErrorInfo,+)__all__ = ["AgentHookTypes",@@ -17,4 +22,7 @@ __all__ = ["Embedding","JSONPrimitive","JSONSerializableObject",+ "ReplyFinishedReason",+ "ErrorType",+ "ErrorInfo",]diff --git a/src/agentscope/types/_reply.py b/src/agentscope/types/_reply.pynew file mode 100644index 000000000..e9e12e396--- /dev/null+++ b/src/agentscope/types/_reply.py@@ -0,0 +1,49 @@+# -*- coding: utf-8 -*-+"""Reply-termination vocabulary shared by the ``message`` and ``event``+modules. Lives in ``types`` (a leaf) so both can depend on it downward+without an import cycle."""+from enum import StrEnum++from pydantic import BaseModel+++class ReplyFinishedReason(StrEnum):+ """The reason a reply finished."""++ COMPLETED = "completed"+ INTERRUPTED = "interrupted"+ EXCEED_MAX_ITERS = "exceed_max_iters"+ ERROR = "error"+++class ErrorType(StrEnum):+ """Classification of a fatal error that terminated a reply.++ Not model-specific: the status-derived members apply to any upstream+ service reached during a reply (chat model, embedding, TTS, MCP)."""++ AUTHENTICATION = "authentication"+ """401 — credential missing or wrong."""+ PERMISSION = "permission"+ """403 — authenticated but not allowed."""+ RATE_LIMIT = "rate_limit"+ """429 — rate/quota exceeded."""+ INVALID_REQUEST = "invalid_request"+ """400 / 422 — malformed request."""+ UPSTREAM = "upstream"+ """5xx — an upstream service failed."""+ CONNECTION = "connection"+ """Network error / timeout — no HTTP status available."""+ INTERNAL = "internal"+ """Framework bug or otherwise unexpected exception."""+ UNKNOWN = "unknown"+ """Fallback when no better classification is possible."""+++class ErrorInfo(BaseModel):+ """Structured, UI-facing description of a fatal reply error."""++ type: ErrorType = ErrorType.UNKNOWN+ """Stable classification key; the frontend localizes off it."""+ message: str+ """Short, sanitized, human-readable description."""diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex c7bf5a56a..1bfe26c94 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -127,6 +127,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"metadata": {},"name": "Friday","role": "assistant",@@ -249,6 +251,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -275,6 +278,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -307,6 +312,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"id": AnyString(),"metadata": {},"usage": None,@@ -328,6 +335,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"metadata": {},"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -355,6 +364,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"metadata": {},"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -433,6 +444,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -460,6 +472,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"metadata": {},"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -502,6 +516,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"id": AnyString(),"metadata": {},"usage": None,@@ -523,6 +539,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"metadata": {},"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -550,6 +568,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"metadata": {},"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{**msg_base,@@ -595,6 +615,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"metadata": {},"name": "Friday","role": "assistant",@@ -826,6 +848,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -851,6 +874,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1057,6 +1082,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1103,6 +1129,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1330,6 +1358,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1388,6 +1417,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [diff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.pyindex e44f41e9a..3fae79148 100644--- a/tests/agent_interrupt_test.py+++ b/tests/agent_interrupt_test.py@@ -152,6 +152,8 @@ def _msg_base(name: str = "Friday") -> dict[str, Any]:"id": AnyString(),"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"metadata": {},"name": name,"role": "assistant",@@ -164,6 +166,8 @@ def _user_msg_dict(content: str) -> dict[str, Any]:"id": AnyString(),"created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"metadata": {},"name": "user","role": "user",@@ -262,6 +266,7 @@ def _assert_interrupted_end("created_at": AnyString(),"metadata": {},"type": "REPLY_END",+ "error": None,"session_id": session_id,"reply_id": reply_id,"finished_reason": "interrupted",diff --git a/tests/agui_protocol_test.py b/tests/agui_protocol_test.pyindex d07fb6cb8..f706c8972 100644--- a/tests/agui_protocol_test.py+++ b/tests/agui_protocol_test.py@@ -40,7 +40,7 @@ from agentscope.event import (ToolResultStartEvent,ToolResultTextDeltaEvent,UserConfirmResultEvent,- ReplyEndReason,+ ReplyFinishedReason,)from agentscope.message import ToolCallBlock, ToolResultBlock, ToolResultStatefrom agentscope.model import FinishedReason@@ -214,7 +214,7 @@ class AGUIProtocolLifecycleTest(IsolatedAsyncioTestCase):event = ReplyEndEvent(session_id="sess_1",reply_id="reply_1",- finished_reason=ReplyEndReason.COMPLETED,+ finished_reason=ReplyFinishedReason.COMPLETED,)result = self.mw._convert_to_protocol(event)@@ -676,7 +676,7 @@ class AGUIProtocolCamelCaseTest(IsolatedAsyncioTestCase):ReplyEndEvent(session_id="s",reply_id="r",- finished_reason=ReplyEndReason.COMPLETED,+ finished_reason=ReplyFinishedReason.COMPLETED,),ModelCallStartEvent(reply_id="r", model_name="m"),ModelCallEndEvent(diff --git a/tests/compress_context_test.py b/tests/compress_context_test.pyindex 49e0abc1f..7e30b0ba4 100644--- a/tests/compress_context_test.py+++ b/tests/compress_context_test.py@@ -226,6 +226,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "1","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -242,6 +244,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -263,6 +267,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -279,6 +285,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -325,6 +333,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "1","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -341,6 +351,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -367,6 +379,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -412,6 +426,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "1","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -428,6 +444,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -449,6 +467,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -465,6 +485,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -510,6 +532,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "1","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -531,6 +555,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -552,6 +578,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -600,6 +628,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -621,6 +651,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -706,6 +738,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "old-user","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -722,6 +756,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "multi-tool-msg","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -782,6 +818,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "multi-tool-msg","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -798,6 +836,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "latest-user","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [@@ -887,6 +927,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "2","created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"name": "Friday","role": "assistant","content": [@@ -903,6 +945,8 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"id": "3","created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"name": "User","role": "user","content": [diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.pyindex 08c06f60d..4799d2af9 100644--- a/tests/event_to_message_test.py+++ b/tests/event_to_message_test.py@@ -35,7 +35,7 @@ from agentscope.event import (ExternalExecutionResultEvent,ModelCallEndEvent,ReplyEndEvent,- ReplyEndReason,+ ReplyFinishedReason,RequireExternalExecutionEvent,RequireUserConfirmEvent,TextBlockDeltaEvent,@@ -161,6 +161,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):def _base(content: list,finished_at: str | None = None,+ finished_reason: str | None = None,usage: dict | None = None,) -> dict:"""Return the expected model_dump() of self.msg."""@@ -171,6 +172,8 @@ class EventToMessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": _created_at,"finished_at": finished_at,+ "finished_reason": finished_reason,+ "error": None,"content": content,"usage": usage,}@@ -720,11 +723,12 @@ class EventToMessageTest(IsolatedAsyncioTestCase):reply_id=_REPLY_ID,session_id=_SESSION_ID,created_at=_FIXED_END_TS,- finished_reason=ReplyEndReason.COMPLETED,+ finished_reason=ReplyFinishedReason.COMPLETED,)gt_reply_end = _base(_final_content,finished_at=_FIXED_END_TS,+ finished_reason="completed",usage={"input_tokens": 15, "output_tokens": 28},)diff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.pyindex f59454efd..770f43d4f 100644--- a/tests/hitl_external_execution_test.py+++ b/tests/hitl_external_execution_test.py@@ -181,6 +181,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"metadata": {},"name": "Friday","role": "assistant",@@ -365,6 +367,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -414,6 +418,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -436,6 +441,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -599,6 +606,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -696,6 +705,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -719,6 +729,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -910,6 +922,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -999,6 +1013,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1022,6 +1037,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1207,6 +1224,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1273,6 +1292,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1294,6 +1314,8 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.pyindex 35cea9aea..ac35b1d84 100644--- a/tests/hitl_user_confirmation_test.py+++ b/tests/hitl_user_confirmation_test.py@@ -274,6 +274,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"metadata": {},"name": "Friday","role": "assistant",@@ -397,6 +399,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -452,6 +456,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -475,6 +480,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -661,6 +668,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -777,6 +786,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -799,6 +809,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1022,6 +1034,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1124,6 +1138,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1146,6 +1161,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1480,6 +1497,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):},],"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,},{"content": [@@ -1569,6 +1588,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):*self.final_text_events,{"type": "REPLY_END",+ "error": None,"session_id": session_id,"finished_reason": "completed",},@@ -1585,6 +1605,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"metadata": {},"name": "user","role": "user",diff --git a/tests/message_test.py b/tests/message_test.pyindex 4ec2ee13d..d9b7f245f 100644--- a/tests/message_test.py+++ b/tests/message_test.py@@ -42,6 +42,8 @@ class MessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -64,6 +66,8 @@ class MessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -120,6 +124,8 @@ class MessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": AnyString(),+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -145,6 +151,8 @@ class MessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -171,6 +179,8 @@ class MessageTest(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,},)diff --git a/tests/service_classify_error_test.py b/tests/service_classify_error_test.pynew file mode 100644index 000000000..a675698db--- /dev/null+++ b/tests/service_classify_error_test.py@@ -0,0 +1,154 @@+# -*- coding: utf-8 -*-+"""Unit tests for :func:`_classify_error` — the fatal-reply exception+classifier that feeds the UI ``ErrorInfo``.++These lock down the behaviour that regressed silently before: status codes+live in different places across clients (``status_code`` on the exception+for openai/anthropic, ``response.status_code`` for raw httpx, ``status``+for aiohttp), connection failures are provider ``TransportError`` subclasses+rather than builtin ``ConnectionError``, and the real error is often one+``__cause__`` deep.+"""+import unittest++import httpx++from agentscope.app._service._errors import (+ _classify_error,+ _classify_type,+ _GENERIC_MESSAGE,+)+from agentscope.exception import DeveloperOrientedException+from agentscope.types import ErrorType+++class _StatusError(Exception):+ """openai/anthropic ``APIStatusError`` shape: status promoted onto the+ exception object."""++ def __init__(self, status_code: int) -> None:+ super().__init__(f"status {status_code}")+ self.status_code = status_code+++class _AiohttpError(Exception):+ """aiohttp ``ClientResponseError`` shape: uses ``status``, not+ ``status_code``."""++ def __init__(self, status: int) -> None:+ super().__init__(f"status {status}")+ self.status = status+++def _httpx_status_error(code: int) -> httpx.HTTPStatusError:+ """A real httpx error, whose code lives on ``response`` — the exact+ shape that used to fall through to INTERNAL."""+ request = httpx.Request("POST", "https://api.example.com/v1/chat")+ response = httpx.Response(code, request=request)+ return httpx.HTTPStatusError("boom", request=request, response=response)+++class ClassifyErrorTest(unittest.TestCase):+ """Tests for the reply-error classifier."""++ def test_status_code_mapping(self) -> None:+ """HTTP status maps to the right ErrorType from every source+ (exception ``status_code``, httpx ``response``, aiohttp+ ``status``)."""+ cases = [+ (401, ErrorType.AUTHENTICATION),+ (403, ErrorType.PERMISSION),+ (429, ErrorType.RATE_LIMIT),+ (400, ErrorType.INVALID_REQUEST),+ (404, ErrorType.INVALID_REQUEST),+ (422, ErrorType.INVALID_REQUEST),+ (418, ErrorType.INVALID_REQUEST), # unmapped 4xx+ (500, ErrorType.UPSTREAM),+ (503, ErrorType.UPSTREAM),+ ]+ for code, expected in cases:+ with self.subTest(source="status_code", code=code):+ self.assertEqual(_classify_type(_StatusError(code)), expected)+ with self.subTest(source="httpx.response", code=code):+ self.assertEqual(+ _classify_type(_httpx_status_error(code)),+ expected,+ )+ with self.subTest(source="aiohttp.status", code=code):+ self.assertEqual(+ _classify_type(_AiohttpError(code)),+ expected,+ )++ def test_httpx_connection_errors(self) -> None:+ """httpx transport failures classify as CONNECTION."""+ # These are httpx.TransportError subclasses, NOT builtin+ # ConnectionError/TimeoutError — the branch that used to be dead.+ for exc in (+ httpx.ConnectError("refused"),+ httpx.ConnectTimeout("slow"),+ httpx.ReadTimeout("slow"),+ httpx.PoolTimeout("slow"),+ ):+ with self.subTest(exc=type(exc).__name__):+ self.assertEqual(_classify_type(exc), ErrorType.CONNECTION)++ def test_builtin_network_errors(self) -> None:+ """Builtin TimeoutError / ConnectionError classify as CONNECTION."""+ self.assertEqual(_classify_type(TimeoutError()), ErrorType.CONNECTION)+ self.assertEqual(+ _classify_type(ConnectionError()),+ ErrorType.CONNECTION,+ )++ def test_cause_chain_is_walked(self) -> None:+ """Status is found on an explicitly chained ``__cause__``."""+ # AgentScope often wraps a provider error one layer deep.+ try:+ try:+ raise _StatusError(401)+ except _StatusError as inner:+ raise RuntimeError("wrapped") from inner+ except RuntimeError as outer:+ self.assertEqual(+ _classify_type(outer),+ ErrorType.AUTHENTICATION,+ )++ def test_context_chain_is_walked(self) -> None:+ # pylint: disable=raise-missing-from+ """Status is found on an implicitly chained ``__context__``."""+ # Intentional implicit chaining (no ``from``) populates __context__.+ try:+ try:+ raise httpx.ConnectError("refused")+ except httpx.ConnectError:+ raise RuntimeError("wrapped") # noqa: B904+ except RuntimeError as outer:+ self.assertEqual(_classify_type(outer), ErrorType.CONNECTION)++ def test_framework_vs_unknown(self) -> None:+ """Framework errors are INTERNAL; anything else is UNKNOWN."""+ self.assertEqual(+ _classify_type(DeveloperOrientedException("x")),+ ErrorType.INTERNAL,+ )+ self.assertEqual(_classify_type(ValueError("x")), ErrorType.UNKNOWN)++ def test_classify_error_returns_generic_message(self) -> None:+ """The ErrorInfo carries the generic per-type message, never the+ raw exception text."""+ info = _classify_error(_StatusError(403))+ self.assertEqual(info.type, ErrorType.PERMISSION)+ self.assertEqual(info.message, _GENERIC_MESSAGE[ErrorType.PERMISSION])+ # Never leak the raw exception text to the UI.+ self.assertNotIn("status 403", info.message)++ def test_every_error_type_has_a_message(self) -> None:+ """Every ErrorType has a generic message entry."""+ for error_type in ErrorType:+ self.assertIn(error_type, _GENERIC_MESSAGE)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pyindex 93833da5a..857419b7c 100644--- a/tests/service_inbox_middleware_test.py+++ b/tests/service_inbox_middleware_test.py@@ -285,6 +285,8 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -343,6 +345,8 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,},)@@ -381,6 +385,8 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,},)diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex b9961ec51..d3edde18d 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -976,6 +976,8 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,}self.assertListEqual(@@ -1116,7 +1118,8 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):'"id":"text_block_a"}''],"role":"user","id":"msg_a","metadata":{},''"created_at":"2026-01-01T00:00:00",'- '"finished_at":"2026-01-01T00:00:00","usage":null}'+ '"finished_at":"2026-01-01T00:00:00",'+ '"finished_reason":null,"error":null,"usage":null}')self.assertEqual(content_after_first,@@ -1159,7 +1162,8 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):+ '"}''],"role":"assistant","id":"' + assistant_1.id + '",''"metadata":{},"created_at":"' + assistant_1.created_at + '",'- '"finished_at":null,"usage":null}'+ '"finished_at":null,'+ '"finished_reason":null,"error":null,"usage":null}')expected_user_msg_b_json = ('{"name":"user","content":['@@ -1167,7 +1171,8 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):'"id":"text_block_b"}''],"role":"user","id":"msg_b","metadata":{},''"created_at":"2026-01-02T00:00:00",'- '"finished_at":"2026-01-02T00:00:00","usage":null}'+ '"finished_at":"2026-01-02T00:00:00",'+ '"finished_reason":null,"error":null,"usage":null}')self.assertEqual(content_after_second,@@ -1216,6 +1221,8 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):"metadata": {},"created_at": AnyString(),"finished_at": None,+ "finished_reason": None,+ "error": None,"usage": None,}self.assertListEqual(