diff --git a/src/agenthub/channels/wecom.py b/src/agenthub/channels/wecom.py index 9067934..ecff2d3 100644 --- a/src/agenthub/channels/wecom.py +++ b/src/agenthub/channels/wecom.py @@ -239,6 +239,14 @@ class WecomAibotChannel: self._stream_append(chat_id, str(payload.get("text", ""))) elif kind == "status": self._stream_ensure(chat_id, str(payload.get("text", ""))) + elif kind == "tool_start": + # show agent progress inside the stream bubble so long tool turns + # don't look stuck + tool = str(payload.get("tool") or "") + cur = self._stream_current(chat_id) + marker = f"\n🔧 {tool}" if tool and (not cur or f"🔧 {tool}" not in cur) else "" + if marker: + self._stream_append(chat_id, marker) elif kind == "interaction": # approval / choice question: close current bubble with a # structured render; user replies in chat (M1: text-based choice) @@ -256,6 +264,11 @@ class WecomAibotChannel: with self._stream_lock: return self._streams.setdefault(chat_id, {"req_id": uuid.uuid4().hex, "buf": "", "sent": False}) + def _stream_current(self, chat_id: str) -> str: + with self._stream_lock: + st = self._streams.get(chat_id) + return st["buf"] if st else "" + def _stream_ensure(self, chat_id: str, text: str) -> None: st = self._stream_key_states(chat_id) if not st["sent"]: diff --git a/src/agenthub/runtime.py b/src/agenthub/runtime.py index 4696fb4..ec9ad3c 100644 --- a/src/agenthub/runtime.py +++ b/src/agenthub/runtime.py @@ -129,8 +129,9 @@ def _safe_inbound(mgr: SessionManager, ch, m) -> None: except Exception as e: # noqa: BLE001 import logging logging.getLogger("agenthub").error(f"[{ch.name}:{m.chat_id}] inbound failed: {e}") + friendly = _friendly_agent_error(str(e)) try: - mgr._emit(f"{ch.name}:{m.chat_id}", "final", {"text": f"出错了:{e}"}) + mgr._emit(f"{ch.name}:{m.chat_id}", "final", {"text": friendly}) except Exception: # noqa: BLE001 pass @@ -139,6 +140,21 @@ def _safe_inbound(mgr: SessionManager, ch, m) -> None: threading.Thread(target=run, name=f"inbound-{ch.name}-{m.chat_id}", daemon=True).start() +def _friendly_agent_error(raw: str) -> str: + """Translate agent/ACP errors into actionable chat text (keep original in logs).""" + low = raw.lower() + if "tool call delta is missing id or name" in low: + return ( + "⚠️ 模型服务这次调用出了点问题(上游返回的工具调用流不完整,多为免费模型偶发)。\n" + "请重发一次消息;若反复出现,发 /model 列表换一个模型再试。" + ) + if "session not found" in low: + return "⚠️ 会话已失效(服务重启或超时)。已自动重置,请重新发送消息。" + if "timeout waiting for" in low: + return "⚠️ 任务执行超时。任务可能还在后台继续,可稍后追问;或换个更简单的问法。" + return f"⚠️ 出错了:{raw}" + + def _safe_event(ch, key: str, kind: str, payload: dict[str, Any]) -> None: try: chat_id = key.split(":", 1)[1] diff --git a/src/agenthub/session.py b/src/agenthub/session.py index f91d9cf..a1dabb7 100644 --- a/src/agenthub/session.py +++ b/src/agenthub/session.py @@ -20,6 +20,7 @@ from __future__ import annotations import fnmatch import json +import logging import os import sqlite3 import threading @@ -27,7 +28,9 @@ import time from dataclasses import dataclass, field from typing import Any, Callable -from .acp_client import ACPClient, ACPProcessDead +from .acp_client import ACPClient, ACPError, ACPProcessDead + +log = logging.getLogger("agenthub.sessions") EventSink = Callable[[str, str, dict[str, Any]], None] # (binding_key, kind, payload) @@ -83,6 +86,20 @@ class PermissionRequest: choice: str | None = None # optionId chosen, None = timeout/deny +def _is_transient_model_error(msg: str) -> bool: + """Upstream model-provider hiccups that a same-session retry usually fixes.""" + low = msg.lower() + return any(s in low for s in ( + "tool call delta is missing id or name", + "internal service failure", + "upstream error", + "rate limit", + "502", + "503", + "504", + )) + + def _gen_request_id() -> str: import uuid @@ -373,6 +390,15 @@ class SessionManager: with self._lock: self._bindings.pop(k, None) raise SessionError(f"session crashed: {e}") from e + except ACPError as e: + # Transient upstream model glitches (incomplete tool-call stream) + # usually succeed on an immediate retry on the same session. + if _is_transient_model_error(str(e)): + log.warning(f"[{key}] transient model error, retrying once: {e}") + self._emit(key, "status", {"text": "模型返回异常,正在重试…"}) + res = client.session_prompt(b.acp_session_id, blocks, timeout=timeout_s) + else: + raise self._append_text(key, b.agent, b.acp_session_id, {"role": "assistant", "text": str(res.get("stopReason", ""))}) # turn terminal: final carries the accumulated text so channels without # an edit API (wecom-app / weixin) can deliver the whole message