Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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
132 changes: 105 additions & 27 deletions executor/agents/claude_code/claude_code_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,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 @@ -852,7 +855,10 @@ def _extract_claude_options(self, task_data: Dict[str, Any]) -> Dict[str, Any]:
if mcp_servers:
# Replace placeholders in MCP servers config with actual values from task_data
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 (provides silent_exit tool via HTTP)
Expand Down Expand Up @@ -1085,10 +1091,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 @@ -1382,36 +1391,88 @@ def _handle_execution_error(
)
return TaskStatus.FAILED

@classmethod
async def _force_close_client_process(
cls, client: ClaudeSDKClient, session_id: str
) -> None:
transport = getattr(client, "_transport", None)
process = getattr(transport, "_process", None) if transport else None
if not process:
return

pid = process.pid if hasattr(process, "pid") else None

try:
process.terminate()
try:
await asyncio.wait_for(
process.wait(), timeout=DISCONNECT_TIMEOUT_SECONDS
)
except asyncio.TimeoutError:
process.kill()
await asyncio.wait_for(process.wait(), timeout=1.0)

logger.info(
f"Force-terminated Claude Code process for session_id={session_id}, PID={pid}"
)
except Exception as e:
logger.warning(
f"Failed to force-terminate process for session_id={session_id}, PID={pid}: {e}"
)

@classmethod
async def close_client(cls, session_id: str) -> TaskStatus:
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}")
client = cls._clients.get(session_id)
if not client:
return TaskStatus.SUCCESS
return TaskStatus.FAILED

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._force_close_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._force_close_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 TaskStatus.SUCCESS
except Exception as e:
logger.exception(
f"Error closing client for session_id {session_id}: {str(e)}"
)
return TaskStatus.FAILED
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 TaskStatus.SUCCESS
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

@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()
for session_id in list(cls._clients.keys()):
await cls.close_client(session_id)

@classmethod
async def cleanup_task_clients(cls, task_id: int) -> int:
Expand Down Expand Up @@ -1708,12 +1769,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
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 @@ -171,6 +175,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 @@ -193,7 +207,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 @@ -221,6 +237,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 @@ -669,7 +718,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
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