"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): capability-gated payloads, explicit stream errors, liveness + provider doctor
Haozhe Wufa2ad4b664bb
diff --git a/agent/.env.example b/agent/.env.exampleindex 35e26beb2..d364b41db 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -26,6 +26,11 @@ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1# LANGCHAIN_MODEL_NAME=deepseek-v4-pro# DEEPSEEK_API_KEY=sk-xxx# DEEPSEEK_BASE_URL=https://api.deepseek.com/v1+# DeepSeek adapter selection: auto (default; use langchain-deepseek if installed),+# native (require langchain-deepseek, error if missing), or openai-compatible+# (force the legacy ChatOpenAI path). Install the adapter with:+# pip install "vibe-trading-ai[deepseek]"+# VIBE_TRADING_DEEPSEEK_ADAPTER=auto# --- Gemini ---# LANGCHAIN_PROVIDER=gemini@@ -146,6 +151,9 @@ TUSHARE_TOKEN=your-tushare-token# SUBAGENT_TIMEOUT=300# SUBAGENT_MAX_ITER=25# TOKEN_THRESHOLD=40000+# Hard timeout (seconds) for read-only tool execution; write tools only warn.+# Default 1800; set 0 to disable.+# VIBE_TRADING_TOOL_TIMEOUT_SECONDS=1800# Frontend SSE idle timeout in seconds before showing "Execution timed out".# Increase when using slow local models (e.g. Ollama on CPU/limited VRAM).# VIBE_TRADING_SSE_TIMEOUT=90diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 5d9524fd4..547013c3d 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -2832,6 +2832,14 @@ def cmd_live_authorize(broker: str) -> int:return EXIT_SUCCESS+def cmd_provider_doctor() -> int:+ """Print redacted provider diagnostics."""+ from src.providers.llm import provider_diagnostics++ console.print_json(data=provider_diagnostics())+ return EXIT_SUCCESS++def _format_expiry_countdown(expires_at: str) -> str:"""Return a human-readable countdown to ``expires_at`` (ISO-8601 UTC)."""from datetime import datetime, timezone@@ -3928,6 +3936,7 @@ def _build_parser() -> argparse.ArgumentParser:provider_subparsers = provider_parser.add_subparsers(dest="provider_command")login_parser = provider_subparsers.add_parser("login", help="Authenticate with an OAuth provider")login_parser.add_argument("provider", help="OAuth provider name, e.g. openai-codex")+ provider_subparsers.add_parser("doctor", help="Print redacted provider diagnostics")list_parser = subparsers.add_parser("list", help="List runs")list_parser.add_argument("--limit", dest="list_limit", type=int, default=20, help="Maximum number of runs")@@ -4529,7 +4538,9 @@ def main(argv: list[str] | None = None) -> int:if args.command == "provider":if args.provider_command == "login":return cmd_provider_login(args.provider)- console.print("[red]provider requires a subcommand.[/red] Try: vibe-trading provider login openai-codex")+ if args.provider_command == "doctor":+ return cmd_provider_doctor()+ console.print("[red]provider requires a subcommand.[/red] Try: vibe-trading provider doctor")return EXIT_USAGE_ERRORif args.command == "run":return _handle_prompt_command(diff --git a/agent/requirements.txt b/agent/requirements.txtindex f14570df9..36f83d51e 100644--- a/agent/requirements.txt+++ b/agent/requirements.txt@@ -4,6 +4,7 @@ pyyaml>=6.0.0langchain>=1.0.0,<2langchain-core>=1.0.0,<2langchain-openai>=1.0.0,<2+# optional: pip install "vibe-trading-ai[deepseek]" — native DeepSeek adapter (langchain-deepseek)langgraph>=1.0.10,<1.1langgraph-checkpoint>=2.1.0,<5python-dotenv>=1.0.0diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 9795b6697..9d3f6ff24 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -17,6 +17,8 @@ import concurrent.futuresimport jsonimport loggingimport os+import queue+import threadingimport time as _timefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional@@ -33,7 +35,7 @@ from src.goal.context import (goal_needs_continuation,goal_progress_tuple,)-from src.providers.chat import ChatLLM+from src.providers.chat import ChatLLM, ProviderStreamErrorfrom src.tools.background_tools import get_background_managerRUNS_DIR = Path(__file__).resolve().parents[2] / "runs"@@ -41,6 +43,9 @@ TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "40000"))KEEP_RECENT = 3TOOL_RESULT_LIMIT = 10_000HEARTBEAT_INTERVAL_S = float(os.getenv("VT_HEARTBEAT_INTERVAL_S", "3.0"))+REASONING_DELTA_MIN_INTERVAL_S = float(os.getenv("VT_REASONING_DELTA_MIN_INTERVAL_S", "1.0"))+STREAM_RETRY_DELAY_S = float(os.getenv("VT_STREAM_RETRY_DELAY_S", "1.0"))+TOOL_TIMEOUT_SECONDS = float(os.getenv("VIBE_TRADING_TOOL_TIMEOUT_SECONDS", "1800"))GOAL_MAX_CONTINUATIONS = int(os.getenv("VIBE_TRADING_GOAL_MAX_CONTINUATIONS", "3"))# Layer 2: Context collapse thresholds@@ -56,6 +61,13 @@ TAIL_TOKEN_BUDGET = 20_000logger = logging.getLogger(__name__)+def _format_timeout(seconds: float) -> str:+ """Return a human-readable timeout label."""+ if seconds < 1:+ return f"{seconds:.2f}s"+ return f"{seconds:.0f}s"++def estimate_tokens(messages: list) -> int:"""Rough token count estimate (~4 chars/token).@@ -394,6 +406,7 @@ class AgentLoop:iteration = 0final_content = ""+ empty_model_response_iter: int | None = Nonegoal_continuations = 0goal_last_progress: tuple[int, int] | None = Nonewrap_up_at = max(1, int(self.max_iterations * 0.8))@@ -450,22 +463,69 @@ class AgentLoop:# Streaming output + collect thinking textthinking_chunks: List[str] = []+ reasoning_chars = 0+ last_reasoning_emit: float | None = Nonedef _on_text_chunk(delta: str) -> None:thinking_chunks.append(delta)self._emit("text_delta", {"delta": delta, "iter": iteration})+ def _on_reasoning_chunk(delta: str) -> None:+ # Throttled: long reasoning streams produce hundreds of+ # chunks; emitting each one floods the SSE replay buffer+ # and evicts tool_call/text_delta events. The first chunk+ # of each iteration always emits immediately so the UI+ # flips to "Reasoning…" without delay.+ nonlocal reasoning_chars, last_reasoning_emit+ reasoning_chars += len(delta)+ now = _time.monotonic()+ if (+ last_reasoning_emit is not None+ and now - last_reasoning_emit < REASONING_DELTA_MIN_INTERVAL_S+ ):+ return+ last_reasoning_emit = now+ self._emit(+ "reasoning_delta",+ {"iter": iteration, "chars": reasoning_chars},+ )+# On last iteration, drop tool definitions to force text outputis_last_iteration = (iteration == self.max_iterations)tool_defs = None if is_last_iteration else self.registry.get_definitions()if is_last_iteration:trace.write({"type": "forced_text_only", "iter": iteration})- response = self.llm.stream_chat(- messages,- tools=tool_defs,- on_text_chunk=_on_text_chunk,- )+ try:+ response = self.llm.stream_chat(+ messages,+ tools=tool_defs,+ on_text_chunk=_on_text_chunk,+ on_reasoning_chunk=_on_reasoning_chunk,+ )+ except ProviderStreamError as exc:+ # One retry for transient mid-stream failures (connection+ # reset, relay hiccup) — mirrors the swarm worker policy.+ # Deterministic 4xx errors fail immediately. Deltas from+ # the failed attempt are dropped so the trace does not+ # contain duplicated thinking text.+ if not exc.retryable:+ raise+ logger.warning(+ "Provider stream failed (iter %s), retrying once: %s",+ iteration,+ exc,+ )+ thinking_chunks.clear()+ reasoning_chars = 0+ last_reasoning_emit = None+ _time.sleep(STREAM_RETRY_DELAY_S)+ response = self.llm.stream_chat(+ messages,+ tools=tool_defs,+ on_text_chunk=_on_text_chunk,+ on_reasoning_chunk=_on_reasoning_chunk,+ )usage = getattr(response, "usage_metadata", None) or {}if usage:self._emit(@@ -510,6 +570,17 @@ class AgentLoop:if not response.has_tool_calls:final_content = response.content or ""+ if not final_content:+ empty_model_response_iter = iteration+ trace.write(+ {+ "type": "empty_model_response",+ "iter": iteration,+ "provider": os.getenv("LANGCHAIN_PROVIDER", "openai"),+ "model": getattr(self.llm, "model_name", None) or os.getenv("LANGCHAIN_MODEL_NAME", ""),+ }+ )+ breakshould_continue_goal = Falsecontinuation_snapshot = Noneif active_goal_id and session_id and GOAL_MAX_CONTINUATIONS > 0:@@ -595,16 +666,24 @@ class AgentLoop:except Exception as exc:logger.exception(f"AgentLoop error: {exc}")+ error_code = (+ "provider_stream_error"+ if isinstance(exc, ProviderStreamError)+ else "agent_loop_error"+ )trace.write({"type": "end", "status": "error", "reason": str(exc), "iterations": iteration})trace.close()state_store.mark_failure(run_dir, str(exc))return {"status": "failed",+ "error_code": error_code,"reason": str(exc),"run_dir": str(run_dir),"run_id": run_dir.name,"content": "","react_trace": react_trace,+ "iterations": iteration,+ "max_iterations": self.max_iterations,}# Determine final status. The reason is also propagated into the@@ -618,6 +697,16 @@ class AgentLoop:elif (run_dir / "artifacts" / "metrics.csv").exists() or final_content:state_store.mark_success(run_dir)final_status = "success"+ elif empty_model_response_iter is not None:+ provider = os.getenv("LANGCHAIN_PROVIDER", "openai").strip().lower() or "openai"+ model = getattr(self.llm, "model_name", None) or os.getenv("LANGCHAIN_MODEL_NAME", "").strip() or "(unset)"+ final_reason = (+ "empty_model_response: "+ f"provider={provider} model={model} iteration {empty_model_response_iter} "+ "returned no content and no tool calls"+ )+ state_store.mark_failure(run_dir, final_reason)+ final_status = "failed"else:final_reason = (f"reached max iterations ({self.max_iterations}) without final answer"@@ -846,27 +935,154 @@ class AgentLoop:Returns:Tuple of (result_str, elapsed_ms)."""+ readonly = self._is_tool_readonly(tool_name)+ timed_out = threading.Event()+def _on_progress(event: ProgressEvent) -> None:+ if timed_out.is_set():+ returnpayload = event.to_dict()payload["tool"] = tool_nameself._emit("tool_progress", payload)def _on_heartbeat(payload: Dict[str, Any]) -> None:+ if timed_out.is_set():+ returnself._emit("tool_heartbeat", payload)- _set_emitter(_on_progress)t0 = _time.perf_counter()- try:- with HeartbeatTimer(+ timeout = TOOL_TIMEOUT_SECONDS if TOOL_TIMEOUT_SECONDS > 0 else None+ timeout_label = _format_timeout(timeout) if timeout is not None else ""++ def _elapsed_ms() -> int:+ """Return milliseconds elapsed since tool start.++ Returns:+ Elapsed wall-clock time in milliseconds.+ """+ return int((_time.perf_counter() - t0) * 1000)++ def _heartbeat_timer() -> HeartbeatTimer:+ """Build the per-invocation heartbeat timer.++ Returns:+ HeartbeatTimer wired to this invocation's heartbeat emitter.+ """+ return HeartbeatTimer(tool_name=tool_name,interval=HEARTBEAT_INTERVAL_S,emit=_on_heartbeat,- ):- result = self.registry.execute(tool_name, args)- finally:- _set_emitter(None)- elapsed_ms = int((_time.perf_counter() - t0) * 1000)- return result, elapsed_ms+ )++ def _emit_timeout_progress(stage: str, message: str, **extra: Any) -> int:+ """Emit a timeout-related tool_progress event.++ Args:+ stage: Progress stage label ("timeout" or "timeout_warning").+ message: Human-readable timeout message.+ **extra: Additional payload fields.++ Returns:+ Elapsed milliseconds at emission time.+ """+ elapsed_ms = _elapsed_ms()+ payload: Dict[str, Any] = {+ "tool": tool_name,+ "stage": stage,+ "message": message,+ "elapsed_s": round(elapsed_ms / 1000, 2),+ }+ payload.update(extra)+ self._emit("tool_progress", payload)+ return elapsed_ms++ if not readonly:+ # Write tools are never killed: a watchdog warns once past the+ # timeout, then the result is awaited to completion.+ finished = threading.Event()++ def _warn_if_stale() -> None:+ if timeout is None or finished.wait(timeout):+ return+ _emit_timeout_progress(+ "timeout_warning",+ (+ f"Write tool exceeded {timeout_label} timeout; "+ "waiting for completion because it cannot be safely cancelled"+ ),+ readonly=False,+ )++ watchdog = threading.Thread(+ target=_warn_if_stale,+ name=f"tool-watchdog-{tool_name}",+ daemon=True,+ )+ watchdog.start()+ _set_emitter(_on_progress)+ try:+ with _heartbeat_timer():+ result = self.registry.execute(tool_name, args)+ finally:+ finished.set()+ _set_emitter(None)+ return result or "", _elapsed_ms()++ # Readonly tools run in a worker thread so a hung tool becomes a+ # bounded error: late results are discarded and the emitters are+ # suppressed via the timed_out event.+ result_queue: queue.Queue[tuple[str | None, BaseException | None]] = queue.Queue(maxsize=1)++ def _worker() -> None:+ _set_emitter(_on_progress)+ try:+ result_queue.put((self.registry.execute(tool_name, args), None))+ except BaseException as exc: # noqa: BLE001 - propagate through caller thread+ result_queue.put((None, exc))+ finally:+ _set_emitter(None)++ worker = threading.Thread(+ target=_worker,+ name=f"tool-{tool_name}",+ daemon=True,+ )+ worker.start()+ with _heartbeat_timer():+ try:+ result, exc = result_queue.get(timeout=timeout)+ except queue.Empty:+ timed_out.set()+ elapsed_ms = _emit_timeout_progress(+ "timeout", f"Tool exceeded {timeout_label} timeout"+ )+ return (+ json.dumps(+ {+ "status": "error",+ "error_code": "tool_timeout",+ "tool": tool_name,+ "timeout_seconds": timeout,+ "message": f"Tool exceeded {timeout_label} timeout",+ },+ ensure_ascii=False,+ ),+ elapsed_ms,+ )+ if exc is not None:+ raise exc+ return result or "", _elapsed_ms()++ def _is_tool_readonly(self, tool_name: str) -> bool:+ """Return whether a tool is known to be side-effect free."""+ get_tool = getattr(self.registry, "get", None)+ if not callable(get_tool):+ return False+ try:+ tool_def = get_tool(tool_name)+ except Exception: # noqa: BLE001 - unknown classification is not readonly+ return False+ return bool(tool_def and getattr(tool_def, "is_readonly", False))def _finalize_tool_result(self,diff --git a/agent/src/preflight.py b/agent/src/preflight.pyindex 97a147a0b..1321921b2 100644--- a/agent/src/preflight.py+++ b/agent/src/preflight.py@@ -29,7 +29,7 @@ class CheckResult:def _check_llm_provider() -> CheckResult:"""Verify LLM provider connectivity."""- from src.providers.llm import _ensure_dotenv, _sync_provider_env+ from src.providers.llm import _ensure_dotenv, _sync_provider_env, provider_diagnostics_ensure_dotenv()provider = os.getenv("LANGCHAIN_PROVIDER", "").strip()@@ -53,7 +53,15 @@ def _check_llm_provider() -> CheckResult:)_sync_provider_env()+ diagnostics = provider_diagnostics()base_url = os.getenv("OPENAI_BASE_URL", "") or os.getenv("OPENAI_API_BASE", "")+ proxy_label = ",".join(sorted(diagnostics.get("proxy", {}).keys())) or "none"+ diag_hint = (+ f"base={diagnostics['base_url']} "+ f"timeout={diagnostics['timeout_seconds']}s "+ f"retries={diagnostics['max_retries']} "+ f"proxy={proxy_label}"+ )if provider.lower() in {"openai-codex", "openai_codex"}:try:@@ -80,7 +88,7 @@ def _check_llm_provider() -> CheckResult:return CheckResult(name=f"LLM ({provider})",status="ready",- message=f"{model} via ChatGPT OAuth ({account})",+ message=f"{model} via ChatGPT OAuth ({account}) | {diag_hint}",impact="",)@@ -88,7 +96,7 @@ def _check_llm_provider() -> CheckResult:return CheckResult(name=f"LLM ({provider})",status="not_configured",- message=f"base URL not set for {provider}",+ message=f"base URL not set for {provider} | {diag_hint}",impact="agent cannot function",critical=True,)@@ -105,14 +113,14 @@ def _check_llm_provider() -> CheckResult:return CheckResult(name=f"LLM ({provider})",status="ready",- message=f"{model} via {base_url}",+ message=f"{model} via {diagnostics['base_url']} | {diag_hint}",impact="",)except Exception as exc:return CheckResult(name=f"LLM ({provider})",status="error",- message=f"{type(exc).__name__}: {exc}",+ message=f"{type(exc).__name__}: {exc} | {diag_hint}",impact="agent cannot function",critical=True,)diff --git a/agent/src/providers/capabilities.py b/agent/src/providers/capabilities.pynew file mode 100644index 000000000..f97e85057--- /dev/null+++ b/agent/src/providers/capabilities.py@@ -0,0 +1,153 @@+"""Provider capability definitions for OpenAI-compatible chat adapters."""++from __future__ import annotations++from dataclasses import dataclass, field+from importlib.metadata import PackageNotFoundError, version+from typing import Mapping, Optional+++@dataclass(frozen=True)+class ProviderCapabilities:+ """Provider-specific payload and diagnostic behavior.++ Args:+ name: Canonical provider name.+ api_key_env: Provider-specific API key environment variable.+ base_url_env: Provider-specific base URL environment variable.+ capture_reasoning: Whether inbound reasoning fields should be preserved.+ send_reasoning_content: Whether outbound assistant history must include+ ``reasoning_content``.+ gemini_thought_signatures: Whether Gemini OpenAI-compatible tool-call+ thought signatures should be round-tripped.+ normalize_assistant_content: Whether assistant ``content=None`` should+ be normalized to ``""`` for strict providers.+ openrouter_reasoning_body: Whether ``extra_body.reasoning`` is a valid+ OpenRouter request option.+ default_headers: Provider-scoped headers passed to ChatOpenAI.+ native_adapter_package: Optional native adapter package to report.+ """++ name: str+ api_key_env: Optional[str]+ base_url_env: str+ capture_reasoning: bool = False+ send_reasoning_content: bool = False+ gemini_thought_signatures: bool = False+ normalize_assistant_content: bool = False+ openrouter_reasoning_body: bool = False+ default_headers: Mapping[str, str] = field(default_factory=dict)+ native_adapter_package: Optional[str] = None+++# Distribution name from pyproject.toml [project].name.+_DISTRIBUTION_NAME = "vibe-trading-ai"+++def _package_version() -> str:+ """Return the installed distribution version for User-Agent headers.++ Returns:+ Installed ``vibe-trading-ai`` version string, or ``"dev"`` when the+ package metadata is unavailable (e.g. an uninstalled source checkout).+ """+ try:+ return version(_DISTRIBUTION_NAME)+ except PackageNotFoundError:+ return "dev"+++_KIMI_USER_AGENT = f"Vibe-Trading/{_package_version()}"+++_MOONSHOT_CAPABILITIES = ProviderCapabilities(+ "moonshot",+ "MOONSHOT_API_KEY",+ "MOONSHOT_BASE_URL",+ capture_reasoning=True,+ send_reasoning_content=True,+ normalize_assistant_content=True,+ default_headers={"User-Agent": _KIMI_USER_AGENT},+)++_OPENAI_CODEX_CAPABILITIES = ProviderCapabilities("openai-codex", None, "OPENAI_CODEX_BASE_URL")+++_PROVIDERS: dict[str, ProviderCapabilities] = {+ "openai": ProviderCapabilities("openai", "OPENAI_API_KEY", "OPENAI_BASE_URL"),+ "openrouter": ProviderCapabilities(+ "openrouter",+ "OPENROUTER_API_KEY",+ "OPENROUTER_BASE_URL",+ capture_reasoning=True,+ openrouter_reasoning_body=True,+ ),+ "deepseek": ProviderCapabilities(+ "deepseek",+ "DEEPSEEK_API_KEY",+ "DEEPSEEK_BASE_URL",+ capture_reasoning=True,+ native_adapter_package="langchain-deepseek",+ ),+ "gemini": ProviderCapabilities(+ "gemini",+ "GEMINI_API_KEY",+ "GEMINI_BASE_URL",+ gemini_thought_signatures=True,+ ),+ "groq": ProviderCapabilities("groq", "GROQ_API_KEY", "GROQ_BASE_URL"),+ "dashscope": ProviderCapabilities("dashscope", "DASHSCOPE_API_KEY", "DASHSCOPE_BASE_URL"),+ "qwen": ProviderCapabilities("qwen", "DASHSCOPE_API_KEY", "DASHSCOPE_BASE_URL"),+ "zhipu": ProviderCapabilities("zhipu", "ZHIPU_API_KEY", "ZHIPU_BASE_URL"),+ "moonshot": _MOONSHOT_CAPABILITIES,+ "kimi": _MOONSHOT_CAPABILITIES,+ "minimax": ProviderCapabilities("minimax", "MINIMAX_API_KEY", "MINIMAX_BASE_URL"),+ "mimo": ProviderCapabilities("mimo", "MIMO_API_KEY", "MIMO_BASE_URL"),+ "zai": ProviderCapabilities("zai", "ZAI_API_KEY", "ZAI_BASE_URL"),+ "ollama": ProviderCapabilities("ollama", None, "OLLAMA_BASE_URL"),+ "openai-codex": _OPENAI_CODEX_CAPABILITIES,+ "openai_codex": _OPENAI_CODEX_CAPABILITIES,+}+++def _infer_from_model(model: str) -> str | None:+ lowered = model.strip().lower()+ if not lowered:+ return None+ if lowered.startswith("gemini"):+ return "gemini"+ if lowered.startswith("deepseek"):+ return "deepseek"+ if "kimi" in lowered or "moonshot" in lowered:+ return "moonshot"+ return None+++def get_provider_capabilities(+ provider: str | None = None,+ model: str | None = None,+) -> ProviderCapabilities:+ """Return the capability record for a provider/model pair.++ Args:+ provider: Configured provider name.+ model: Configured model name, used for direct test/adapter inference.++ Returns:+ Provider capability definition. Unknown providers fall back to OpenAI.+ """+ normalized = (provider or "").strip().lower().replace("_", "-")+ if normalized == "openai-codex":+ return _PROVIDERS["openai-codex"]+ if normalized and normalized != "openai":+ return _PROVIDERS.get(normalized, _PROVIDERS["openai"])+ inferred = _infer_from_model(model or "")+ if inferred:+ return _PROVIDERS[inferred]+ return _PROVIDERS.get(normalized, _PROVIDERS["openai"])+++def provider_env_names(provider: str | None, model: str | None = None) -> tuple[str | None, str]:+ """Return the API-key and base-URL env names for a provider/model pair."""+ caps = get_provider_capabilities(provider, model)+ return caps.api_key_env, caps.base_url_envdiff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 718c3a3b6..682f1c162 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -5,6 +5,7 @@ ChatLLM is designed specifically for the AgentLoop ReAct cycle.from __future__ import annotations+import osfrom dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional@@ -68,6 +69,55 @@ class LLMResponse:return len(self.tool_calls) > 0+class ProviderStreamError(RuntimeError):+ """Raised when provider streaming fails before a complete response."""++ def __init__(self, *, provider: str, model: str, original: Exception) -> None:+ """Initialize a provider-contextual stream error.++ Args:+ provider: Effective provider name.+ model: Effective model name.+ original: Original exception from the stream path.+ """+ self.provider = provider+ self.model = model+ self.original = original+ self.status_code: Optional[int] = getattr(original, "status_code", None)+ safe_message = _redact_provider_error(str(original))+ super().__init__(+ f"provider_stream_error provider={provider} model={model}: "+ f"{type(original).__name__}: {safe_message}"+ )++ @property+ def retryable(self) -> bool:+ """Whether a single retry could plausibly succeed.++ Returns:+ False for deterministic client errors (4xx other than 408/429),+ True for everything else — timeouts, rate limits, 5xx, and+ transport errors that carry no HTTP status.+ """+ if self.status_code is None:+ return True+ if self.status_code in (408, 429):+ return True+ return not 400 <= self.status_code < 500+++def _redact_provider_error(message: str) -> str:+ """Redact configured secret/proxy values from provider errors."""+ redacted = message+ sensitive_markers = ("KEY", "TOKEN", "SECRET", "PASSWORD", "PASS", "PROXY")+ for key, value in os.environ.items():+ if not value or len(value) < 8:+ continue+ if any(marker in key.upper() for marker in sensitive_markers):+ redacted = redacted.replace(value, "[redacted]")+ return redacted++class ChatLLM:"""LLM chat client with function calling support.@@ -107,17 +157,20 @@ class ChatLLM:messages: List[Dict[str, Any]],tools: Optional[List[Dict[str, Any]]] = None,on_text_chunk: Optional[Any] = None,+ on_reasoning_chunk: Optional[Any] = None,timeout: Optional[int] = None,) -> LLMResponse:"""Stream the LLM and optionally forward text deltas (e.g. thinking).- Iterates AIMessageChunk; each text delta invokes ``on_text_chunk``.- Aggregates chunks into one response; on failure falls back to ``chat()``.+ Iterates AIMessageChunk; text deltas invoke ``on_text_chunk`` and+ reasoning-only deltas invoke ``on_reasoning_chunk``. Aggregates chunks+ into one response. Stream failures are explicit provider errors.Args:messages: Messages in OpenAI format.tools: Tool definitions for function calling.on_text_chunk: Optional callback ``(delta: str) -> None``.+ on_reasoning_chunk: Optional callback ``(delta: str) -> None``.timeout: Optional per-call timeout in seconds.Returns:@@ -130,12 +183,17 @@ class ChatLLM:for chunk in llm.stream(messages, config=config):if chunk.content and on_text_chunk:on_text_chunk(chunk.content)+ reasoning = getattr(chunk, "additional_kwargs", {}).get("reasoning_content")+ if reasoning and not chunk.content and on_reasoning_chunk:+ on_reasoning_chunk(reasoning)accumulated = chunk if accumulated is None else accumulated + chunkif accumulated is None:return LLMResponse(content="", tool_calls=[], finish_reason="stop")return self._parse_response(accumulated)- except Exception:- return self.chat(messages, tools=tools, timeout=timeout)+ except Exception as exc:+ provider = os.getenv("LANGCHAIN_PROVIDER", "openai").strip().lower() or "openai"+ model = self.model_name or os.getenv("LANGCHAIN_MODEL_NAME", "").strip() or "(unset)"+ raise ProviderStreamError(provider=provider, model=model, original=exc) from exc@staticmethoddef _tool_call_thought_signature_maps(ai_message: Any) -> tuple[dict[str, str], dict[int, str]]:diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex c6bfd2946..5e9447c08 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -5,10 +5,16 @@ from __future__ import annotationsimport loggingimport osfrom collections.abc import Sequence+from importlib import import_module+from importlib.metadata import PackageNotFoundError, versionfrom pathlib import Pathfrom typing import Any, Optionalfrom urllib.parse import urlsplit+from pydantic import PrivateAttr++from src.providers.capabilities import get_provider_capabilities, provider_env_names+try:from dotenv import load_dotenvexcept ImportError:@@ -34,6 +40,22 @@ if ChatOpenAI is not None:multi-turn continuations."""+ _vibe_provider: Optional[str] = PrivateAttr(default=None)++ def __init__(self, *args: Any, vibe_provider: str | None = None, **kwargs: Any) -> None:+ """Initialize while retaining the resolved provider name."""+ super().__init__(*args, **kwargs)+ self._vibe_provider = vibe_provider++ def _capabilities(self):+ model = (+ getattr(self, "model_name", None)+ or getattr(self, "model", None)+ or getattr(self, "model_name_", None)+ or ""+ )+ return get_provider_capabilities(self._vibe_provider, str(model))+@staticmethoddef _extract_tool_call_thought_signature(tool_call: Any) -> Optional[str]:if not isinstance(tool_call, dict):@@ -78,13 +100,15 @@ if ChatOpenAI is not None:signatures.append(entry)return signatures- @classmethod- def _capture(cls, src: Any, msg: Any) -> None:+ def _capture(self, src: Any, msg: Any) -> None:if not isinstance(src, dict):return- if value := src.get("reasoning_content") or src.get("reasoning"):+ caps = self._capabilities()+ if caps.capture_reasoning and (value := src.get("reasoning_content") or src.get("reasoning")):msg.additional_kwargs["reasoning_content"] = value- if signatures := cls._collect_tool_call_thought_signatures(src.get("tool_calls")):+ if caps.gemini_thought_signatures and (+ signatures := self._collect_tool_call_thought_signatures(src.get("tool_calls"))+ ):msg.additional_kwargs["tool_call_thought_signatures"] = signaturesdef _convert_input(self, input: Any) -> Any: # type: ignore[override]@@ -107,6 +131,8 @@ if ChatOpenAI is not None:re-invoked on already-converted ``BaseMessage`` objects (idempotent)."""prompt_value = super()._convert_input(input)+ if not self._capabilities().gemini_thought_signatures:+ return prompt_valueif isinstance(input, Sequence) and not isinstance(input, (str, bytes)):messages = prompt_value.to_messages()if len(messages) == len(input):@@ -190,6 +216,14 @@ if ChatOpenAI is not None:if signature:cls._set_tool_call_thought_signature(tool_call, signature)+ @staticmethod+ def _strip_tool_call_extra_content(outbound: Any) -> None:+ if not isinstance(outbound, list):+ return+ for tool_call in outbound:+ if isinstance(tool_call, dict):+ tool_call.pop("extra_content", None)+def _create_chat_result(self, response, generation_info=None): # type: ignore[override]result = super()._create_chat_result(response, generation_info)raw = response if isinstance(response, dict) else response.model_dump()@@ -229,14 +263,21 @@ if ChatOpenAI is not None:"""payload = super()._get_request_payload(input_, stop=stop, **kwargs)messages = super()._convert_input(input_).to_messages()+ caps = self._capabilities()for i, m in enumerate(payload["messages"]):if m.get("role") != "assistant":continuesource_message = messages[i]- if m.get("content") is None:+ if caps.normalize_assistant_content and m.get("content") is None:m["content"] = ""- m["reasoning_content"] = source_message.additional_kwargs.get("reasoning_content", "")- self._inject_tool_call_thought_signatures(m.get("tool_calls"), source_message)+ if caps.send_reasoning_content:+ m["reasoning_content"] = source_message.additional_kwargs.get("reasoning_content", "")+ else:+ m.pop("reasoning_content", None)+ if caps.gemini_thought_signatures:+ self._inject_tool_call_thought_signatures(m.get("tool_calls"), source_message)+ else:+ self._strip_tool_call_extra_content(m.get("tool_calls"))return payloadelse:ChatOpenAIWithReasoning = None # type: ignore@@ -305,6 +346,74 @@ def _redact_base_url_for_log(raw: str | None) -> str:return f"{parsed.scheme}://{host}"+def _package_version(package: str) -> str:+ """Return an installed package version or a stable missing label."""+ try:+ return version(package)+ except PackageNotFoundError:+ return "not_installed"+++def _redact_env_flag(name: str) -> str:+ """Report whether an env var is set without exposing its value."""+ value = os.getenv(name, "")+ return "set" if value else "unset"+++def _redact_proxy_url(name: str, raw: str | None) -> str:+ """Return a credential-free proxy URL label."""+ if not raw:+ return "unset"+ if name.upper().endswith("NO_PROXY"):+ return "set"+ return _redact_base_url_for_log(raw)+++def _deepseek_adapter_mode() -> str:+ """Return the configured DeepSeek adapter mode."""+ mode = os.getenv("VIBE_TRADING_DEEPSEEK_ADAPTER", "auto").strip().lower()+ aliases = {+ "compat": "openai-compatible",+ "compatible": "openai-compatible",+ "openai": "openai-compatible",+ "openai_compatible": "openai-compatible",+ }+ return aliases.get(mode, mode or "auto")+++def _build_native_deepseek(+ *,+ model: str,+ temperature: float,+ callbacks: Any = None,+) -> Any | None:+ """Build the optional native DeepSeek adapter when installed.++ Returns:+ A ChatDeepSeek instance, or ``None`` when the optional package is not+ available.+ """+ try:+ module = import_module("langchain_deepseek")+ chat_deepseek = getattr(module, "ChatDeepSeek")+ except Exception as exc: # noqa: BLE001 - optional adapter fallback+ logger.info("DeepSeek native adapter unavailable; using OpenAI-compatible path: %s", exc)+ return None++ key_env, base_env = provider_env_names("deepseek", model)+ api_key = os.getenv(key_env or "", "") or os.getenv("OPENAI_API_KEY", "")+ base_url = os.getenv(base_env, "") or os.getenv("OPENAI_BASE_URL", "") or os.getenv("OPENAI_API_BASE", "")+ return chat_deepseek(+ model=model,+ temperature=temperature,+ timeout=int(os.getenv("TIMEOUT_SECONDS", "120")),+ max_retries=int(os.getenv("MAX_RETRIES", "2")),+ callbacks=callbacks,+ api_key=api_key or None,+ base_url=base_url or None,+ )++def _load_env_file(path: Path) -> None:"""Load a single .env file into os.environ (setdefault, no override)."""if load_dotenv is not None:@@ -371,25 +480,7 @@ def _sync_provider_env() -> None:os.environ.pop("OPENAI_API_KEY", None)return- # (api_key_env, base_url_env)- _PROVIDER_MAP: dict[str, tuple[str | None, str]] = {- "openai": ("OPENAI_API_KEY", "OPENAI_BASE_URL"),- "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_BASE_URL"),- "deepseek": ("DEEPSEEK_API_KEY", "DEEPSEEK_BASE_URL"),- "gemini": ("GEMINI_API_KEY", "GEMINI_BASE_URL"),- "groq": ("GROQ_API_KEY", "GROQ_BASE_URL"),- "dashscope": ("DASHSCOPE_API_KEY", "DASHSCOPE_BASE_URL"),- "qwen": ("DASHSCOPE_API_KEY", "DASHSCOPE_BASE_URL"),- "zhipu": ("ZHIPU_API_KEY", "ZHIPU_BASE_URL"),- "moonshot": ("MOONSHOT_API_KEY", "MOONSHOT_BASE_URL"),- "minimax": ("MINIMAX_API_KEY", "MINIMAX_BASE_URL"),- "mimo": ("MIMO_API_KEY", "MIMO_BASE_URL"),- "zai": ("ZAI_API_KEY", "ZAI_BASE_URL"),- "ollama": (None, "OLLAMA_BASE_URL"),- }-- spec = _PROVIDER_MAP.get(provider, _PROVIDER_MAP["openai"])- key_env, base_env = spec+ key_env, base_env = provider_env_names(provider, os.getenv("LANGCHAIN_MODEL_NAME", ""))# Resolve API key: provider-specific env → OPENAI_API_KEY fallbackif key_env is not None:@@ -409,6 +500,69 @@ def _sync_provider_env() -> None:os.environ.setdefault("OPENAI_BASE_URL", base_url)+def provider_diagnostics() -> dict[str, Any]:+ """Build a redacted provider diagnostic snapshot.++ Returns:+ Redacted provider/model/package/env/proxy/capability details.+ """+ _sync_provider_env()+ provider = os.getenv("LANGCHAIN_PROVIDER", "openai").strip().lower()+ model = os.getenv("LANGCHAIN_MODEL_NAME", "").strip()+ caps = get_provider_capabilities(provider, model)+ key_env, base_env = provider_env_names(provider, model)+ base_url = os.getenv(base_env, "") or os.getenv("OPENAI_BASE_URL", "") or os.getenv("OPENAI_API_BASE", "")+ proxy_names = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]+ package_names = ["langchain-openai", "langchain-core", "langchain", "openai", "langchain-deepseek"]+ native_package_version = (+ _package_version(caps.native_adapter_package)+ if caps.native_adapter_package+ else None+ )+ adapter_mode = _deepseek_adapter_mode() if caps.name == "deepseek" else "openai-compatible"+ adapter_type = (+ "native"+ if caps.name == "deepseek"+ and adapter_mode != "openai-compatible"+ and native_package_version not in {None, "not_installed"}+ else "openai-compatible"+ )+ return {+ "provider": caps.name if provider in {"kimi", "openai_codex"} else provider,+ "model": model,+ "base_url": _redact_base_url_for_log(base_url),+ "api_key": {key_env: _redact_env_flag(key_env)} if key_env else {},+ "env": {+ "LANGCHAIN_PROVIDER": _redact_env_flag("LANGCHAIN_PROVIDER"),+ "LANGCHAIN_MODEL_NAME": _redact_env_flag("LANGCHAIN_MODEL_NAME"),+ "OPENAI_API_KEY": _redact_env_flag("OPENAI_API_KEY"),+ "OPENAI_BASE_URL": _redact_base_url_for_log(os.getenv("OPENAI_BASE_URL")),+ "OPENAI_API_BASE": _redact_base_url_for_log(os.getenv("OPENAI_API_BASE")),+ },+ "proxy": {+ name: _redact_proxy_url(name, os.getenv(name))+ for name in proxy_names+ if os.getenv(name)+ },+ "packages": {name: _package_version(name) for name in package_names},+ "timeout_seconds": int(os.getenv("TIMEOUT_SECONDS", "120")),+ "max_retries": int(os.getenv("MAX_RETRIES", "2")),+ "reasoning_effort": os.getenv("LANGCHAIN_REASONING_EFFORT", "").strip().lower(),+ "adapter": {+ "type": adapter_type,+ "mode": adapter_mode,+ "native_package": caps.native_adapter_package,+ "native_package_version": native_package_version,+ },+ "capabilities": {+ "capture_reasoning": caps.capture_reasoning,+ "send_reasoning_content": caps.send_reasoning_content,+ "gemini_thought_signatures": caps.gemini_thought_signatures,+ "openrouter_reasoning_body": caps.openrouter_reasoning_body,+ },+ }++def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Any:"""Construct a ChatOpenAI instance.@@ -428,6 +582,7 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Anyraise RuntimeError("LANGCHAIN_MODEL_NAME is not set")temperature = float(os.getenv("LANGCHAIN_TEMPERATURE", "0.0"))provider = os.getenv("LANGCHAIN_PROVIDER", "openai").lower()+ caps = get_provider_capabilities(provider, name)if provider in {"openai-codex", "openai_codex"}:from src.providers.openai_codex import OpenAICodexLLM@@ -439,20 +594,44 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Anyreasoning_effort=effort or None,)+ if provider == "deepseek":+ adapter_mode = _deepseek_adapter_mode()+ if adapter_mode != "openai-compatible":+ native_llm = _build_native_deepseek(+ model=name,+ temperature=temperature,+ callbacks=callbacks,+ )+ if native_llm is not None:+ return native_llm+ if adapter_mode == "native":+ raise RuntimeError(+ "VIBE_TRADING_DEEPSEEK_ADAPTER=native requires langchain-deepseek"+ )+if ChatOpenAI is None:raise RuntimeError("langchain-openai is not installed")# MiniMax requires temperature in (0.0, 1.0] — clamp to 0.01 when the# default 0.0 is used to avoid an API validation error.if provider == "minimax" and temperature <= 0.0:temperature = 0.01+ # Moonshot kimi-k2.x reasoning models reject any temperature other than 1+ # ("invalid temperature: only 1 is allowed for this model").+ if caps.name == "moonshot" and name.lower().startswith("kimi-k2") and temperature != 1.0:+ logger.info("Forcing temperature=1.0 for %s (provider requirement)", name)+ temperature = 1.0# Optional reasoning activation for relays requiring opt-in (e.g. OpenRouter).# Moonshot/DeepSeek official APIs emit reasoning by default and ignore this field.effort = os.getenv("LANGCHAIN_REASONING_EFFORT", "").strip().lower()- return ChatOpenAIWithReasoning(- model=name,- temperature=temperature,- timeout=int(os.getenv("TIMEOUT_SECONDS", "120")),- max_retries=int(os.getenv("MAX_RETRIES", "2")),- callbacks=callbacks,- extra_body={"reasoning": {"effort": effort}} if effort else None,- )+ kwargs: dict[str, Any] = {+ "model": name,+ "temperature": temperature,+ "timeout": int(os.getenv("TIMEOUT_SECONDS", "120")),+ "max_retries": int(os.getenv("MAX_RETRIES", "2")),+ "callbacks": callbacks,+ "extra_body": {"reasoning": {"effort": effort}} if effort and caps.openrouter_reasoning_body else None,+ "vibe_provider": provider,+ }+ if caps.default_headers:+ kwargs["default_headers"] = dict(caps.default_headers)+ return ChatOpenAIWithReasoning(**kwargs)diff --git a/agent/src/session/events.py b/agent/src/session/events.pyindex 46eb93ab1..31c40fb9f 100644--- a/agent/src/session/events.py+++ b/agent/src/session/events.py@@ -29,7 +29,7 @@ class SSEEvent:timestamp: Event timestamp."""- event_id: str = field(default_factory=lambda: uuid.uuid4().hex[:16])+ event_id: Optional[str] = field(default_factory=lambda: uuid.uuid4().hex[:16])event_type: str = "message"data: Dict[str, Any] = field(default_factory=dict)session_id: str = ""@@ -42,13 +42,15 @@ class SSEEvent:Text that conforms to the SSE specification."""payload = json.dumps(self.data, ensure_ascii=False)- lines = [- f"id: {self.event_id}",+ lines = []+ if self.event_id:+ lines.append(f"id: {self.event_id}")+ lines.extend([f"event: {self.event_type}",f"data: {payload}","","",- ]+ ])return "\n".join(lines)@@ -176,6 +178,8 @@ class EventBus:result.append(event)elif event.event_id == last_event_id:found = True+ if not found and replay_all:+ return list(buffer)return resultasync def subscribe(@@ -214,6 +218,7 @@ class EventBus:yield eventexcept asyncio.TimeoutError:yield SSEEvent(+ event_id=None,event_type="heartbeat",data={"ts": time.time()},session_id=session_id,diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex f6a4341a2..c7d60e936 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -19,7 +19,7 @@ from src.agent.progress import HeartbeatTimerfrom src.agent.skills import SkillsLoaderfrom src.agent.tools import ToolRegistryfrom src.config.schema import AgentConfig-from src.providers.chat import ChatLLM+from src.providers.chat import ChatLLM, LLMResponse, ProviderStreamErrorfrom src.swarm.models import (SwarmAgentSpec,SwarmEvent,@@ -49,7 +49,22 @@ def _heartbeat_interval_s() -> float:return 3.0+def _stream_retry_delay_s() -> float:+ """Resolve the delay before the single stream retry, robust to garbage.++ Returns:+ Seconds to sleep between a failed ``stream_chat`` attempt and its one+ retry. Configurable via ``SWARM_STREAM_RETRY_DELAY_S``; a bad value+ falls back to 1.0s instead of crashing import.+ """+ try:+ return float(os.getenv("SWARM_STREAM_RETRY_DELAY_S", "1.0"))+ except ValueError:+ return 1.0++_HEARTBEAT_INTERVAL_S = _heartbeat_interval_s()+_STREAM_RETRY_DELAY_S = _stream_retry_delay_s()_MAX_TOKEN_ESTIMATE = 60_000@@ -439,8 +454,6 @@ def run_worker(# Stream the LLM — moonshot/kimi non-streaming invoke is unreliable# (issue #42), and streaming also feeds dashboard live progress.try:- remaining_timeout = max(10, int(timeout - elapsed))-def _on_text_chunk(delta: str) -> None:_emit(event_callback, "worker_text", agent_id, task_id,{"content": delta, "iteration": iteration})@@ -462,17 +475,54 @@ def run_worker({**payload, "iteration": iteration, "phase": "llm"},)- with HeartbeatTimer(- tool_name=f"llm:{agent_spec.model_name or 'default'}",- interval=_HEARTBEAT_INTERVAL_S,- emit=_on_llm_heartbeat,- ):- response = llm.stream_chat(- messages,- tools=tool_defs,- timeout=remaining_timeout,- on_text_chunk=_on_text_chunk,+ def _stream_once() -> LLMResponse:+ """Run one heartbeat-wrapped streaming LLM call.++ Recomputes the remaining time budget at call time so the+ single retry after a stream failure never reuses a stale+ timeout.++ Returns:+ Parsed ``LLMResponse`` from ``ChatLLM.stream_chat``.++ Raises:+ ProviderStreamError: When provider streaming fails.+ """+ remaining_timeout = max(10, int(timeout - (time.monotonic() - t0)))+ with HeartbeatTimer(+ tool_name=f"llm:{agent_spec.model_name or 'default'}",+ interval=_HEARTBEAT_INTERVAL_S,+ emit=_on_llm_heartbeat,+ ):+ return llm.stream_chat(+ messages,+ tools=tool_defs,+ timeout=remaining_timeout,+ on_text_chunk=_on_text_chunk,+ )++ # A transient mid-stream hiccup (connection reset) used to be+ # absorbed by ChatLLM's silent non-streaming fallback; it now+ # surfaces as ProviderStreamError, so retry the stream exactly+ # once before taking the existing failure path. Deterministic+ # 4xx errors skip the retry and fail immediately.+ try:+ response = _stream_once()+ except ProviderStreamError as stream_exc:+ if not stream_exc.retryable:+ raise+ logger.warning(+ "Provider stream failed for agent=%s task=%s iteration=%d "+ "(provider=%s model=%s); retrying once: %s",+ agent_id,+ task_id,+ iteration,+ stream_exc.provider,+ stream_exc.model,+ stream_exc,)+ time.sleep(_STREAM_RETRY_DELAY_S)+ response = _stream_once()except Exception as exc:error_msg = f"LLM call failed at iteration {iteration}: {exc}"logger.warning(error_msg)diff --git a/agent/tests/test_agent_goal_context.py b/agent/tests/test_agent_goal_context.pyindex 10a0e8a29..8a274ffc9 100644--- a/agent/tests/test_agent_goal_context.py+++ b/agent/tests/test_agent_goal_context.py@@ -29,8 +29,9 @@ class _CapturingLLM:messages: list[dict[str, Any]],tools: list[Any] | None = None,on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,) -> _AnswerResponse:- del tools, on_text_chunk+ del tools, on_text_chunk, on_reasoning_chunkself.messages = messagesself.calls.append([dict(item) for item in messages])return _AnswerResponse(total_tokens=self.total_tokens)diff --git a/agent/tests/test_agent_loop_stream_retry.py b/agent/tests/test_agent_loop_stream_retry.pynew file mode 100644index 000000000..f45e68796--- /dev/null+++ b/agent/tests/test_agent_loop_stream_retry.py@@ -0,0 +1,165 @@+"""AgentLoop single stream retry on ProviderStreamError.++Mirrors the swarm worker policy: a transient mid-stream failure (connection+reset, relay hiccup, 5xx) is retried exactly once; a deterministic 4xx fails+the run immediately with error_code=provider_stream_error and no wasted+request. Deltas from the failed attempt are dropped so the trace does not+contain duplicated thinking text.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any, Callable++import pytest++import src.agent.loop as loop_mod+from src.providers.chat import LLMResponse, ProviderStreamError+++class _FlakyLoopLLM:+ """LLM stub raising queued errors from stream_chat before succeeding."""++ def __init__(self, errors: list[Exception], final_content: str) -> None:+ """Initialize the flaky stub.++ Args:+ errors: Exceptions raised by successive ``stream_chat`` calls,+ consumed in order before any success.+ final_content: Content of the response returned once the error+ queue is drained.+ """+ self._errors = list(errors)+ self._final_content = final_content+ self.calls = 0++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ ) -> LLMResponse:+ """Raise the next queued error or return the final response.++ Args:+ messages: Conversation messages (ignored).+ tools: Tool definitions (ignored).+ on_text_chunk: Text streaming callback; fires before a queued+ error so the dropped-delta behavior is observable.+ on_reasoning_chunk: Reasoning callback (ignored).++ Returns:+ The scripted final ``LLMResponse``.++ Raises:+ Exception: The next queued error, if any remain.+ """+ self.calls += 1+ if self._errors:+ if on_text_chunk:+ on_text_chunk("partial-from-failed-attempt ")+ raise self._errors.pop(0)+ return LLMResponse(content=self._final_content)++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:+ """Return an empty non-streaming response (unused).++ Args:+ messages: Conversation messages (ignored).++ Returns:+ Empty ``LLMResponse``.+ """+ return LLMResponse(content="")+++def _transient_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a transient mid-stream reset.++ Returns:+ ProviderStreamError wrapping a ``ConnectionResetError`` (no status).+ """+ return ProviderStreamError(+ provider="deepseek",+ model="deepseek-v4-pro",+ original=ConnectionResetError("connection reset by peer"),+ )+++def _bad_request_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a deterministic 400 rejection.++ Returns:+ ProviderStreamError whose original exception carries status_code=400.+ """+ original = Exception("invalid temperature: only 1 is allowed for this model")+ original.status_code = 400 # type: ignore[attr-defined]+ return ProviderStreamError(+ provider="moonshot", model="kimi-k2.6", original=original+ )+++def _run(monkeypatch, tmp_path: Path, llm: _FlakyLoopLLM) -> dict[str, Any]:+ """Run an AgentLoop turn against the given scripted LLM.++ Args:+ monkeypatch: pytest monkeypatch fixture (zeroes the retry sleep).+ tmp_path: Scratch run directory.+ llm: The scripted LLM stub.++ Returns:+ The AgentLoop result dict.+ """+ from src.agent.loop import AgentLoop+ from src.memory.persistent import PersistentMemory+ from src.tools import build_registry++ monkeypatch.setattr(loop_mod, "STREAM_RETRY_DELAY_S", 0.0)+ pm = PersistentMemory()+ agent = AgentLoop(+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),+ llm=llm,+ max_iterations=3,+ persistent_memory=pm,+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir(parents=True, exist_ok=True)+ agent.memory.run_dir = str(run_dir)+ return agent.run(user_message="hello")+++def test_transient_stream_failure_is_retried_and_run_succeeds(+ monkeypatch, tmp_path: Path+) -> None:+ """One transient ProviderStreamError then success → run completes (2 calls)."""+ llm = _FlakyLoopLLM([_transient_error()], "Final answer.")++ result = _run(monkeypatch, tmp_path, llm)++ assert result["status"] == "success"+ assert result["content"] == "Final answer."+ assert llm.calls == 2+++def test_double_stream_failure_fails_run(monkeypatch, tmp_path: Path) -> None:+ """Two consecutive transient failures → failed run, no third attempt."""+ llm = _FlakyLoopLLM([_transient_error(), _transient_error()], "Final answer.")++ result = _run(monkeypatch, tmp_path, llm)++ assert result["status"] == "failed"+ assert result["error_code"] == "provider_stream_error"+ assert llm.calls == 2+++def test_non_retryable_4xx_fails_without_retry(monkeypatch, tmp_path: Path) -> None:+ """A deterministic 4xx ProviderStreamError fails immediately (1 call)."""+ llm = _FlakyLoopLLM([_bad_request_error()], "Final answer.")++ result = _run(monkeypatch, tmp_path, llm)++ assert result["status"] == "failed"+ assert result["error_code"] == "provider_stream_error"+ assert llm.calls == 1diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.pyindex e3d001f79..c10e0670f 100644--- a/agent/tests/test_agent_loop_terminal_state.py+++ b/agent/tests/test_agent_loop_terminal_state.py@@ -17,6 +17,7 @@ from typing import Any, Callableimport pytestfrom src.agent.loop import AgentLoop+from src.providers.chat import ProviderStreamErrorclass _StubLLMResponse:@@ -41,6 +42,7 @@ class _StubLLMNoFinal:messages: list[dict[str, Any]],tools: list[Any] | None = None,on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,) -> _StubLLMResponse:return _StubLLMResponse()@@ -63,6 +65,7 @@ class _StubLLMCancelMidStream:messages: list[dict[str, Any]],tools: list[Any] | None = None,on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,) -> _StubLLMResponse:# Set _cancelled on the bound agent so the next loop iteration check# picks it up. We still need a valid response so the current@@ -93,18 +96,17 @@ def _build_agent(llm: Any, max_iter: int = 3, tmp_run_dir: Path | None = None) -return agent-def test_failed_terminal_returns_reason_iterations_and_max_iterations(+def test_empty_model_response_returns_specific_reason(tmp_path: Path,) -> None:- """When the loop exits without a final answer or metrics.csv, the- returned dict must carry `reason`, `iterations`, and `max_iterations`- so SessionService can render an actionable error message."""+ """Empty no-tool provider output is distinct from exhausting iterations."""agent = _build_agent(_StubLLMNoFinal(), max_iter=3, tmp_run_dir=tmp_path / "run")result = agent.run(user_message="anything")assert result["status"] == "failed"- assert result["reason"] == "reached max iterations (3) without final answer"+ assert result["reason"].startswith("empty_model_response")+ assert "iteration 1" in result["reason"]assert result["iterations"] >= 1assert result["max_iterations"] == 3@@ -136,8 +138,8 @@ def test_session_service_renders_meaningful_error_from_result(tmp_path: Path) ->ui_error = result.get("reason", "unknown")assert ui_error != "unknown"- assert "max iterations" in ui_error- assert "2" in ui_error+ assert "empty_model_response" in ui_error+ assert "iteration 1" in ui_errorclass _StubLLMAlwaysToolCalls:@@ -151,6 +153,7 @@ class _StubLLMAlwaysToolCalls:messages: list[dict[str, Any]],tools: list[Any] | None = None,on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,) -> _StubLLMResponse:resp = _StubLLMResponse()if tools is not None:@@ -168,6 +171,71 @@ class _StubLLMAlwaysToolCalls:return _StubLLMResponse()+class _StubLLMIgnoresForcedTextOnly:+ """LLM stub that keeps returning tool calls even when tools=None."""++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ ) -> _StubLLMResponse:+ resp = _StubLLMResponse()+ resp.has_tool_calls = True+ resp.tool_calls = [+ type("TC", (), {"id": "tc_1", "name": "compact", "arguments": {}})()+ ]+ return resp++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:+ return _StubLLMResponse()+++class _StubLLMStreamFailure:+ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ ) -> _StubLLMResponse:+ raise ProviderStreamError(+ provider="deepseek",+ model="deepseek-v4-pro",+ original=RuntimeError("stream exploded"),+ )++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:+ return _StubLLMResponse()+++def test_provider_stream_error_returns_structured_failure(tmp_path: Path) -> None:+ """Provider stream failures should stay diagnosable at the session boundary."""+ agent = _build_agent(_StubLLMStreamFailure(), max_iter=3, tmp_run_dir=tmp_path / "run")++ result = agent.run(user_message="anything")++ assert result["status"] == "failed"+ assert result["error_code"] == "provider_stream_error"+ assert "provider_stream_error" in result["reason"]+ assert result["iterations"] == 1+ assert result["max_iterations"] == 3+++def test_true_max_iterations_still_returns_max_iteration_reason(tmp_path: Path) -> None:+ """A provider that ignores the forced text-only last turn is still max-iter."""+ agent = _build_agent(+ _StubLLMIgnoresForcedTextOnly(), max_iter=1, tmp_run_dir=tmp_path / "run"+ )++ result = agent.run(user_message="do something")++ assert result["status"] == "failed"+ assert result["reason"] == "reached max iterations (1) without final answer"+ assert result["iterations"] == 1++def test_force_text_only_on_last_iteration(tmp_path: Path) -> None:"""When the LLM keeps calling tools, the last iteration forces text-onlyoutput by passing tools=None, producing a final answer instead of failure."""diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.pynew file mode 100644index 000000000..df91554f9--- /dev/null+++ b/agent/tests/test_chat_llm_streaming.py@@ -0,0 +1,143 @@+"""ChatLLM streaming liveness and error semantics."""++from __future__ import annotations++import os+from typing import Any+from unittest.mock import patch++import pytest++from src.providers.chat import ChatLLM, ProviderStreamError+++class _FakeChunk:+ def __init__(+ self,+ *,+ content: str = "",+ reasoning: str = "",+ finish_reason: str = "stop",+ ) -> None:+ self.content = content+ self.tool_calls: list[dict[str, Any]] = []+ self.additional_kwargs = {"reasoning_content": reasoning} if reasoning else {}+ self.response_metadata = {"finish_reason": finish_reason}+ self.usage_metadata = None++ def __add__(self, other: "_FakeChunk") -> "_FakeChunk":+ merged = _FakeChunk(+ content=f"{self.content}{other.content}",+ reasoning=(+ f"{self.additional_kwargs.get('reasoning_content', '')}"+ f"{other.additional_kwargs.get('reasoning_content', '')}"+ ),+ finish_reason=other.response_metadata.get("finish_reason", "stop"),+ )+ return merged+++class _FakeStreamingLLM:+ def __init__(self, chunks: list[_FakeChunk] | None = None, exc: Exception | None = None) -> None:+ self.chunks = chunks or []+ self.exc = exc+ self.invoke_called = False++ def bind_tools(self, tools: list[dict[str, Any]]) -> "_FakeStreamingLLM":+ return self++ def stream(self, messages: list[dict[str, Any]], config: dict[str, Any] | None = None):+ if self.exc is not None:+ raise self.exc+ yield from self.chunks++ def invoke(self, messages: list[dict[str, Any]], config: dict[str, Any] | None = None):+ self.invoke_called = True+ return _FakeChunk(content="fallback")+++def _client(fake_llm: _FakeStreamingLLM) -> ChatLLM:+ client = ChatLLM.__new__(ChatLLM)+ client.model_name = "deepseek-v4-pro"+ client._llm = fake_llm+ return client+++def test_reasoning_only_chunks_emit_progress_without_final_answer_text() -> None:+ fake = _FakeStreamingLLM([+ _FakeChunk(reasoning="thinking "),+ _FakeChunk(reasoning="more"),+ _FakeChunk(content="final"),+ ])+ text_chunks: list[str] = []+ reasoning_chunks: list[str] = []++ response = _client(fake).stream_chat(+ [{"role": "user", "content": "hi"}],+ on_text_chunk=text_chunks.append,+ on_reasoning_chunk=reasoning_chunks.append,+ )++ assert text_chunks == ["final"]+ assert reasoning_chunks == ["thinking ", "more"]+ assert response.content == "final"+ assert response.reasoning_content == "thinking more"+++def test_stream_failure_raises_provider_error_without_silent_fallback() -> None:+ fake = _FakeStreamingLLM(exc=RuntimeError("stream exploded"))++ with patch.dict(+ os.environ,+ {"LANGCHAIN_PROVIDER": "deepseek", "LANGCHAIN_MODEL_NAME": "deepseek-v4-pro"},+ clear=True,+ ):+ with pytest.raises(ProviderStreamError) as excinfo:+ _client(fake).stream_chat([{"role": "user", "content": "hi"}])++ assert "provider=deepseek" in str(excinfo.value)+ assert "model=deepseek-v4-pro" in str(excinfo.value)+ assert fake.invoke_called is False+++def test_stream_error_redacts_configured_secret_values() -> None:+ fake = _FakeStreamingLLM(exc=RuntimeError("bad key sk-live-secret-123456"))++ with patch.dict(+ os.environ,+ {+ "LANGCHAIN_PROVIDER": "deepseek",+ "LANGCHAIN_MODEL_NAME": "deepseek-v4-pro",+ "DEEPSEEK_API_KEY": "sk-live-secret-123456",+ },+ clear=True,+ ):+ with pytest.raises(ProviderStreamError) as excinfo:+ _client(fake).stream_chat([{"role": "user", "content": "hi"}])++ assert "sk-live-secret-123456" not in str(excinfo.value)+ assert "[redacted]" in str(excinfo.value)+++ ("status_code", "expected"),+ [+ (None, True), # transport error, no HTTP status — plausibly transient+ (400, False), # deterministic client error+ (401, False),+ (404, False),+ (408, True), # request timeout — transient+ (429, True), # rate limit — transient+ (500, True),+ (503, True),+ ],+)+def test_provider_stream_error_retryable_classification(+ status_code: int | None, expected: bool+) -> None:+ original = Exception("boom")+ if status_code is not None:+ original.status_code = status_code # type: ignore[attr-defined]+ err = ProviderStreamError(provider="kimi", model="kimi-k2.6", original=original)+ assert err.status_code == status_code+ assert err.retryable is expecteddiff --git a/agent/tests/test_kimi_reasoning_content.py b/agent/tests/test_kimi_reasoning_content.pyindex 5699e463e..2c3e61bf7 100644--- a/agent/tests/test_kimi_reasoning_content.py+++ b/agent/tests/test_kimi_reasoning_content.py@@ -668,6 +668,39 @@ class TestChatOpenAIWithReasoningOutboundPayload:assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")assert assistant_msg["reasoning_content"] == ""+ def test_openai_does_not_inject_empty_reasoning_content(self) -> None:+ """Strict Kimi continuation fields must not leak into OpenAI payloads."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance(model="gpt-4")+ history = [+ HumanMessage(content="hi"),+ AIMessage(content="plain assistant reply"),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert "reasoning_content" not in assistant_msg++ def test_deepseek_does_not_replay_reasoning_content_outbound(self) -> None:+ """DeepSeek reasoning traces are inbound progress, not next-turn payload."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance(model="deepseek-v4-pro")+ history = [+ HumanMessage(content="hi"),+ AIMessage(+ content="",+ additional_kwargs={"reasoning_content": "internal reasoning"},+ ),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert "reasoning_content" not in assistant_msg+def test_user_and_system_messages_untouched(self) -> None:"""Only assistant messages get the reasoning_content injection."""from langchain_core.messages import HumanMessage, SystemMessage@@ -682,3 +715,29 @@ class TestChatOpenAIWithReasoningOutboundPayload:for m in payload["messages"]:assert "reasoning_content" not in m++ def test_non_gemini_does_not_inject_tool_call_thought_signature(self) -> None:+ """Gemini thought signatures must be Gemini-only payload mutations."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance(model="gpt-4")+ history = [+ HumanMessage(content="hi"),+ AIMessage(+ content="",+ additional_kwargs={+ "tool_call_thought_signatures": [+ {"id": "c1", "index": 0, "thought_signature": "sig-a"},+ ],+ "tool_calls": [+ {"id": "c1", "type": "function",+ "function": {"name": "t", "arguments": "{}"}},+ ],+ },+ ),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert "extra_content" not in assistant_msg["tool_calls"][0]diff --git a/agent/tests/test_provider_diagnostics.py b/agent/tests/test_provider_diagnostics.pynew file mode 100644index 000000000..b51cf5c98--- /dev/null+++ b/agent/tests/test_provider_diagnostics.py@@ -0,0 +1,160 @@+"""Provider capability and diagnostic regression tests."""++from __future__ import annotations++import json+import os+from unittest.mock import patch++from src.providers.capabilities import get_provider_capabilities+from src.providers.llm import build_llm, provider_diagnostics+++def test_provider_diagnostics_redacts_secrets_and_proxy_values() -> None:+ """Doctor output must be useful without leaking keys or proxy credentials."""+ import src.providers.llm as llm_mod++ llm_mod._dotenv_loaded = True+ env = {+ "LANGCHAIN_PROVIDER": "deepseek",+ "LANGCHAIN_MODEL_NAME": "deepseek-v4-pro",+ "DEEPSEEK_API_KEY": "sk-super-secret",+ "DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1?token=secret",+ "HTTPS_PROXY": "http://user:[email protected]:8888",+ "NO_PROXY": "localhost,127.0.0.1,::1",+ "TIMEOUT_SECONDS": "7",+ "MAX_RETRIES": "5",+ }++ with patch.dict(os.environ, env, clear=True):+ diagnostics = provider_diagnostics()++ encoded = json.dumps(diagnostics, sort_keys=True)+ assert diagnostics["provider"] == "deepseek"+ assert diagnostics["model"] == "deepseek-v4-pro"+ assert diagnostics["base_url"] == "https://api.deepseek.com"+ assert diagnostics["timeout_seconds"] == 7+ assert diagnostics["max_retries"] == 5+ assert diagnostics["api_key"]["DEEPSEEK_API_KEY"] == "set"+ assert diagnostics["proxy"]["HTTPS_PROXY"] == "http://proxy.local:8888"+ assert diagnostics["proxy"]["NO_PROXY"] == "set"+ assert "langchain-openai" in diagnostics["packages"]+ assert "sk-super-secret" not in encoded+ assert "user:pass" not in encoded+ assert "token=secret" not in encoded+++def test_provider_capabilities_are_provider_specific() -> None:+ """DeepSeek, Kimi, Gemini, and OpenRouter should not share one mutation bag."""+ deepseek = get_provider_capabilities("deepseek", "deepseek-v4-pro")+ kimi = get_provider_capabilities("moonshot", "kimi-k2.6")+ gemini = get_provider_capabilities("gemini", "gemini-3.5-flash")+ openrouter = get_provider_capabilities("openrouter", "deepseek/deepseek-v4-pro")++ assert deepseek.capture_reasoning is True+ assert deepseek.send_reasoning_content is False+ assert deepseek.gemini_thought_signatures is False++ assert kimi.capture_reasoning is True+ assert kimi.send_reasoning_content is True+ assert kimi.default_headers["User-Agent"].startswith("Vibe-Trading/")++ assert gemini.gemini_thought_signatures is True+ assert gemini.send_reasoning_content is False++ assert openrouter.openrouter_reasoning_body is True+ assert openrouter.send_reasoning_content is False+++def test_reasoning_effort_extra_body_is_openrouter_only() -> None:+ """LANGCHAIN_REASONING_EFFORT should not leak into official DeepSeek payloads."""+ import src.providers.llm as llm_mod++ llm_mod._dotenv_loaded = True+ captured: dict = {}++ class _FakeChatOpenAI:+ def __init__(self, **kwargs: object) -> None:+ captured.update(kwargs)++ env = {+ "LANGCHAIN_PROVIDER": "deepseek",+ "DEEPSEEK_API_KEY": "ds-test",+ "DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1",+ "LANGCHAIN_MODEL_NAME": "deepseek-v4-pro",+ "LANGCHAIN_REASONING_EFFORT": "high",+ "VIBE_TRADING_DEEPSEEK_ADAPTER": "openai-compatible",+ }+ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ build_llm()++ assert captured["extra_body"] is None+++def test_kimi_user_agent_header_is_moonshot_only() -> None:+ """Kimi whitelist headers should be scoped to Moonshot/Kimi."""+ import src.providers.llm as llm_mod++ llm_mod._dotenv_loaded = True+ captured: dict = {}++ class _FakeChatOpenAI:+ def __init__(self, **kwargs: object) -> None:+ captured.update(kwargs)++ env = {+ "LANGCHAIN_PROVIDER": "moonshot",+ "MOONSHOT_API_KEY": "mk-test",+ "MOONSHOT_BASE_URL": "https://api.moonshot.ai/v1",+ "LANGCHAIN_MODEL_NAME": "kimi-k2.6",+ }+ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ build_llm()++ assert captured["default_headers"]["User-Agent"].startswith("Vibe-Trading/")++ captured.clear()+ env = {+ "LANGCHAIN_PROVIDER": "openai",+ "OPENAI_API_KEY": "sk-test",+ "OPENAI_BASE_URL": "https://api.openai.com/v1",+ "LANGCHAIN_MODEL_NAME": "gpt-4",+ }+ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ build_llm()++ assert "default_headers" not in captured+++def test_deepseek_native_adapter_is_used_when_available(monkeypatch) -> None:+ """DeepSeek should prefer the optional native adapter when installed."""+ import sys+ from types import SimpleNamespace++ import src.providers.llm as llm_mod++ llm_mod._dotenv_loaded = True+ captured: dict = {}++ class _FakeChatDeepSeek:+ def __init__(self, **kwargs: object) -> None:+ captured.update(kwargs)++ monkeypatch.setitem(sys.modules, "langchain_deepseek", SimpleNamespace(ChatDeepSeek=_FakeChatDeepSeek))+ env = {+ "LANGCHAIN_PROVIDER": "deepseek",+ "DEEPSEEK_API_KEY": "ds-test",+ "DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1",+ "LANGCHAIN_MODEL_NAME": "deepseek-v4-pro",+ }++ with patch.dict(os.environ, env, clear=True):+ llm = build_llm()++ assert isinstance(llm, _FakeChatDeepSeek)+ assert captured["model"] == "deepseek-v4-pro"+ assert captured["api_key"] == "ds-test"+ assert captured["base_url"] == "https://api.deepseek.com/v1"diff --git a/agent/tests/test_reasoning_delta_throttle.py b/agent/tests/test_reasoning_delta_throttle.pynew file mode 100644index 000000000..b6dbd52bf--- /dev/null+++ b/agent/tests/test_reasoning_delta_throttle.py@@ -0,0 +1,97 @@+"""Regression test: reasoning_delta SSE events are throttled.++Long DeepSeek/Kimi reasoning streams produce hundreds of chunks. Before the+throttle, each chunk emitted one reasoning_delta event, flooding the 500-event+session replay ring buffer and evicting the tool_call/text_delta events that+reconnect replay depends on. The loop now emits at most one reasoning_delta+per REASONING_DELTA_MIN_INTERVAL_S, but always emits the first chunk of an+iteration immediately so the UI flips to "Reasoning…" without delay.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any, Callable++CHUNK_COUNT = 300+CHUNK_TEXT = "reasoning…"+++class _StubLLMResponse:+ """Minimal stand-in for ChatLLM's response object."""++ def __init__(self, content: str = "") -> None:+ self.content = content+ self.tool_calls: list[Any] = []+ self.reasoning_content: str | None = None+ self.has_tool_calls = False+++class _ReasoningBurstLLM:+ """LLM stub that fires many reasoning chunks in a tight loop."""++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ ) -> _StubLLMResponse:+ assert on_reasoning_chunk is not None+ for _ in range(CHUNK_COUNT):+ on_reasoning_chunk(CHUNK_TEXT)+ return _StubLLMResponse(content="Final answer.")++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:+ return _StubLLMResponse()+++def _build_agent(llm: Any, events: list, tmp_run_dir: Path):+ """Build an AgentLoop with a real (but shell-free) registry and a stub LLM.++ Args:+ llm: Stub LLM object exposing stream_chat/chat.+ events: List that collects (event_type, data) tuples.+ tmp_run_dir: Run directory for the agent's workspace memory.++ Returns:+ Configured AgentLoop instance.+ """+ from src.agent.loop import AgentLoop+ from src.memory.persistent import PersistentMemory+ from src.tools import build_registry++ pm = PersistentMemory()+ agent = AgentLoop(+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),+ llm=llm,+ event_callback=lambda event_type, data: events.append((event_type, data)),+ max_iterations=3,+ persistent_memory=pm,+ )+ tmp_run_dir.mkdir(parents=True, exist_ok=True)+ agent.memory.run_dir = str(tmp_run_dir)+ return agent+++def test_reasoning_delta_throttled_but_first_chunk_immediate(tmp_path: Path) -> None:+ """A burst of reasoning chunks must collapse to few events, first one instant."""+ events: list[tuple[str, dict[str, Any]]] = []+ agent = _build_agent(_ReasoningBurstLLM(), events, tmp_path / "run")++ result = agent.run(user_message="think hard")++ assert result["status"] == "success"+ deltas = [data for event_type, data in events if event_type == "reasoning_delta"]++ # First chunk emitted immediately: cumulative chars equals exactly one chunk.+ assert deltas, "expected at least one reasoning_delta event"+ assert deltas[0]["chars"] == len(CHUNK_TEXT)++ # Throttled: a tight 300-chunk burst (well under the 1s window) must emit+ # far fewer events than chunks — not one event per chunk.+ assert len(deltas) < CHUNK_COUNT // 10++ # Cumulative "chars" payload semantics preserved (monotonically increasing).+ chars = [d["chars"] for d in deltas]+ assert chars == sorted(chars)diff --git a/agent/tests/test_session_events.py b/agent/tests/test_session_events.pyindex 26895fd3a..0a12b0ac5 100644--- a/agent/tests/test_session_events.py+++ b/agent/tests/test_session_events.py@@ -2,7 +2,7 @@from __future__ import annotations-from src.session.events import EventBus+from src.session.events import EventBus, SSEEventdef test_first_connect_does_not_replay_completed_history_by_default() -> None:@@ -27,3 +27,24 @@ def test_last_event_id_replay_still_returns_only_later_events() -> None:third = bus.emit("s1", "text_delta", {"delta": "done"})assert bus.replay("s1", last_event_id=first.event_id, replay_all=True) == [second, third]+++def test_replay_all_with_unknown_last_event_id_returns_buffer() -> None:+ """A non-buffered heartbeat id must not cause active terminal events to be skipped."""+ bus = EventBus()+ first = bus.emit("s1", "tool_call", {"tool": "load_skill"})+ terminal = bus.emit("s1", "attempt.completed", {"summary": "done"})++ assert bus.replay("s1", last_event_id="synthetic-heartbeat-id", replay_all=True) == [+ first,+ terminal,+ ]+++def test_synthetic_heartbeat_frame_has_no_replay_id() -> None:+ heartbeat = SSEEvent(event_id=None, event_type="heartbeat", data={"ts": 1}, session_id="s1")++ frame = heartbeat.to_sse()++ assert "event: heartbeat" in frame+ assert "id:" not in framediff --git a/agent/tests/test_swarm_status_hydration.py b/agent/tests/test_swarm_status_hydration.pyindex eb3b7ed7c..409146bf0 100644--- a/agent/tests/test_swarm_status_hydration.py+++ b/agent/tests/test_swarm_status_hydration.py@@ -553,8 +553,12 @@ def test_worker_source_wires_heartbeat_around_llm_streaming():versions only wrapped registry.execute, leaving a real loophole wherereconcile_run would mark a healthy run failed mid-LLM-call."""import inspect+ import resource = inspect.getsource(worker_mod)- timer_idx = source.find('with HeartbeatTimer(\n tool_name=f"llm:')+ timer_match = re.search(+ r'with HeartbeatTimer\(\s*\n\s*tool_name=f"llm:', source+ )+ timer_idx = timer_match.start() if timer_match else -1stream_idx = source.find("llm.stream_chat(", timer_idx)assert 0 < timer_idx < stream_idx, ("llm.stream_chat must be wrapped in a HeartbeatTimer so the stale-"diff --git a/agent/tests/test_swarm_worker_stream_retry.py b/agent/tests/test_swarm_worker_stream_retry.pynew file mode 100644index 000000000..2be91fdc0--- /dev/null+++ b/agent/tests/test_swarm_worker_stream_retry.py@@ -0,0 +1,191 @@+"""Tests for the single stream retry on ProviderStreamError in run_worker.++``ChatLLM.stream_chat`` used to silently fall back to non-streaming ``chat()``+on any exception; it now raises ``ProviderStreamError``. A swarm worker that+previously survived a transient mid-stream hiccup (connection reset) via the+silent fallback would now fail outright, so ``run_worker`` retries the stream+exactly once for ``ProviderStreamError`` — and only for it — before the+existing failure path.+"""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++from src.providers.chat import LLMResponse, ProviderStreamError+from src.swarm.models import SwarmAgentSpec, SwarmTask, WorkerResult+import src.swarm.worker as worker_mod+from src.swarm.worker import run_worker++# Substantive prose so _classify_deliverable accepts the tool-less worker.+FINAL_TEXT = (+ "# BTC-USDT — Short-Term View\n\n"+ "Spot 81,704.6 (2026-05-05). 7d range 77,750-82,842.\n\n"+ "**Recommendation: accumulate on dips to 79k; invalidation below 77.5k.**\n"+ "Position 3% NAV, stop 76,900, target 86,000. Funding 0.035%/8h elevated\n"+ "but not extreme; exchange reserves declining (bullish)."+)+++class _EmptyRegistry:+ """Minimal stand-in for the swarm ToolRegistry (worker needs no tools)."""++ def get_definitions(self) -> list[dict]:+ """Return an empty tool-definition list.++ Returns:+ Empty list — the scripted LLM never requests a tool call.+ """+ return []+++class _FlakyChatLLM:+ """Scripted ChatLLM whose stream_chat raises queued errors, then succeeds."""++ def __init__(self, errors: list[Exception], final: LLMResponse) -> None:+ """Initialize the flaky stub.++ Args:+ errors: Exceptions raised by successive ``stream_chat`` calls,+ consumed in order before any success.+ final: Response returned once the error queue is drained.+ """+ self._errors = list(errors)+ self._final = final+ self.calls = 0++ def __call__(self, *args, **kwargs) -> "_FlakyChatLLM":+ """Support ``ChatLLM(model_name=...)`` constructor-style patching.++ Returns:+ The shared stub instance.+ """+ return self++ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None) -> LLMResponse:+ """Raise the next queued error or return the final response.++ Args:+ messages: Conversation messages (ignored).+ tools: Tool definitions (ignored).+ on_text_chunk: Streaming callback (ignored).+ timeout: Per-call timeout (ignored).++ Returns:+ The scripted final ``LLMResponse``.++ Raises:+ Exception: The next queued error, if any remain.+ """+ self.calls += 1+ if self._errors:+ raise self._errors.pop(0)+ return self._final+++def _stream_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a transient mid-stream reset.++ Returns:+ ProviderStreamError wrapping a ``ConnectionResetError``.+ """+ return ProviderStreamError(+ provider="openrouter",+ model="test-model",+ original=ConnectionResetError("connection reset by peer"),+ )+++def _run(monkeypatch, tmp_path: Path, llm: _FlakyChatLLM) -> WorkerResult:+ """Run a tool-less worker against the given scripted LLM.++ Args:+ monkeypatch: pytest monkeypatch fixture (zeroes the retry sleep).+ tmp_path: Scratch run directory.+ llm: The scripted ChatLLM stub.++ Returns:+ The WorkerResult from ``run_worker``.+ """+ monkeypatch.setattr(worker_mod, "_STREAM_RETRY_DELAY_S", 0.0)+ agent = SwarmAgentSpec(+ id="analyst",+ role="Synthesis analyst",+ system_prompt="You synthesize upstream findings.",+ tools=[],+ skills=[],+ max_iterations=3,+ timeout_seconds=60,+ )+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="Summarize.")+ with (+ patch.object(worker_mod, "build_swarm_registry", lambda *a, **k: _EmptyRegistry()),+ patch.object(worker_mod, "ChatLLM", llm),+ ):+ return run_worker(+ agent_spec=agent,+ task=task,+ upstream_summaries={},+ user_vars={},+ run_dir=tmp_path,+ )+++def test_single_stream_failure_is_retried_and_worker_succeeds(monkeypatch, tmp_path):+ """One ProviderStreamError then success → worker completes (2 calls)."""+ llm = _FlakyChatLLM([_stream_error()], LLMResponse(content=FINAL_TEXT))++ result = _run(monkeypatch, tmp_path, llm)++ assert result.status == "completed"+ assert result.error is None+ assert llm.calls == 2+++def test_double_stream_failure_fails_worker(monkeypatch, tmp_path):+ """Two consecutive ProviderStreamErrors → existing failure path (no 3rd try)."""+ llm = _FlakyChatLLM(+ [_stream_error(), _stream_error()], LLMResponse(content=FINAL_TEXT)+ )++ result = _run(monkeypatch, tmp_path, llm)++ assert result.status == "failed"+ assert "LLM call failed at iteration 0" in (result.error or "")+ assert llm.calls == 2+++def test_non_stream_error_is_not_retried(monkeypatch, tmp_path):+ """A non-ProviderStreamError fails immediately without a retry."""+ llm = _FlakyChatLLM([ValueError("boom")], LLMResponse(content=FINAL_TEXT))++ result = _run(monkeypatch, tmp_path, llm)++ assert result.status == "failed"+ assert "LLM call failed at iteration 0" in (result.error or "")+ assert llm.calls == 1+++def _bad_request_error() -> ProviderStreamError:+ """Build a ProviderStreamError mimicking a deterministic 400 rejection.++ Returns:+ ProviderStreamError whose original exception carries status_code=400.+ """+ original = Exception("invalid temperature: only 1 is allowed for this model")+ original.status_code = 400 # type: ignore[attr-defined]+ return ProviderStreamError(+ provider="moonshot", model="kimi-k2.6", original=original+ )+++def test_non_retryable_4xx_fails_without_retry(monkeypatch, tmp_path):+ """A deterministic 4xx ProviderStreamError fails immediately (1 call)."""+ llm = _FlakyChatLLM([_bad_request_error()], LLMResponse(content=FINAL_TEXT))++ result = _run(monkeypatch, tmp_path, llm)++ assert result.status == "failed"+ assert "LLM call failed at iteration 0" in (result.error or "")+ assert llm.calls == 1diff --git a/agent/tests/test_tool_timeout.py b/agent/tests/test_tool_timeout.pynew file mode 100644index 000000000..aec4ec4ec--- /dev/null+++ b/agent/tests/test_tool_timeout.py@@ -0,0 +1,87 @@+"""Tool timeout/liveness regression tests."""++from __future__ import annotations++import json+import time+from types import SimpleNamespace+from typing import Any++from src.agent import loop as loop_mod+from src.agent.loop import AgentLoop+++class _SlowRegistry:+ class _Tool:+ is_readonly = True++ def get(self, tool_name: str) -> object:+ return self._Tool()++ def execute(self, tool_name: str, args: dict[str, Any]) -> str:+ time.sleep(1.0)+ return '{"status":"ok"}'+++class _SlowWriteRegistry:+ class _Tool:+ is_readonly = False++ def __init__(self) -> None:+ self.completed = False++ def get(self, tool_name: str) -> object:+ return self._Tool()++ def execute(self, tool_name: str, args: dict[str, Any]) -> str:+ time.sleep(0.08)+ self.completed = True+ return '{"status":"ok"}'+++def test_tool_timeout_returns_error_and_stops_heartbeats(monkeypatch) -> None:+ """A hung tool should become a bounded diagnostic instead of heartbeating forever."""+ monkeypatch.setattr(loop_mod, "TOOL_TIMEOUT_SECONDS", 0.05)+ monkeypatch.setattr(loop_mod, "HEARTBEAT_INTERVAL_S", 0.01)+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=_SlowRegistry(), # type: ignore[arg-type]+ llm=SimpleNamespace(),+ event_callback=lambda event_type, data: events.append((event_type, data)),+ max_iterations=1,+ )++ result, elapsed_ms = agent._invoke_tool("slow_tool", {})+ event_count_at_return = len(events)+ time.sleep(0.08)++ payload = json.loads(result)+ assert payload["status"] == "error"+ assert payload["error_code"] == "tool_timeout"+ assert payload["tool"] == "slow_tool"+ assert elapsed_ms >= 40+ assert len(events) == event_count_at_return+++def test_write_tool_timeout_warns_but_does_not_return_before_completion(monkeypatch) -> None:+ """Write tools must not report failure while their side effect continues."""+ monkeypatch.setattr(loop_mod, "TOOL_TIMEOUT_SECONDS", 0.02)+ monkeypatch.setattr(loop_mod, "HEARTBEAT_INTERVAL_S", 0.01)+ events: list[tuple[str, dict[str, Any]]] = []+ registry = _SlowWriteRegistry()+ agent = AgentLoop(+ registry=registry, # type: ignore[arg-type]+ llm=SimpleNamespace(),+ event_callback=lambda event_type, data: events.append((event_type, data)),+ max_iterations=1,+ )++ result, elapsed_ms = agent._invoke_tool("place_order", {})++ assert json.loads(result) == {"status": "ok"}+ assert registry.completed is True+ assert elapsed_ms >= 70+ assert any(+ event_type == "tool_progress" and data.get("stage") == "timeout_warning"+ for event_type, data in events+ )diff --git a/frontend/src/hooks/__tests__/useSSE.test.ts b/frontend/src/hooks/__tests__/useSSE.test.tsindex 1413ffc4e..5ac3e6102 100644--- a/frontend/src/hooks/__tests__/useSSE.test.ts+++ b/frontend/src/hooks/__tests__/useSSE.test.ts@@ -122,6 +122,20 @@ describe("useSSE — event handling", () => {expect(textDeltas[0]).toEqual({ content: "hello" });});+ it("dispatches reasoning progress events", () => {+ const reasoningEvents: unknown[] = [];+ const { result } = renderHook(() => useSSE());++ act(() =>+ result.current.connect("http://test/events", {+ reasoning_delta: (data) => reasoningEvents.push(data),+ }),+ );++ act(() => MockEventSource.latest.emit("reasoning_delta", { chars: 8 }, "evt-reasoning"));+ expect(reasoningEvents).toEqual([{ chars: 8 }]);+ });+it("falls back to message handler for known event types without specific handler", () => {const messages: unknown[] = [];const { result } = renderHook(() => useSSE());diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex b3c857c76..5d1b322c8 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -80,7 +80,7 @@ export function useSSE(config?: SSEConfig) {// Only subscribe to event types the backend actually emitsconst knownTypes = [- "text_delta", "thinking_done", "tool_call", "tool_result", "compact",+ "text_delta", "reasoning_delta", "thinking_done", "tool_call", "tool_result", "compact","tool_heartbeat", "tool_progress", "llm_usage","swarm.started", "swarm.event","attempt.created", "attempt.started", "attempt.completed", "attempt.failed",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 52655dd83..6682e7727 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -249,6 +249,7 @@ export function Agent() {* could be active out-of-band (CLI/another session), not only off in-session SSE* items (audit M2: always-available global halt — SPEC Consent §4). */const [liveStatus, setLiveStatus] = useState<LiveStatus | null>(null);+ const [reasoningActive, setReasoningActive] = useState(false);/* The status endpoint is not wired on every backend; a 404/501 hides the panel* and removes status from the kill-switch visibility condition. */const [liveStatusUnavailable, setLiveStatusUnavailable] = useState(false);@@ -409,11 +410,23 @@ export function Agent() {const touch = () => { lastEventRef.current = Date.now(); };connect(api.sseUrl(sid, { replay: "active" }), {- text_delta: (d) => { touch(); act().appendDelta(String(d.delta || "")); scrollToBottom(); },+ text_delta: (d) => {+ touch();+ setReasoningActive(false);+ act().appendDelta(String(d.delta || ""));+ scrollToBottom();+ },+ reasoning_delta: () => {+ touch();+ setReasoningActive(true);+ if (act().status !== "streaming") act().setStatus("streaming");+ scrollToBottom();+ },thinking_done: () => { touch(); /* don't flush — keep streaming text visible */ },tool_call: (d) => {touch();+ setReasoningActive(false);const toolName = String(d.tool || "");// Only update toolCalls tracker (no message creation during streaming)act().addToolCall({@@ -498,6 +511,7 @@ export function Agent() {"attempt.completed": async (d) => {touch();+ setReasoningActive(false);const s = act();// Build ThinkingTimeline summary from accumulated toolCallsconst completedTools = s.toolCalls;@@ -562,6 +576,7 @@ export function Agent() {"attempt.failed": (d) => {touch();+ setReasoningActive(false);act().clearStreaming();act().addMessage({ id: "", type: "error", content: String(d.error || "Execution failed"), timestamp: Date.now() });act().setStatus("idle");@@ -774,6 +789,7 @@ export function Agent() {lastEventRef.current = Date.now();const timer = setInterval(() => {if (lastEventRef.current && Date.now() - lastEventRef.current > sseTimeoutMsRef.current && act().status === "streaming") {+ setReasoningActive(false);act().setStatus("idle");toast.warning("Execution timed out, automatically stopped");}@@ -858,6 +874,7 @@ export function Agent() {const handleSubmit = (e: FormEvent) => { e.preventDefault(); runPrompt(input.trim()); };const handleCancel = async () => {+ setReasoningActive(false);if (!sessionId) {act().setStatus("idle");return;@@ -1140,7 +1157,7 @@ export function Agent() {})}{/* Pre-stream placeholder: visible after Send, before first SSE event */}- {status === "streaming" && !streamingText && toolCalls.length === 0 && !messages.some((m) => m.type === "swarm_status" && m.swarmStatus?.status === "running") && (+ {status === "streaming" && !reasoningActive && !streamingText && toolCalls.length === 0 && !messages.some((m) => m.type === "swarm_status" && m.swarmStatus?.status === "running") && (<div className="flex gap-3"><AgentAvatar /><div className="flex-1 min-w-0 flex items-center gap-2 text-xs text-muted-foreground pt-1">@@ -1151,10 +1168,16 @@ export function Agent() {)}{/* Live streaming area: text + tool status */}- {(streamingText || (status === "streaming" && toolCalls.length > 0)) && (+ {(streamingText || reasoningActive || (status === "streaming" && toolCalls.length > 0)) && (<div className="flex gap-3"><AgentAvatar /><div className="flex-1 min-w-0 space-y-1.5">+ {reasoningActive && !streamingText && (+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />+ <span>Reasoning…</span>+ </div>+ )}{streamingText && (<div className="prose prose-sm dark:prose-invert max-w-none leading-relaxed">{streamingText}diff --git a/pyproject.toml b/pyproject.tomlindex 0b272f629..bd88c1dd8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -94,6 +94,9 @@ include = ["src*", "backtest*", "cli*"]ibkr = ["ib_async>=2.0",]+deepseek = [+ "langchain-deepseek>=1.0.0,<2",+]dev = ["pytest>=7.0","pytest-cov>=4.0",