-
Notifications
You must be signed in to change notification settings - Fork 413
Expand file tree
/
Copy pathfacade.py
More file actions
286 lines (244 loc) · 10.1 KB
/
Copy pathfacade.py
File metadata and controls
286 lines (244 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""High-level Claude Code integration facade.
Provides simple interface for bot handlers.
"""
import asyncio
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import structlog
from ..config.settings import Settings
from .sdk_integration import ClaudeResponse, ClaudeSDKManager, StreamUpdate
from .session import SessionManager
logger = structlog.get_logger()
class ClaudeIntegration:
"""Main integration point for Claude Code."""
def __init__(
self,
config: Settings,
sdk_manager: Optional[ClaudeSDKManager] = None,
session_manager: Optional[SessionManager] = None,
):
"""Initialize Claude integration facade."""
self.config = config
self.sdk_manager = sdk_manager or ClaudeSDKManager(config)
self.session_manager = session_manager
async def run_command(
self,
prompt: str,
working_directory: Path,
user_id: int,
session_id: Optional[str] = None,
on_stream: Optional[Callable[[StreamUpdate], None]] = None,
force_new: bool = False,
interrupt_event: Optional["asyncio.Event"] = None,
images: Optional[List[Dict[str, str]]] = None,
) -> ClaudeResponse:
"""Run Claude Code command with full integration."""
logger.info(
"Running Claude command",
user_id=user_id,
working_directory=str(working_directory),
session_id=session_id,
prompt_length=len(prompt),
force_new=force_new,
)
# If no session_id provided, try to find an existing session for this
# user+directory combination (auto-resume).
# Skip auto-resume when force_new is set (e.g. after /new command).
if not session_id and not force_new:
existing_session = await self._find_resumable_session(
user_id, working_directory
)
if existing_session:
session_id = existing_session.session_id
logger.info(
"Auto-resuming existing session for project",
session_id=session_id,
project_path=str(working_directory),
user_id=user_id,
)
# Get or create session
session = await self.session_manager.get_or_create_session(
user_id, working_directory, session_id
)
# Execute command
try:
# Continue session if we have an existing session with a real ID
is_new = getattr(session, "is_new_session", False)
should_continue = not is_new and bool(session.session_id)
# For new sessions, don't pass session_id to Claude Code
claude_session_id = session.session_id if should_continue else None
try:
response = await self._execute(
prompt=prompt,
working_directory=working_directory,
session_id=claude_session_id,
continue_session=should_continue,
stream_callback=on_stream,
interrupt_event=interrupt_event,
images=images,
)
except Exception as resume_error:
# If resume failed (e.g., session expired/missing on Claude's side),
# retry as a fresh session. The CLI returns a generic exit-code-1
# when the session is gone, so we catch *any* error during resume.
if should_continue:
logger.warning(
"Session resume failed, starting fresh session",
failed_session_id=claude_session_id,
error=str(resume_error),
)
# Clean up the stale session
await self.session_manager.remove_session(session.session_id)
# Create a fresh session and retry
session = await self.session_manager.get_or_create_session(
user_id, working_directory
)
response = await self._execute(
prompt=prompt,
working_directory=working_directory,
session_id=None,
continue_session=False,
stream_callback=on_stream,
interrupt_event=interrupt_event,
images=images,
)
else:
raise
# Update session (assigns real session_id for new sessions)
await self.session_manager.update_session(session, response)
# Ensure response has the session's final ID
response.session_id = session.session_id
if not response.session_id:
logger.warning(
"No session_id after execution; session cannot be resumed",
user_id=user_id,
)
logger.info(
"Claude command completed",
session_id=response.session_id,
cost=response.cost,
duration_ms=response.duration_ms,
num_turns=response.num_turns,
is_error=response.is_error,
)
return response
except Exception as e:
logger.error(
"Claude command failed",
error=str(e),
user_id=user_id,
session_id=session.session_id,
)
raise
async def _execute(
self,
prompt: str,
working_directory: Path,
session_id: Optional[str] = None,
continue_session: bool = False,
stream_callback: Optional[Callable] = None,
interrupt_event: Optional[asyncio.Event] = None,
images: Optional[List[Dict[str, str]]] = None,
) -> ClaudeResponse:
"""Execute command via SDK."""
return await self.sdk_manager.execute_command(
prompt=prompt,
working_directory=working_directory,
session_id=session_id,
continue_session=continue_session,
stream_callback=stream_callback,
interrupt_event=interrupt_event,
images=images,
)
async def _find_resumable_session(
self,
user_id: int,
working_directory: Path,
) -> Optional["ClaudeSession"]: # noqa: F821
"""Find the most recent resumable session for a user in a directory.
Returns the session if one exists that is non-expired and has a real
(non-temporary) session ID from Claude. Returns None otherwise.
"""
sessions = await self.session_manager._get_user_sessions(user_id)
matching_sessions = [
s
for s in sessions
if s.project_path == working_directory
and bool(s.session_id)
and not self.session_manager._is_session_expired(s)
]
if not matching_sessions:
return None
return max(matching_sessions, key=lambda s: s.last_used)
async def continue_session(
self,
user_id: int,
working_directory: Path,
prompt: Optional[str] = None,
on_stream: Optional[Callable[[StreamUpdate], None]] = None,
) -> Optional[ClaudeResponse]:
"""Continue the most recent session."""
logger.info(
"Continuing session",
user_id=user_id,
working_directory=str(working_directory),
has_prompt=bool(prompt),
)
# Get user's sessions
sessions = await self.session_manager._get_user_sessions(user_id)
# Find most recent session in this directory (exclude sessions without IDs)
matching_sessions = [
s
for s in sessions
if s.project_path == working_directory and bool(s.session_id)
]
if not matching_sessions:
logger.info("No matching sessions found", user_id=user_id)
return None
# Get most recent
latest_session = max(matching_sessions, key=lambda s: s.last_used)
# Continue session with default prompt if none provided
# Claude CLI requires a prompt, so we use a placeholder
return await self.run_command(
prompt=prompt or "Please continue where we left off",
working_directory=working_directory,
user_id=user_id,
session_id=latest_session.session_id,
on_stream=on_stream,
)
async def get_session_info(
self, session_id: str, user_id: int
) -> Optional[Dict[str, Any]]:
"""Get session information (scoped to requesting user)."""
return await self.session_manager.get_session_info(session_id, user_id)
async def get_user_sessions(self, user_id: int) -> List[Dict[str, Any]]:
"""Get all sessions for a user."""
sessions = await self.session_manager._get_user_sessions(user_id)
return [
{
"session_id": s.session_id,
"project_path": str(s.project_path),
"created_at": s.created_at.isoformat(),
"last_used": s.last_used.isoformat(),
"total_cost": s.total_cost,
"message_count": s.message_count,
"tools_used": s.tools_used,
"expired": self.session_manager._is_session_expired(s),
}
for s in sessions
]
async def cleanup_expired_sessions(self) -> int:
"""Clean up expired sessions."""
return await self.session_manager.cleanup_expired_sessions()
async def get_user_summary(self, user_id: int) -> Dict[str, Any]:
"""Get comprehensive user summary."""
session_summary = await self.session_manager.get_user_session_summary(user_id)
return {
"user_id": user_id,
**session_summary,
}
async def shutdown(self) -> None:
"""Shutdown integration and cleanup resources."""
logger.info("Shutting down Claude integration")
await self.cleanup_expired_sessions()
logger.info("Claude integration shutdown complete")