mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 04:15:43 +08:00
fix(llm): bound Claude session lifecycle and share SDK wire adaptation
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
"""Isolated, inference-free Claude SDK model discovery for both adapters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_models(rows: list) -> list[dict[str, str]]:
|
||||
models = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
value = str(row.get("value") or "").strip()
|
||||
if not value or value == "default" or row.get("disabled") or row.get("isDisabled"):
|
||||
continue
|
||||
if row.get("available") is False:
|
||||
continue
|
||||
slug = str(row.get("resolvedModel") or value).strip()
|
||||
if value.endswith("[1m]") and not slug.endswith("[1m]"):
|
||||
slug += "[1m]"
|
||||
if not slug or slug in seen:
|
||||
continue
|
||||
seen.add(slug)
|
||||
models.append({"slug": slug, "display_name": str(row.get("displayName") or slug)})
|
||||
return models
|
||||
|
||||
|
||||
async def discover_models() -> list[dict[str, str]]:
|
||||
# Keep the SDK optional; CLI-only installs retain the existing fallback.
|
||||
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient
|
||||
|
||||
options: dict[str, Any] = {
|
||||
"tools": [],
|
||||
"setting_sources": [],
|
||||
"permission_mode": "dontAsk",
|
||||
"extra_args": {"strict-mcp-config": None},
|
||||
}
|
||||
cli = shutil.which("claude")
|
||||
if cli:
|
||||
options["cli_path"] = cli
|
||||
# Do not discover project files, hooks, or MCP servers from the repo whose
|
||||
# settings page initiated sync. Authentication stays CLI-managed.
|
||||
async with asyncio.timeout(15):
|
||||
return await _discover_in_directory(ClaudeAgentOptions, ClaudeSDKClient, options)
|
||||
|
||||
|
||||
async def _discover_in_directory(ClaudeAgentOptions, ClaudeSDKClient, options):
|
||||
with tempfile.TemporaryDirectory(prefix="dt-claude-model-sdk-") as directory:
|
||||
options["cwd"] = directory
|
||||
async with ClaudeSDKClient(options=ClaudeAgentOptions(**options)) as client:
|
||||
info = await client.get_server_info() or {}
|
||||
return parse_models(info.get("models") or [])
|
||||
@@ -11,16 +11,18 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse
|
||||
from deeptutor.services.llm.provider_core.codebuddy_provider import (
|
||||
from deeptutor.services.llm.provider_core.sdk_bridge import (
|
||||
_MCP_SERVER_NAME,
|
||||
_MCP_TOOL_PREFIX,
|
||||
_consume_messages,
|
||||
@@ -75,7 +77,11 @@ class _ClaudeCodeSession:
|
||||
session._owner_loop(sdk, options, ready),
|
||||
name="claude-code-session-owner",
|
||||
)
|
||||
await ready
|
||||
try:
|
||||
await ready
|
||||
except BaseException:
|
||||
await session.close()
|
||||
raise
|
||||
return session
|
||||
|
||||
@property
|
||||
@@ -110,15 +116,19 @@ class _ClaudeCodeSession:
|
||||
except BaseException as exc:
|
||||
if not turn.future.done():
|
||||
turn.future.set_exception(exc)
|
||||
raise
|
||||
except BaseException as exc:
|
||||
if not ready.done():
|
||||
ready.set_exception(exc)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
await client.disconnect()
|
||||
except BaseException:
|
||||
pass
|
||||
while not self._ops.empty():
|
||||
pending = self._ops.get_nowait()
|
||||
if pending is not None and not pending.future.done():
|
||||
pending.future.cancel()
|
||||
with suppress(Exception):
|
||||
async with asyncio.timeout(5):
|
||||
await client.disconnect()
|
||||
|
||||
async def run_turn(
|
||||
self,
|
||||
@@ -139,11 +149,11 @@ class _ClaudeCodeSession:
|
||||
return
|
||||
self._owner = None
|
||||
if not owner.done():
|
||||
await self._ops.put(None)
|
||||
try:
|
||||
owner.cancel()
|
||||
# Cancellation reaches receive_response immediately; disconnect still
|
||||
# runs in the task that entered the SDK's anyio scopes.
|
||||
with suppress(asyncio.CancelledError, Exception):
|
||||
await owner
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _no_interrupt() -> None:
|
||||
@@ -165,6 +175,7 @@ class ClaudeCodeProvider(LLMProvider):
|
||||
self.default_model = default_model or DEFAULT_CLAUDE_CODE_MODEL
|
||||
self._sessions: OrderedDict[str, _ClaudeCodeSession] = OrderedDict()
|
||||
self._sessions_lock = asyncio.Lock()
|
||||
self._workspace = tempfile.TemporaryDirectory(prefix="dt-claude-provider-")
|
||||
|
||||
async def chat(
|
||||
self,
|
||||
@@ -222,7 +233,9 @@ class ClaudeCodeProvider(LLMProvider):
|
||||
reasoning_effort,
|
||||
on_content_delta,
|
||||
)
|
||||
options = _build_options(sdk, model, system_prompt, reasoning_effort, tools)
|
||||
options = _build_options(
|
||||
sdk, model, system_prompt, reasoning_effort, tools, cwd=self._workspace.name
|
||||
)
|
||||
stream = sdk.query(prompt=_sdk_prompt(_prompt_input(conversation)), options=options)
|
||||
try:
|
||||
return await _consume_messages(
|
||||
@@ -252,6 +265,23 @@ class ClaudeCodeProvider(LLMProvider):
|
||||
)
|
||||
try:
|
||||
async with session.lock:
|
||||
if session.messages and (
|
||||
len(conversation) <= len(session.messages)
|
||||
or conversation[: len(session.messages)] != session.messages
|
||||
):
|
||||
# Edited/regenerated history must never append to the old
|
||||
# CLI transcript. Retire it before replaying the new branch.
|
||||
await self._drop_session(session_id, session)
|
||||
return await self._run_session(
|
||||
sdk,
|
||||
session_id,
|
||||
system_prompt,
|
||||
conversation,
|
||||
tools,
|
||||
model,
|
||||
reasoning_effort,
|
||||
on_content_delta,
|
||||
)
|
||||
prompt = _prompt_input(_incremental_messages(session, conversation))
|
||||
session.messages = deepcopy(conversation)
|
||||
response = await session.run_turn(prompt, on_content_delta)
|
||||
@@ -282,14 +312,25 @@ class ClaudeCodeProvider(LLMProvider):
|
||||
self._sessions.pop(session_id, None)
|
||||
to_close.append(existing)
|
||||
|
||||
options = _build_options(sdk, model, system_prompt, reasoning_effort, tools)
|
||||
options = _build_options(
|
||||
sdk, model, system_prompt, reasoning_effort, tools, cwd=self._workspace.name
|
||||
)
|
||||
session = await _ClaudeCodeSession.start(
|
||||
sdk=sdk, signature=signature, options=options
|
||||
)
|
||||
self._sessions[session_id] = session
|
||||
while len(self._sessions) > _SESSION_POOL_MAXSIZE:
|
||||
_, evicted = self._sessions.popitem(last=False)
|
||||
to_close.append(evicted)
|
||||
idle_key = next(
|
||||
(
|
||||
key
|
||||
for key, item in self._sessions.items()
|
||||
if key != session_id and not item.lock.locked()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if idle_key is None:
|
||||
break
|
||||
to_close.append(self._sessions.pop(idle_key))
|
||||
return session
|
||||
finally:
|
||||
for stale in to_close:
|
||||
@@ -306,14 +347,8 @@ class ClaudeCodeProvider(LLMProvider):
|
||||
sessions = list(self._sessions.values())
|
||||
self._sessions.clear()
|
||||
for session in sessions:
|
||||
try:
|
||||
await session.close()
|
||||
except asyncio.CancelledError:
|
||||
task = asyncio.current_task()
|
||||
if task is not None:
|
||||
task.uncancel()
|
||||
except Exception:
|
||||
pass
|
||||
await session.close()
|
||||
self._workspace.cleanup()
|
||||
|
||||
def get_default_model(self) -> str:
|
||||
return self.default_model
|
||||
@@ -325,7 +360,8 @@ def _load_sdk() -> ModuleType:
|
||||
except ImportError as exc: # pragma: no cover - optional dependency
|
||||
raise RuntimeError(
|
||||
"claude-agent-sdk is not installed. Install it with "
|
||||
"`python -m pip install claude-agent-sdk` or `pip install -e .[claude-code]`."
|
||||
"`python scripts/install_extras.py claude-code` in a source checkout, "
|
||||
'or `python -m pip install "deeptutor[claude-code]"` for a wheel installation.'
|
||||
) from exc
|
||||
return claude_agent_sdk
|
||||
|
||||
@@ -464,6 +500,8 @@ def _build_options(
|
||||
system_prompt: str,
|
||||
reasoning_effort: str | None,
|
||||
tools: list[dict[str, Any]] | None,
|
||||
*,
|
||||
cwd: str,
|
||||
) -> Any:
|
||||
stripped_model = _strip_model_prefix(model)
|
||||
return sdk.ClaudeAgentOptions(
|
||||
@@ -471,6 +509,9 @@ def _build_options(
|
||||
system_prompt=system_prompt,
|
||||
# No built-in Claude Code tools and none of the operator's settings,
|
||||
# CLAUDE.md files, hooks or plugins: this is a plain model endpoint.
|
||||
cwd=cwd,
|
||||
permission_mode="dontAsk",
|
||||
extra_args={"strict-mcp-config": None},
|
||||
tools=[],
|
||||
setting_sources=[],
|
||||
max_turns=1,
|
||||
@@ -555,35 +596,21 @@ async def fetch_claude_code_catalog() -> list[dict[str, str]]:
|
||||
default, but managed or user settings may pin a different model at run time.
|
||||
Falls back to the bare aliases when the CLI cannot be started.
|
||||
"""
|
||||
from deeptutor.services.llm.claude_sdk import discover_models
|
||||
|
||||
try:
|
||||
sdk = _load_sdk()
|
||||
client = sdk.ClaudeSDKClient(
|
||||
options=sdk.ClaudeAgentOptions(tools=[], setting_sources=[], max_turns=1)
|
||||
)
|
||||
await client.connect()
|
||||
try:
|
||||
info = await client.get_server_info() or {}
|
||||
finally:
|
||||
await client.disconnect()
|
||||
models = info.get("models") or []
|
||||
models = await discover_models()
|
||||
except Exception as exc:
|
||||
logger.warning("Claude Code model catalog unavailable (%s)", type(exc).__name__)
|
||||
models = []
|
||||
|
||||
catalog: list[dict[str, str]] = []
|
||||
for entry in models:
|
||||
value = str(entry.get("value") or "").strip() if isinstance(entry, dict) else ""
|
||||
if not value:
|
||||
continue
|
||||
name = (
|
||||
"Default (account setting)"
|
||||
if value == "default"
|
||||
else str(entry.get("displayName") or value)
|
||||
)
|
||||
catalog.append({"id": f"claude-code/{value}", "name": name})
|
||||
if not catalog:
|
||||
catalog = [{"id": f"claude-code/{name}", "name": name} for name in CLAUDE_CODE_MODELS]
|
||||
return catalog
|
||||
if not models:
|
||||
models = [
|
||||
{"slug": name, "display_name": name} for name in CLAUDE_CODE_MODELS if name != "default"
|
||||
]
|
||||
return [
|
||||
{"id": "claude-code/default", "name": "Default (account setting)"},
|
||||
*[{"id": f"claude-code/{row['slug']}", "name": row["display_name"]} for row in models],
|
||||
]
|
||||
|
||||
|
||||
async def fetch_claude_code_models() -> list[str]:
|
||||
|
||||
@@ -20,15 +20,20 @@ from typing import Any
|
||||
from deeptutor.services.llm.provider_core.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from deeptutor.services.llm.provider_core.sdk_bridge import (
|
||||
_MCP_SERVER_NAME,
|
||||
_MCP_TOOL_PREFIX,
|
||||
_consume_messages,
|
||||
_content_text,
|
||||
_messages_to_prompt,
|
||||
_reasoning_options,
|
||||
)
|
||||
|
||||
DEFAULT_CODEBUDDY_MODEL = "codebuddy/hy3"
|
||||
_CODEBUDDY_API_KEY_ENV = "CODEBUDDY_API_KEY"
|
||||
_API_KEY_ENV_LOCK = asyncio.Lock()
|
||||
_SESSION_POOL_MAXSIZE = 4
|
||||
_MCP_SERVER_NAME = "deeptutor"
|
||||
_MCP_TOOL_PREFIX = f"mcp__{_MCP_SERVER_NAME}__"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -524,122 +529,6 @@ def _incremental_prompt(
|
||||
return _messages_to_prompt(messages)
|
||||
|
||||
|
||||
async def _consume_messages(
|
||||
messages: Any,
|
||||
*,
|
||||
on_content_delta: Callable[[str], Awaitable[None]] | None,
|
||||
interrupt: Callable[[], Awaitable[None]] | None = None,
|
||||
label: str = "CodeBuddy",
|
||||
) -> LLMResponse:
|
||||
chunks: list[str] = []
|
||||
pending_result_text = ""
|
||||
async for message in messages:
|
||||
if _is_error_result(message):
|
||||
return LLMResponse(
|
||||
content=f"Error calling {label}: {_result_text(message)}",
|
||||
finish_reason="error",
|
||||
)
|
||||
if _is_result_message(message):
|
||||
pending_result_text = _result_text(message)
|
||||
continue
|
||||
|
||||
tool_calls = _assistant_tool_calls(message)
|
||||
text = _assistant_text(message)
|
||||
if text:
|
||||
chunks.append(text)
|
||||
if on_content_delta:
|
||||
await on_content_delta(text)
|
||||
if tool_calls:
|
||||
if interrupt is not None:
|
||||
try:
|
||||
await interrupt()
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"%s interrupt after tool calls failed (%s); "
|
||||
"background generation may keep running",
|
||||
label,
|
||||
type(exc).__name__,
|
||||
)
|
||||
else:
|
||||
await _drain_interrupted_response(messages)
|
||||
return LLMResponse(
|
||||
content="".join(chunks),
|
||||
tool_calls=tool_calls,
|
||||
finish_reason="tool_calls",
|
||||
)
|
||||
|
||||
if not chunks and pending_result_text:
|
||||
chunks.append(pending_result_text)
|
||||
if on_content_delta:
|
||||
await on_content_delta(pending_result_text)
|
||||
return LLMResponse(content="".join(chunks), finish_reason="stop")
|
||||
|
||||
|
||||
async def _drain_interrupted_response(messages: Any) -> None:
|
||||
"""Consume the SDK's interrupt result so it cannot leak into the next turn."""
|
||||
try:
|
||||
async for message in messages:
|
||||
if _is_result_message(message) or type(message).__name__ == "ErrorMessage":
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"CodeBuddy interrupted response drain failed (%s); "
|
||||
"stale SDK messages may surface in the next turn",
|
||||
type(exc).__name__,
|
||||
)
|
||||
|
||||
|
||||
def _assistant_tool_calls(message: Any) -> list[ToolCallRequest]:
|
||||
content = getattr(message, "content", None)
|
||||
if content is None and isinstance(message, dict):
|
||||
content = message.get("content")
|
||||
if not isinstance(content, list):
|
||||
return []
|
||||
|
||||
calls: list[ToolCallRequest] = []
|
||||
for block in content:
|
||||
if isinstance(block, dict):
|
||||
block_type = str(block.get("type") or "").lower()
|
||||
name = str(block.get("name") or "")
|
||||
call_id = str(block.get("id") or "")
|
||||
arguments = block.get("input")
|
||||
else:
|
||||
block_type = type(block).__name__.lower()
|
||||
name = str(getattr(block, "name", "") or "")
|
||||
call_id = str(getattr(block, "id", "") or "")
|
||||
arguments = getattr(block, "input", None)
|
||||
if block_type not in {"tool_use", "tooluse"} and not block_type.endswith("tooluseblock"):
|
||||
continue
|
||||
if not name.startswith(_MCP_TOOL_PREFIX):
|
||||
continue
|
||||
tool_name = name[len(_MCP_TOOL_PREFIX) :]
|
||||
if not tool_name:
|
||||
continue
|
||||
calls.append(
|
||||
ToolCallRequest(
|
||||
id=call_id or f"codebuddy_tool_{len(calls)}",
|
||||
name=tool_name,
|
||||
arguments=arguments if isinstance(arguments, dict) else {},
|
||||
)
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _reasoning_options(reasoning_effort: str | None) -> dict[str, Any]:
|
||||
"""Map DeepTutor reasoning levels to CodeBuddy SDK thinking controls.
|
||||
|
||||
The SDK enables adaptive thinking when the field is omitted, unlike the
|
||||
local CodeBuddy CLI configuration. Defaulting to disabled keeps ordinary
|
||||
chat latency aligned with the CLI; an explicit effort turns it back on.
|
||||
"""
|
||||
effort = (reasoning_effort or "").strip().lower()
|
||||
if effort in {"low", "medium", "high", "xhigh"}:
|
||||
return {"thinking": {"type": "adaptive"}, "effort": effort}
|
||||
if effort == "adaptive":
|
||||
return {"thinking": {"type": "adaptive"}}
|
||||
return {"thinking": {"type": "disabled"}}
|
||||
|
||||
|
||||
def _options_has_api_key_env(options: Any | None) -> bool:
|
||||
if options is None:
|
||||
return False
|
||||
@@ -653,113 +542,6 @@ def _options_has_api_key_env(options: Any | None) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
|
||||
sections: list[str] = []
|
||||
for message in messages:
|
||||
role = str(message.get("role") or "user").strip() or "user"
|
||||
content = _content_text(message.get("content"))
|
||||
if not content:
|
||||
continue
|
||||
if role == "system":
|
||||
heading = "System instructions"
|
||||
elif role == "assistant":
|
||||
heading = "Assistant"
|
||||
elif role == "tool":
|
||||
name = message.get("name") or message.get("tool_call_id") or "tool"
|
||||
heading = f"Tool result ({name})"
|
||||
else:
|
||||
heading = "User"
|
||||
sections.append(f"{heading}:\n{content}")
|
||||
|
||||
return "\n\n".join(sections) if sections else ""
|
||||
|
||||
|
||||
def _content_text(content: Any) -> str:
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, dict):
|
||||
return _content_part_text(content)
|
||||
if isinstance(content, list):
|
||||
parts = [_content_part_text(part) for part in content]
|
||||
return "\n".join(part for part in parts if part)
|
||||
return str(content)
|
||||
|
||||
|
||||
def _content_part_text(part: Any) -> str:
|
||||
if isinstance(part, str):
|
||||
return part
|
||||
if not isinstance(part, dict):
|
||||
return str(part)
|
||||
part_type = part.get("type")
|
||||
if part_type in {"text", "input_text", "output_text"}:
|
||||
return str(part.get("text") or "")
|
||||
if "text" in part and isinstance(part.get("text"), str):
|
||||
return str(part["text"])
|
||||
if part_type in {"image_url", "input_image"}:
|
||||
return "[image input omitted]"
|
||||
return ""
|
||||
|
||||
|
||||
def _assistant_text(message: Any) -> str:
|
||||
content = getattr(message, "content", None)
|
||||
if content is None and isinstance(message, dict):
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if not isinstance(content, list):
|
||||
content = [content]
|
||||
|
||||
chunks: list[str] = []
|
||||
for block in content:
|
||||
text = _block_text(block)
|
||||
if text:
|
||||
chunks.append(text)
|
||||
return "".join(chunks)
|
||||
|
||||
|
||||
def _block_text(block: Any) -> str:
|
||||
if isinstance(block, str):
|
||||
return block
|
||||
if isinstance(block, dict):
|
||||
block_type = block.get("type")
|
||||
if block_type in {"text", "assistant_text"} or "text" in block:
|
||||
return str(block.get("text") or "")
|
||||
return ""
|
||||
block_type = type(block).__name__
|
||||
if block_type == "TextBlock" or hasattr(block, "text"):
|
||||
return str(getattr(block, "text") or "")
|
||||
return ""
|
||||
|
||||
|
||||
def _is_result_message(message: Any) -> bool:
|
||||
message_type = type(message).__name__
|
||||
if message_type == "ResultMessage" or message_type.endswith("ResultMessage"):
|
||||
return True
|
||||
if hasattr(message, "result") and hasattr(message, "is_error"):
|
||||
return True
|
||||
return isinstance(message, dict) and str(message.get("type") or "").lower() == "result"
|
||||
|
||||
|
||||
def _is_error_result(message: Any) -> bool:
|
||||
if not _is_result_message(message):
|
||||
return False
|
||||
if isinstance(message, dict):
|
||||
return bool(message.get("is_error") or message.get("error"))
|
||||
return bool(getattr(message, "is_error", False) or getattr(message, "error", None))
|
||||
|
||||
|
||||
def _result_text(message: Any) -> str:
|
||||
if isinstance(message, dict):
|
||||
value = message.get("result") or message.get("error") or message.get("content")
|
||||
else:
|
||||
value = getattr(message, "result", None) or getattr(message, "error", None)
|
||||
return "" if value is None else str(value)
|
||||
|
||||
|
||||
def _friendly_error(exc: Exception) -> str:
|
||||
message = str(exc)
|
||||
if "Authentication required" in message:
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Wire adaptation shared by local agent SDK model providers.
|
||||
|
||||
SDK lifecycle and authentication stay with each provider. This module only
|
||||
translates prompts, streamed messages and DeepTutor-owned MCP tool calls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from .base import LLMResponse, ToolCallRequest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_MCP_SERVER_NAME = "deeptutor"
|
||||
_MCP_TOOL_PREFIX = f"mcp__{_MCP_SERVER_NAME}__"
|
||||
|
||||
|
||||
async def _consume_messages(
|
||||
messages: Any,
|
||||
*,
|
||||
on_content_delta: Callable[[str], Awaitable[None]] | None,
|
||||
interrupt: Callable[[], Awaitable[None]] | None = None,
|
||||
label: str = "CodeBuddy",
|
||||
) -> LLMResponse:
|
||||
chunks: list[str] = []
|
||||
pending_result_text = ""
|
||||
async for message in messages:
|
||||
if _is_error_result(message):
|
||||
return LLMResponse(
|
||||
content=f"Error calling {label}: {_result_text(message)}",
|
||||
finish_reason="error",
|
||||
)
|
||||
if _is_result_message(message):
|
||||
pending_result_text = _result_text(message)
|
||||
continue
|
||||
|
||||
tool_calls = _assistant_tool_calls(message)
|
||||
text = _assistant_text(message)
|
||||
if text:
|
||||
chunks.append(text)
|
||||
if on_content_delta:
|
||||
await on_content_delta(text)
|
||||
if tool_calls:
|
||||
if interrupt is not None:
|
||||
try:
|
||||
await interrupt()
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"%s interrupt after tool calls failed (%s); "
|
||||
"background generation may keep running",
|
||||
label,
|
||||
type(exc).__name__,
|
||||
)
|
||||
else:
|
||||
await _drain_interrupted_response(messages, label=label)
|
||||
return LLMResponse(
|
||||
content="".join(chunks),
|
||||
tool_calls=tool_calls,
|
||||
finish_reason="tool_calls",
|
||||
)
|
||||
|
||||
if not chunks and pending_result_text:
|
||||
chunks.append(pending_result_text)
|
||||
if on_content_delta:
|
||||
await on_content_delta(pending_result_text)
|
||||
return LLMResponse(content="".join(chunks), finish_reason="stop")
|
||||
|
||||
|
||||
async def _drain_interrupted_response(messages: Any, *, label: str = "CodeBuddy") -> None:
|
||||
"""Consume the SDK's interrupt result so it cannot leak into the next turn."""
|
||||
try:
|
||||
async for message in messages:
|
||||
if _is_result_message(message) or type(message).__name__ == "ErrorMessage":
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"%s interrupted response drain failed (%s); "
|
||||
"stale SDK messages may surface in the next turn",
|
||||
label,
|
||||
type(exc).__name__,
|
||||
)
|
||||
|
||||
|
||||
def _assistant_tool_calls(message: Any) -> list[ToolCallRequest]:
|
||||
content = getattr(message, "content", None)
|
||||
if content is None and isinstance(message, dict):
|
||||
content = message.get("content")
|
||||
if not isinstance(content, list):
|
||||
return []
|
||||
|
||||
calls: list[ToolCallRequest] = []
|
||||
for block in content:
|
||||
if isinstance(block, dict):
|
||||
block_type = str(block.get("type") or "").lower()
|
||||
name = str(block.get("name") or "")
|
||||
call_id = str(block.get("id") or "")
|
||||
arguments = block.get("input")
|
||||
else:
|
||||
block_type = type(block).__name__.lower()
|
||||
name = str(getattr(block, "name", "") or "")
|
||||
call_id = str(getattr(block, "id", "") or "")
|
||||
arguments = getattr(block, "input", None)
|
||||
if block_type not in {"tool_use", "tooluse"} and not block_type.endswith("tooluseblock"):
|
||||
continue
|
||||
if not name.startswith(_MCP_TOOL_PREFIX):
|
||||
continue
|
||||
tool_name = name[len(_MCP_TOOL_PREFIX) :]
|
||||
if not tool_name:
|
||||
continue
|
||||
calls.append(
|
||||
ToolCallRequest(
|
||||
id=call_id or f"codebuddy_tool_{len(calls)}",
|
||||
name=tool_name,
|
||||
arguments=arguments if isinstance(arguments, dict) else {},
|
||||
)
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _reasoning_options(reasoning_effort: str | None) -> dict[str, Any]:
|
||||
"""Map DeepTutor reasoning levels to CodeBuddy SDK thinking controls.
|
||||
|
||||
The SDK enables adaptive thinking when the field is omitted, unlike the
|
||||
local CodeBuddy CLI configuration. Defaulting to disabled keeps ordinary
|
||||
chat latency aligned with the CLI; an explicit effort turns it back on.
|
||||
"""
|
||||
effort = (reasoning_effort or "").strip().lower()
|
||||
if effort in {"low", "medium", "high", "xhigh"}:
|
||||
return {"thinking": {"type": "adaptive"}, "effort": effort}
|
||||
if effort == "adaptive":
|
||||
return {"thinking": {"type": "adaptive"}}
|
||||
return {"thinking": {"type": "disabled"}}
|
||||
|
||||
|
||||
def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
|
||||
sections: list[str] = []
|
||||
for message in messages:
|
||||
role = str(message.get("role") or "user").strip() or "user"
|
||||
content = _content_text(message.get("content"))
|
||||
if not content:
|
||||
continue
|
||||
if role == "system":
|
||||
heading = "System instructions"
|
||||
elif role == "assistant":
|
||||
heading = "Assistant"
|
||||
elif role == "tool":
|
||||
name = message.get("name") or message.get("tool_call_id") or "tool"
|
||||
heading = f"Tool result ({name})"
|
||||
else:
|
||||
heading = "User"
|
||||
sections.append(f"{heading}:\n{content}")
|
||||
|
||||
return "\n\n".join(sections) if sections else ""
|
||||
|
||||
|
||||
def _content_text(content: Any) -> str:
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, dict):
|
||||
return _content_part_text(content)
|
||||
if isinstance(content, list):
|
||||
parts = [_content_part_text(part) for part in content]
|
||||
return "\n".join(part for part in parts if part)
|
||||
return str(content)
|
||||
|
||||
|
||||
def _content_part_text(part: Any) -> str:
|
||||
if isinstance(part, str):
|
||||
return part
|
||||
if not isinstance(part, dict):
|
||||
return str(part)
|
||||
part_type = part.get("type")
|
||||
if part_type in {"text", "input_text", "output_text"}:
|
||||
return str(part.get("text") or "")
|
||||
if "text" in part and isinstance(part.get("text"), str):
|
||||
return str(part["text"])
|
||||
if part_type in {"image_url", "input_image"}:
|
||||
return "[image input omitted]"
|
||||
return ""
|
||||
|
||||
|
||||
def _assistant_text(message: Any) -> str:
|
||||
content = getattr(message, "content", None)
|
||||
if content is None and isinstance(message, dict):
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if not isinstance(content, list):
|
||||
content = [content]
|
||||
|
||||
chunks: list[str] = []
|
||||
for block in content:
|
||||
text = _block_text(block)
|
||||
if text:
|
||||
chunks.append(text)
|
||||
return "".join(chunks)
|
||||
|
||||
|
||||
def _block_text(block: Any) -> str:
|
||||
if isinstance(block, str):
|
||||
return block
|
||||
if isinstance(block, dict):
|
||||
block_type = block.get("type")
|
||||
if block_type in {"text", "assistant_text"} or "text" in block:
|
||||
return str(block.get("text") or "")
|
||||
return ""
|
||||
block_type = type(block).__name__
|
||||
if block_type == "TextBlock" or hasattr(block, "text"):
|
||||
return str(getattr(block, "text") or "")
|
||||
return ""
|
||||
|
||||
|
||||
def _is_result_message(message: Any) -> bool:
|
||||
message_type = type(message).__name__
|
||||
if message_type == "ResultMessage" or message_type.endswith("ResultMessage"):
|
||||
return True
|
||||
if hasattr(message, "result") and hasattr(message, "is_error"):
|
||||
return True
|
||||
return isinstance(message, dict) and str(message.get("type") or "").lower() == "result"
|
||||
|
||||
|
||||
def _is_error_result(message: Any) -> bool:
|
||||
if not _is_result_message(message):
|
||||
return False
|
||||
if isinstance(message, dict):
|
||||
return bool(message.get("is_error") or message.get("error"))
|
||||
return bool(getattr(message, "is_error", False) or getattr(message, "error", None))
|
||||
|
||||
|
||||
def _result_text(message: Any) -> str:
|
||||
if isinstance(message, dict):
|
||||
value = message.get("result") or message.get("error") or message.get("content")
|
||||
else:
|
||||
value = getattr(message, "result", None) or getattr(message, "error", None)
|
||||
return "" if value is None else str(value)
|
||||
@@ -21,7 +21,6 @@ import shutil
|
||||
import signal
|
||||
import tempfile
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.services.path_service import get_path_service
|
||||
|
||||
@@ -99,47 +98,10 @@ async def sync_claude_models() -> tuple[list[dict[str, str]], str]:
|
||||
return models, fetched_at
|
||||
|
||||
|
||||
def _parse_sdk_models(rows: list) -> list[dict[str, str]]:
|
||||
models = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
value = str(row.get("value") or "").strip()
|
||||
if not value or value == "default" or row.get("disabled") or row.get("isDisabled"):
|
||||
continue
|
||||
if row.get("available") is False:
|
||||
continue
|
||||
slug = str(row.get("resolvedModel") or value).strip()
|
||||
if value.endswith("[1m]") and not slug.endswith("[1m]"):
|
||||
slug += "[1m]"
|
||||
if not slug or slug in seen:
|
||||
continue
|
||||
seen.add(slug)
|
||||
models.append({"slug": slug, "display_name": str(row.get("displayName") or slug)})
|
||||
return models
|
||||
|
||||
|
||||
async def _discover_sdk_models() -> list[dict[str, str]]:
|
||||
# Keep the SDK optional; CLI-only installs retain the existing fallback.
|
||||
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient
|
||||
from deeptutor.services.llm.claude_sdk import discover_models
|
||||
|
||||
options: dict[str, Any] = {
|
||||
"tools": [],
|
||||
"setting_sources": [],
|
||||
"permission_mode": "dontAsk",
|
||||
"extra_args": {"strict-mcp-config": None},
|
||||
}
|
||||
cli = shutil.which("claude")
|
||||
if cli:
|
||||
options["cli_path"] = cli
|
||||
# Do not discover project files, hooks, or MCP servers from the repo whose
|
||||
# settings page initiated sync. Authentication stays CLI-managed.
|
||||
with tempfile.TemporaryDirectory(prefix="dt-claude-model-sdk-") as directory:
|
||||
options["cwd"] = directory
|
||||
async with ClaudeSDKClient(options=ClaudeAgentOptions(**options)) as client:
|
||||
info = await client.get_server_info() or {}
|
||||
return _parse_sdk_models(info.get("models") or [])
|
||||
return await discover_models()
|
||||
|
||||
|
||||
def _write_cache(models: list[dict[str, str]], fetched_at: str) -> None:
|
||||
@@ -282,7 +244,6 @@ def _capture_model_screen() -> str | None:
|
||||
|
||||
|
||||
def _cleanup_dir(path: str) -> None:
|
||||
import shutil
|
||||
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -65,7 +66,14 @@ class FakeClient:
|
||||
FakeClient.instances.append(self)
|
||||
|
||||
async def connect(self):
|
||||
return None
|
||||
self.owner = asyncio.current_task()
|
||||
|
||||
async def __aenter__(self):
|
||||
await self.connect()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await self.disconnect()
|
||||
|
||||
async def query(self, prompt):
|
||||
if not isinstance(prompt, str):
|
||||
@@ -80,6 +88,7 @@ class FakeClient:
|
||||
self.interrupts += 1
|
||||
|
||||
async def disconnect(self):
|
||||
assert self.owner is asyncio.current_task()
|
||||
self.disconnected = True
|
||||
|
||||
|
||||
@@ -365,3 +374,46 @@ async def test_session_sends_only_new_image_message_as_blocks(monkeypatch) -> No
|
||||
},
|
||||
]
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_active_stream_closes_in_owner_task(monkeypatch):
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def blocked_response(self):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
yield FakeResultMessage("unreachable")
|
||||
|
||||
monkeypatch.setattr(FakeClient, "receive_response", blocked_response)
|
||||
_install_fake_sdk(monkeypatch)
|
||||
provider = ClaudeCodeProvider()
|
||||
task = asyncio.create_task(
|
||||
provider.chat(
|
||||
[{"role": "user", "content": "Wait"}],
|
||||
deeptutor_session_id="cancel",
|
||||
)
|
||||
)
|
||||
await asyncio.wait_for(entered.wait(), 1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, 1)
|
||||
assert FakeClient.instances[0].disconnected
|
||||
assert not provider._sessions
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regeneration_replaces_old_cli_transcript(monkeypatch):
|
||||
_install_fake_sdk(monkeypatch)
|
||||
FakeClient.script = [[FakeResultMessage("one")], [FakeResultMessage("two")]]
|
||||
provider = ClaudeCodeProvider()
|
||||
await provider.chat([{"role": "user", "content": "Original"}], deeptutor_session_id="branch")
|
||||
await provider.chat([{"role": "user", "content": "Edited"}], deeptutor_session_id="branch")
|
||||
assert len(FakeClient.instances) == 2
|
||||
assert FakeClient.instances[0].disconnected
|
||||
assert FakeClient.instances[1].prompts == ["User:\nEdited"]
|
||||
options = FakeClient.instances[1].options.kwargs
|
||||
assert options["permission_mode"] == "dontAsk"
|
||||
assert options["extra_args"] == {"strict-mcp-config": None}
|
||||
await provider.aclose()
|
||||
|
||||
@@ -465,7 +465,7 @@ async def test_codebuddy_interrupt_failure_after_tool_calls_logs_warning(
|
||||
|
||||
with caplog.at_level(
|
||||
logging.WARNING,
|
||||
logger="deeptutor.services.llm.provider_core.codebuddy_provider",
|
||||
logger="deeptutor.services.llm.provider_core.sdk_bridge",
|
||||
):
|
||||
response = await provider.chat(
|
||||
[{"role": "user", "content": "Search"}],
|
||||
@@ -479,7 +479,7 @@ async def test_codebuddy_interrupt_failure_after_tool_calls_logs_warning(
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.WARNING
|
||||
and r.name == "deeptutor.services.llm.provider_core.codebuddy_provider"
|
||||
and r.name == "deeptutor.services.llm.provider_core.sdk_bridge"
|
||||
]
|
||||
assert any(
|
||||
"interrupt" in r.getMessage().lower() and "RuntimeError" in r.getMessage() for r in warnings
|
||||
@@ -561,7 +561,7 @@ async def _append_async(items: list[str], text: str) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_interrupted_drain_logs_error_type_without_exception_body(caplog):
|
||||
from deeptutor.services.llm.provider_core.codebuddy_provider import _drain_interrupted_response
|
||||
from deeptutor.services.llm.provider_core.sdk_bridge import _drain_interrupted_response
|
||||
|
||||
async def broken_stream():
|
||||
yield {"type": "intermediate"}
|
||||
|
||||
@@ -5,6 +5,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.llm import claude_sdk
|
||||
from deeptutor.services.subagent import claude_models as module
|
||||
|
||||
ROWS = [
|
||||
@@ -24,7 +25,7 @@ ROWS = [
|
||||
|
||||
|
||||
def test_sdk_catalog_keeps_all_versions_and_context_variants():
|
||||
models = module._parse_sdk_models([*ROWS, ROWS[1], {}, "invalid"])
|
||||
models = claude_sdk.parse_models([*ROWS, ROWS[1], {}, "invalid"])
|
||||
assert [m["slug"] for m in models] == [
|
||||
"claude-opus-test",
|
||||
"claude-fable-test",
|
||||
@@ -64,14 +65,14 @@ def sdk(monkeypatch):
|
||||
"claude_agent_sdk",
|
||||
SimpleNamespace(ClaudeSDKClient=Client, ClaudeAgentOptions=lambda **kw: kw),
|
||||
)
|
||||
monkeypatch.setattr(module.shutil, "which", lambda command: "/native/claude")
|
||||
monkeypatch.setattr(claude_sdk.shutil, "which", lambda command: "/native/claude")
|
||||
return state
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sdk_discovery_closes_in_owner_task_and_does_not_return_account_data(sdk):
|
||||
models = await module._discover_sdk_models()
|
||||
assert models == module._parse_sdk_models(ROWS)
|
||||
assert models == claude_sdk.parse_models(ROWS)
|
||||
assert sdk.closed
|
||||
assert sdk.options["cli_path"] == "/native/claude"
|
||||
assert sdk.options["tools"] == []
|
||||
@@ -100,7 +101,7 @@ def cache(monkeypatch, tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_sdk_sync_caches_results_without_starting_terminal_capture(monkeypatch, cache):
|
||||
async def discover():
|
||||
return module._parse_sdk_models(ROWS)
|
||||
return claude_sdk.parse_models(ROWS)
|
||||
|
||||
monkeypatch.setattr(module, "_discover_sdk_models", discover)
|
||||
monkeypatch.setattr(
|
||||
|
||||
Reference in New Issue
Block a user