Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion chat_shell/chat_shell/tools/mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def build_connections(
config = replace_mcp_server_variables(config, task_data)
logger.debug(
"[MCP] Applied variable substitution to MCP config with task_data keys: %s",
task_data,
sorted(task_data.keys()),
)

connections = {}
Expand Down
43 changes: 33 additions & 10 deletions executor/agents/claude_code/claude_code_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@

logger = setup_logger("claude_code_agent")

INTERRUPT_TIMEOUT_SECONDS = 5.0
DISCONNECT_TIMEOUT_SECONDS = 2.0
Comment on lines +66 to +67

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Duplicated timeout constants — define them in one place.

INTERRUPT_TIMEOUT_SECONDS and DISCONNECT_TIMEOUT_SECONDS are declared identically in both this file and session_manager.py (Lines 24-25). Moreover, each file only uses one of the two constants it defines:

  • This file uses INTERRUPT_TIMEOUT_SECONDS (Line 1024) but never DISCONNECT_TIMEOUT_SECONDS.
  • session_manager.py uses DISCONNECT_TIMEOUT_SECONDS (Line 239) but never INTERRUPT_TIMEOUT_SECONDS.

Define them once in session_manager.py and import here, to avoid drift.

♻️ Suggested fix

In this file, replace the local constants with an import:

-INTERRUPT_TIMEOUT_SECONDS = 5.0
-DISCONNECT_TIMEOUT_SECONDS = 2.0
+from executor.agents.claude_code.session_manager import INTERRUPT_TIMEOUT_SECONDS
🤖 Prompt for AI Agents
In `@executor/agents/claude_code/claude_code_agent.py` around lines 66 - 67,
Replace the duplicated timeout constants by removing INTERRUPT_TIMEOUT_SECONDS
and DISCONNECT_TIMEOUT_SECONDS definitions from claude_code_agent.py and import
the single source of truth from session_manager (use the existing
DISCONNECT_TIMEOUT_SECONDS/INTERRUPT_TIMEOUT_SECONDS definitions there); update
claude_code_agent.py to import INTERRUPT_TIMEOUT_SECONDS from session_manager
and delete the unused local DISCONNECT_TIMEOUT_SECONDS constant so each constant
is defined only in session_manager and used via import in claude_code_agent.py.



def _extract_claude_agent_attributes(self, *args, **kwargs) -> Dict[str, Any]:
"""Extract trace attributes from ClaudeCodeAgent instance."""
Expand Down Expand Up @@ -576,10 +579,13 @@ async def _async_execute(self) -> TaskStatus:
TaskStatus: Execution status
"""
try:
# Check if task was cancelled before execution
if self.task_state_manager.is_cancelled(self.task_id):
logger.info(f"Task {self.task_id} was cancelled before execution")
return TaskStatus.COMPLETED
# Soft-cancel: cancellation should only interrupt the current operation.
# If a previous run was cancelled, allow follow-up messages to execute normally.
if self.task_state_manager.get_state(self.task_id) == TaskState.CANCELLED:
logger.info(
f"Task {self.task_id} was previously cancelled; resetting state to RUNNING for new execution"
)
self.task_state_manager.set_state(self.task_id, TaskState.RUNNING)

progress = 65
# Update current progress
Expand Down Expand Up @@ -1013,12 +1019,29 @@ async def _async_cancel_run(self) -> None:
"""
try:
if self.client is not None:
await self.client.interrupt()
# Note: No longer send callback here
# Callback will be sent asynchronously by background task in main.py
logger.info(
f"Successfully sent interrupt to client for session_id: {self.session_id}"
)
try:
await asyncio.wait_for(
self.client.interrupt(), timeout=INTERRUPT_TIMEOUT_SECONDS
)
# Note: No longer send callback here
# Callback will be sent asynchronously by background task in main.py
logger.info(
f"Successfully sent interrupt to client for session_id: {self.session_id}"
)
return
except asyncio.TimeoutError:
logger.warning(
f"Interrupt timed out after {INTERRUPT_TIMEOUT_SECONDS}s for task_id={self.task_id}, "
f"session_id={self.session_id}; forcing process cleanup"
)
except Exception as interrupt_error:
logger.exception(
f"Interrupt failed for task_id={self.task_id}, session_id={self.session_id}: {interrupt_error}. "
"Forcing process cleanup"
)

await type(self).cleanup_task_clients(self.task_id)
self.client = None
except Exception as e:
logger.exception(
f"Error during async interrupt for session_id {self.session_id}: {str(e)}"
Expand Down
6 changes: 5 additions & 1 deletion executor/agents/claude_code/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from shared.logger import setup_logger
from shared.utils.crypto import decrypt_sensitive_data, is_data_encrypted
from shared.utils.sensitive_data_masker import mask_sensitive_data

logger = setup_logger("claude_code_config_manager")

Expand Down Expand Up @@ -273,7 +274,10 @@ def extract_claude_options(task_data: Dict[str, Any]) -> Dict[str, Any]:
if mcp_servers:
# Replace placeholders in MCP servers config with actual values
mcp_servers = replace_mcp_server_variables(mcp_servers, task_data)
logger.info(f"Detected MCP servers configuration: {mcp_servers}")
logger.info(
"Detected MCP servers configuration (masked): %s",
mask_sensitive_data(mcp_servers),
)
bot_config["mcp_servers"] = mcp_servers

# Add wegent MCP server for subscription tasks
Expand Down
57 changes: 54 additions & 3 deletions executor/agents/claude_code/response_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ async def process_response(

if isinstance(msg, SystemMessage):
# Handle SystemMessage
_handle_system_message(msg, state_manager, thinking_manager)
terminal_status = _handle_system_message(
msg, state_manager, thinking_manager
)
if terminal_status:
return terminal_status

elif isinstance(msg, UserMessage):
# Handle UserMessage and check for silent_exit in tool results
Expand Down Expand Up @@ -169,6 +173,16 @@ async def process_response(

return TaskStatus.RUNNING
except Exception as e:
task_id = state_manager.task_data.get("task_id") if state_manager else None
if task_state_manager and task_id and task_state_manager.is_cancelled(task_id):
logger.info(
f"Response processing interrupted by cancellation for task_id={task_id}: {e}",
exc_info=True,
)
if state_manager:
state_manager.update_workbench_status("completed")
return TaskStatus.COMPLETED

logger.exception(f"Error processing response: {str(e)}")

# Add thinking step for error
Expand All @@ -191,7 +205,9 @@ async def process_response(
return TaskStatus.FAILED


def _handle_system_message(msg: SystemMessage, state_manager, thinking_manager=None):
def _handle_system_message(
msg: SystemMessage, state_manager, thinking_manager=None
) -> Optional[TaskStatus]:
"""处理系统消息,提取详细信息"""

# 构建系统消息的详细信息,符合目标格式
Expand Down Expand Up @@ -219,6 +235,39 @@ def _handle_system_message(msg: SystemMessage, state_manager, thinking_manager=N
details=masked_system_detail,
)

if msg.subtype == "error_during_execution":
error_text = (
msg.data.get("message")
or msg.data.get("error")
or msg.data.get("detail")
or json.dumps(masked_system_detail, ensure_ascii=False)
)

logger.error(f"SystemMessage error_during_execution received: {error_text}")

if state_manager:
state_manager.update_workbench_status("failed")
state_manager.report_progress(
progress=100,
status=TaskStatus.FAILED.value,
message=str(error_text),
extra_result={
"error_subtype": msg.subtype,
"error": error_text,
},
)

if thinking_manager:
thinking_manager.add_thinking_step_by_key(
title_key="thinking.task_execution_failed",
report_immediately=False,
details={"subtype": msg.subtype, "error": error_text},
)

return TaskStatus.FAILED

return None


def _handle_user_message(msg: UserMessage, thinking_manager=None) -> tuple[bool, str]:
"""处理用户消息,提取详细信息
Expand Down Expand Up @@ -667,7 +716,9 @@ async def _process_result_message(
)
return TaskStatus.COMPLETED

if msg.is_error:
is_error = msg.is_error or msg.subtype == "error_during_execution"

if is_error:
logger.error(f"Received error from Claude SDK: {msg.result}")
result_str = str(msg.result) if msg.result is not None else "No result"

Expand Down
70 changes: 53 additions & 17 deletions executor/agents/claude_code/session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@

logger = setup_logger("claude_code_session_manager")

# Timeout constants for client operations
INTERRUPT_TIMEOUT_SECONDS = 5.0
DISCONNECT_TIMEOUT_SECONDS = 2.0


class SessionManager:
"""
Expand Down Expand Up @@ -214,38 +218,70 @@ def get_active_session_count(cls) -> int:
async def close_client(cls, session_id: str) -> bool:
"""Close a specific client connection.

Implements multi-level shutdown:
1. Try graceful disconnect with timeout
2. Force terminate process if disconnect fails or times out
3. Handle cancel-scope mismatch errors

Args:
session_id: Session ID to close

Returns:
True if successfully closed, False otherwise
"""
try:
if session_id in cls._clients:
client = cls._clients[session_id]
await client.disconnect()
del cls._clients[session_id]
logger.info(f"Closed Claude client for session_id: {session_id}")
return True
return False
client = cls._clients.get(session_id)
if not client:
return False

try:
await asyncio.wait_for(
client.disconnect(), timeout=DISCONNECT_TIMEOUT_SECONDS
)
logger.info(f"Disconnected Claude client for session_id: {session_id}")
except asyncio.TimeoutError:
logger.warning(
f"Disconnect timed out after {DISCONNECT_TIMEOUT_SECONDS}s for session_id={session_id}; "
"forcing process termination"
)
await cls._terminate_client_process(client, session_id)
except RuntimeError as e:
if "Attempted to exit cancel scope in a different task" in str(e):
logger.warning(
f"Disconnect failed due to cancel-scope mismatch for session_id={session_id}; "
"forcing process termination"
)
await cls._terminate_client_process(client, session_id)
else:
raise
finally:
cls._clients.pop(session_id, None)
for internal_key, mapped_session_id in list(
cls._session_id_map.items()
):
if mapped_session_id == session_id:
cls._session_id_map.pop(internal_key, None)

return True
except Exception as e:
logger.exception(
f"Error closing client for session_id {session_id}: {str(e)}"
)
cls._clients.pop(session_id, None)
for internal_key, mapped_session_id in list(cls._session_id_map.items()):
if mapped_session_id == session_id:
cls._session_id_map.pop(internal_key, None)
return False

@classmethod
async def close_all_clients(cls) -> None:
"""Close all client connections."""
for session_id, client in list(cls._clients.items()):
try:
await client.disconnect()
logger.info(f"Closed Claude client for session_id: {session_id}")
except Exception as e:
logger.exception(
f"Error closing client for session_id {session_id}: {str(e)}"
)
cls._clients.clear()
"""Close all client connections.

Uses close_client for each client to ensure proper cleanup with
timeout protection and force termination if needed.
"""
for session_id in list(cls._clients.keys()):
await cls.close_client(session_id)

@classmethod
async def _terminate_client_process(
Expand Down
6 changes: 3 additions & 3 deletions executor/services/agent_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ async def _close_agent_session(
) -> Tuple[TaskStatus, Optional[str]]:
try:
agent_name = agent.get_name()
if agent_name == "ClaudeCodeAgent":
if agent_name == "ClaudeCode":
await ClaudeCodeAgent.close_client(task_id)
logger.info(f"[{_format_task_log(task_id, -1)}] Closed Claude client")
elif agent_name == "Agno":
Expand Down Expand Up @@ -434,13 +434,13 @@ async def close_all_agent_sessions(self) -> Tuple[TaskStatus, str, Dict[str, str
error_detail: Dict[str, str] = {}
agent_types = {s.agent.get_name() for s in self._agent_sessions.values()}

if "ClaudeCodeAgent" in agent_types:
if "ClaudeCode" in agent_types:
status, msg = await self._close_claude_sessions()
if status == TaskStatus.SUCCESS:
results.append("Claude")
else:
errors.append("Claude")
error_detail["ClaudeCodeAgent"] = msg or "Unknown error"
error_detail["ClaudeCode"] = msg or "Unknown error"

if "Agno" in agent_types:
status, msg = await self._close_agno_sessions()
Expand Down
Loading