-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2568 lines (2205 loc) · 113 KB
/
main.py
File metadata and controls
2568 lines (2205 loc) · 113 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import asyncio
import logging
import secrets
import string
import random
import time
from typing import Optional, AsyncGenerator, Dict, Any, Tuple
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.security import HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError
from dotenv import load_dotenv
from models import (
ChatCompletionRequest,
ChatCompletionResponse,
ChatCompletionStreamResponse,
Choice,
Message,
Usage,
StreamChoice,
ErrorResponse,
ErrorDetail
)
from claude_cli import ClaudeCodeCLI
from gemini_cli import GeminiCLI
from qwen_cli import QwenCLI
from message_adapter import MessageAdapter
from gemini_message_adapter import GeminiMessageAdapter
from qwen_message_adapter import QwenMessageAdapter
from image_analysis_orchestrator import ImageAnalysisOrchestrator
from auth import verify_api_key, security, validate_claude_code_auth, get_claude_code_auth_info
from parameter_validator import ParameterValidator, CompatibilityReporter
from rate_limiter import limiter, rate_limit_exceeded_handler, get_rate_limit_for_endpoint, rate_limit_endpoint
from chat_mode import ChatMode, get_chat_mode_info
from model_utils import ModelUtils
from session_tracker import get_tracker, scan_claude_projects_for_sandbox_sessions
from model_discovery import get_supported_models, clear_model_cache
# Load environment variables
load_dotenv()
# Configure logging based on debug mode
DEBUG_MODE = os.getenv('DEBUG_MODE', 'false').lower() in ('true', '1', 'yes', 'on')
VERBOSE = os.getenv('VERBOSE', 'false').lower() in ('true', '1', 'yes', 'on')
SSE_KEEPALIVE_INTERVAL = int(os.getenv('SSE_KEEPALIVE_INTERVAL', '30')) # seconds
CHAT_MODE_CLEANUP_SESSIONS = os.getenv('CHAT_MODE_CLEANUP_SESSIONS', 'true').lower() in ('true', '1', 'yes', 'on')
CHAT_MODE_CLEANUP_DELAY_MINUTES = int(os.getenv('CHAT_MODE_CLEANUP_DELAY_MINUTES', '720')) # 12 hours default
# Warmup configuration
SKIP_CLI_VERIFICATION = os.getenv('SKIP_CLI_VERIFICATION', 'false').lower() in ('true', '1', 'yes')
# Set logging level based on debug/verbose mode
log_level = logging.DEBUG if (DEBUG_MODE or VERBOSE) else logging.INFO
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ALL_CLAUDE_TOOLS constant removed - using ChatMode.get_allowed_tools() instead
# Global variable to store runtime-generated API key
runtime_api_key = None
def create_error_response(error: Exception, context: str) -> Dict[str, Any]:
"""Create standardized error response."""
logger.error(f"{context}: {type(error).__name__}: {str(error)}")
return {
"error": {
"message": str(error),
"type": type(error).__name__,
"context": context
}
}
def get_model_provider(model_name: str) -> str:
"""Determine which provider to use based on model name."""
base_model = model_name.lower()
# Remove chat mode suffixes if present
base_model = base_model.replace("-chat-progress", "").replace("-chat", "")
if base_model.startswith("qwen"):
return "qwen"
elif base_model.startswith("gemini") or base_model.startswith("models/gemini"):
return "gemini"
elif base_model.startswith("claude"):
return "claude"
else:
# Default to Claude for backward compatibility
return "claude"
def generate_secure_token(length: int = 32) -> str:
"""Generate a secure random token for API authentication."""
alphabet = string.ascii_letters + string.digits + '-_'
return ''.join(secrets.choice(alphabet) for _ in range(length))
def prompt_for_api_protection() -> Optional[str]:
"""
Interactively ask user if they want API key protection.
Returns the generated token if user chooses protection, None otherwise.
"""
# Don't prompt if API_KEY is already set via environment variable
if os.getenv("API_KEY"):
return None
print("\n" + "="*60)
print("🔐 API Endpoint Security Configuration")
print("="*60)
print("Would you like to protect your API endpoint with an API key?")
print("This adds a security layer when accessing your server remotely.")
print("")
while True:
try:
choice = input("Enable API key protection? (y/N): ").strip().lower()
if choice in ['', 'n', 'no']:
print("✅ API endpoint will be accessible without authentication")
print("="*60)
return None
elif choice in ['y', 'yes']:
token = generate_secure_token()
print("")
print("🔑 API Key Generated!")
print("="*60)
print(f"API Key: {token}")
print("="*60)
print("📋 IMPORTANT: Save this key - you'll need it for API calls!")
print(" Example usage:")
print(f' curl -H "Authorization: Bearer {token}" \\')
print(" http://localhost:8000/v1/models")
print("="*60)
return token
else:
print("Please enter 'y' for yes or 'n' for no (or press Enter for no)")
except (EOFError, KeyboardInterrupt):
print("\n✅ Defaulting to no authentication")
return None
# Initialize Claude CLI
claude_cli = ClaudeCodeCLI(
timeout=int(os.getenv("MAX_TIMEOUT", "600000"))
)
# Initialize Gemini CLI
gemini_cli = GeminiCLI(
timeout=int(os.getenv("MAX_TIMEOUT", "600000"))
)
# Initialize Qwen CLI
qwen_cli = QwenCLI(
timeout=int(os.getenv("MAX_TIMEOUT", "600000"))
)
async def sandbox_session_cleanup_task():
"""Background task to clean up expired sandbox sessions."""
tracker = get_tracker()
while True:
try:
# Wait for check interval (1 minute)
await asyncio.sleep(60)
# Skip if cleanup is disabled or delay is 0 (immediate cleanup)
if not CHAT_MODE_CLEANUP_SESSIONS or CHAT_MODE_CLEANUP_DELAY_MINUTES == 0:
continue
# Get expired sessions
expired_sessions = tracker.get_expired_sandbox_sessions(CHAT_MODE_CLEANUP_DELAY_MINUTES)
if expired_sessions:
logger.info(f"Found {len(expired_sessions)} expired sandbox sessions to clean up")
for session_id, info in expired_sessions.items():
try:
sandbox_dir = info.get("sandbox_dir", "")
# Safety check
if "claude_chat_sandbox" not in sandbox_dir:
logger.warning(f"Skipping non-sandbox session {session_id}")
tracker.cleanup_tracked_session(session_id)
continue
# Clean up the session
if cleanup_claude_session(sandbox_dir, session_id):
logger.info(f"Cleaned up expired sandbox session {session_id}")
tracker.cleanup_tracked_session(session_id)
else:
logger.warning(f"Failed to cleanup session {session_id}")
except Exception as e:
logger.error(f"Error cleaning up session {session_id}: {e}")
# Remove from tracking even if cleanup failed
tracker.cleanup_tracked_session(session_id)
# Also clean up stale tracker entries (older than 5 hours)
stale_count = tracker.cleanup_stale_entries()
if stale_count > 0:
logger.info(f"Removed {stale_count} stale tracker entries")
except asyncio.CancelledError:
logger.info("Sandbox cleanup task cancelled")
break
except Exception as e:
logger.error(f"Error in sandbox cleanup task: {e}")
# Continue running even if there's an error
await asyncio.sleep(60)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Verify Claude Code authentication and CLI on startup."""
logger.info("Verifying Claude Code authentication and CLI...")
# Discover available models
try:
discovered_models = get_supported_models()
logger.info(f"✅ Discovered {len(discovered_models)} Claude models: {sorted(discovered_models)}")
except Exception as e:
logger.warning(f"⚠️ Model discovery failed: {e}")
logger.warning("Will use fallback model list")
# Validate authentication first
auth_valid, auth_info = validate_claude_code_auth()
if not auth_valid:
logger.error("❌ Claude Code authentication failed!")
for error in auth_info.get('errors', []):
logger.error(f" - {error}")
logger.warning("Authentication setup guide:")
logger.warning(" 1. For Anthropic API: Set ANTHROPIC_API_KEY")
logger.warning(" 2. For Bedrock: Set CLAUDE_CODE_USE_BEDROCK=1 + AWS credentials")
logger.warning(" 3. For Vertex AI: Set CLAUDE_CODE_USE_VERTEX=1 + GCP credentials")
else:
logger.info(f"✅ Claude Code authentication validated: {auth_info['method']}")
# Skip or perform CLI verification based on configuration
if not SKIP_CLI_VERIFICATION:
logger.info("Verifying Claude Code CLI...")
cli_verified = await claude_cli.verify_cli()
if cli_verified:
logger.info("✅ Claude Code CLI verified successfully")
else:
logger.warning("⚠️ Claude Code CLI verification failed!")
logger.warning("The server will start, but requests may fail.")
else:
logger.info("Skipping CLI verification (SKIP_CLI_VERIFICATION=true)")
logger.info("This speeds up startup and avoids unnecessary cold start")
# Log debug information if debug mode is enabled
if DEBUG_MODE or VERBOSE:
logger.debug("🔧 Debug mode enabled - Enhanced logging active")
logger.debug(f"🔧 Environment variables:")
logger.debug(f" DEBUG_MODE: {DEBUG_MODE}")
logger.debug(f" VERBOSE: {VERBOSE}")
logger.debug(f" PORT: {os.getenv('PORT', '8000')}")
logger.debug(f" CORS_ORIGINS: {os.getenv('CORS_ORIGINS', '[\"*\"]')}")
logger.debug(f" MAX_TIMEOUT: {os.getenv('MAX_TIMEOUT', '600000')}")
logger.debug(f"🔧 Available endpoints:")
logger.debug(f" POST /v1/chat/completions - Main chat endpoint")
logger.debug(f" GET /v1/models - List available models")
logger.debug(f" POST /v1/debug/request - Debug request validation")
logger.debug(f" GET /v1/auth/status - Authentication status")
logger.debug(f" GET /health - Health check")
logger.debug(f"🔧 API Key protection: {'Enabled' if (os.getenv('API_KEY') or runtime_api_key) else 'Disabled'}")
# Start sandbox session cleanup task if enabled
sandbox_cleanup_task = None
if CHAT_MODE_CLEANUP_SESSIONS:
# Perform startup cleanup of old sessions
logger.info(f"Starting sandbox session cleanup (delay: {CHAT_MODE_CLEANUP_DELAY_MINUTES} minutes)")
# Clean up old sessions on startup
if CHAT_MODE_CLEANUP_DELAY_MINUTES > 0:
old_sessions = scan_claude_projects_for_sandbox_sessions(CHAT_MODE_CLEANUP_DELAY_MINUTES)
for session_id, project_dir, age_minutes in old_sessions:
try:
# The scan returns the full project directory path
# We need to extract the session file directly from it
session_file = os.path.join(project_dir, f"{session_id}.jsonl")
if os.path.exists(session_file):
os.remove(session_file)
logger.info(f"Deleted old sandbox session file: {session_file} (age: {age_minutes:.1f} minutes)")
# Try to remove the project directory if empty
try:
if os.path.exists(project_dir) and not os.listdir(project_dir):
os.rmdir(project_dir)
logger.info(f"Removed empty sandbox project directory: {project_dir}")
except Exception as dir_err:
logger.debug(f"Could not remove project directory (may not be empty): {dir_err}")
else:
logger.warning(f"Old sandbox session file not found: {session_file}")
except Exception as e:
logger.error(f"Failed to cleanup old session {session_id}: {e}")
# Start background cleanup task
sandbox_cleanup_task = asyncio.create_task(sandbox_session_cleanup_task())
logger.info("Started sandbox session cleanup background task")
yield
# Cleanup on shutdown
if sandbox_cleanup_task:
sandbox_cleanup_task.cancel()
try:
await sandbox_cleanup_task
except asyncio.CancelledError:
pass
logger.info("Stopped sandbox session cleanup task")
# Create FastAPI app
app = FastAPI(
title="Claude Code OpenAI API Wrapper",
description="OpenAI-compatible API for Claude Code",
version="1.0.0",
lifespan=lifespan
)
# Configure CORS
cors_origins = json.loads(os.getenv("CORS_ORIGINS", '["*"]'))
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Add rate limiting error handler
if limiter:
app.state.limiter = limiter
app.add_exception_handler(429, rate_limit_exceeded_handler)
# Add debug logging middleware
from starlette.middleware.base import BaseHTTPMiddleware
class DebugLoggingMiddleware(BaseHTTPMiddleware):
"""ASGI-compliant middleware for logging request/response details when debug mode is enabled."""
async def dispatch(self, request: Request, call_next):
if not (DEBUG_MODE or VERBOSE):
return await call_next(request)
# Log request details
start_time = asyncio.get_event_loop().time()
# Log basic request info
logger.debug(f"🔍 Incoming request: {request.method} {request.url}")
logger.debug(f"🔍 Headers: {dict(request.headers)}")
# For POST requests, try to log body (but don't break if we can't)
body_logged = False
if request.method == "POST" and request.url.path.startswith("/v1/"):
try:
# Only attempt to read body if it's reasonable size and content-type
content_length = request.headers.get("content-length")
if content_length and int(content_length) < 100000: # Less than 100KB
body = await request.body()
if body:
try:
import json as json_lib
parsed_body = json_lib.loads(body.decode())
logger.debug(f"🔍 Request body: {json_lib.dumps(parsed_body, indent=2)}")
body_logged = True
except:
logger.debug(f"🔍 Request body (raw): {body.decode()[:500]}...")
body_logged = True
except Exception as e:
logger.debug(f"🔍 Could not read request body: {e}")
if not body_logged and request.method == "POST":
logger.debug("🔍 Request body: [not logged - streaming or large payload]")
# Process the request
try:
response = await call_next(request)
# Log response details
end_time = asyncio.get_event_loop().time()
duration = (end_time - start_time) * 1000 # Convert to milliseconds
logger.debug(f"🔍 Response: {response.status_code} in {duration:.2f}ms")
return response
except Exception as e:
end_time = asyncio.get_event_loop().time()
duration = (end_time - start_time) * 1000
logger.debug(f"🔍 Request failed after {duration:.2f}ms: {e}")
raise
# Add the debug middleware
app.add_middleware(DebugLoggingMiddleware)
# Custom exception handler for 422 validation errors
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
"""Handle request validation errors with detailed debugging information."""
# Log the validation error details
logger.error(f"❌ Request validation failed for {request.method} {request.url}")
logger.error(f"❌ Validation errors: {exc.errors()}")
# Create detailed error response
error_details = []
for error in exc.errors():
location = " -> ".join(str(loc) for loc in error.get("loc", []))
error_details.append({
"field": location,
"message": error.get("msg", "Unknown validation error"),
"type": error.get("type", "validation_error"),
"input": error.get("input")
})
# If debug mode is enabled, include the raw request body
debug_info = {}
if DEBUG_MODE or VERBOSE:
try:
body = await request.body()
if body:
debug_info["raw_request_body"] = body.decode()
except:
debug_info["raw_request_body"] = "Could not read request body"
error_response = {
"error": {
"message": "Request validation failed - the request body doesn't match the expected format",
"type": "validation_error",
"code": "invalid_request_error",
"details": error_details,
"help": {
"common_issues": [
"Missing required fields (model, messages)",
"Invalid field types (e.g. messages should be an array)",
"Invalid role values (must be 'system', 'user', or 'assistant')",
"Invalid parameter ranges (e.g. temperature must be 0-2)"
],
"debug_tip": "Set DEBUG_MODE=true or VERBOSE=true environment variable for more detailed logging"
}
}
}
# Add debug info if available
if debug_info:
error_response["error"]["debug"] = debug_info
return JSONResponse(
status_code=422,
content=error_response
)
def create_progress_chunk(request_id: str, model: str, content: str) -> str:
"""Create a progress indicator chunk in SSE format."""
chunk = ChatCompletionStreamResponse(
id=request_id,
model=model,
choices=[StreamChoice(
index=0,
delta={"content": content},
finish_reason=None
)]
)
return f"data: {chunk.model_dump_json()}\n\n"
def create_sse_keepalive() -> str:
"""Create an SSE comment for keep-alive. Comments are not shown to clients."""
return ": keepalive\n\n"
async def create_keepalive_task(interval: int = None) -> Tuple[asyncio.Task, asyncio.Queue]:
"""Create a keepalive task that sends SSE comments periodically.
Args:
interval: Keepalive interval in seconds (defaults to SSE_KEEPALIVE_INTERVAL)
Returns:
Tuple of (keepalive_task, keepalive_queue)
"""
if interval is None:
interval = SSE_KEEPALIVE_INTERVAL
keepalive_queue = asyncio.Queue()
async def send_keepalives():
"""Send SSE keepalive comments periodically"""
try:
while True:
await asyncio.sleep(interval)
await keepalive_queue.put(create_sse_keepalive())
logger.debug(f"Queued SSE keepalive comment")
except asyncio.CancelledError:
logger.debug("Keepalive task cancelled")
keepalive_task = asyncio.create_task(send_keepalives())
return keepalive_task, keepalive_queue
def extract_content_from_chunk(chunk: Dict[str, Any]) -> Optional[str]:
"""Extract text content from ANY SDK chunk format.
Returns None only if the chunk genuinely has no content (not an error).
"""
# Format 1: AssistantMessage with content array
if "content" in chunk and isinstance(chunk["content"], list):
text_parts = []
for block in chunk["content"]:
# Handle TextBlock objects from Claude Code SDK
if hasattr(block, 'text'):
text_parts.append(block.text)
# Handle dictionary format
elif isinstance(block, dict) and block.get("type") == "text":
text_parts.append(block.get("text", ""))
if text_parts:
return "".join(text_parts)
# Format 2: Old assistant message format
if chunk.get("type") == "assistant" and "message" in chunk:
message = chunk["message"]
if isinstance(message, dict) and "content" in message:
content = message["content"]
# Recursively extract from message content
if isinstance(content, list):
text_parts = []
for block in content:
if hasattr(block, 'text'):
text_parts.append(block.text)
elif isinstance(block, dict) and block.get("type") == "text":
text_parts.append(block.get("text", ""))
if text_parts:
return "".join(text_parts)
elif isinstance(content, str):
return content
# Format 3: Result message
if chunk.get("subtype") == "success" and "result" in chunk:
return chunk["result"]
# Format 4: Direct content string
if "content" in chunk and isinstance(chunk["content"], str):
return chunk["content"]
# Format 5: Old format with type=assistant and direct content
if chunk.get("type") == "assistant" and isinstance(chunk.get("content"), str):
return chunk["content"]
# Log unhandled format for investigation
# Check both type and subtype fields for known non-content types
chunk_type = chunk.get("type", "")
chunk_subtype = chunk.get("subtype", "")
known_non_content_types = ["init", "tool_use", "tool_result", "error", "progress"]
known_non_content_subtypes = ["init", "error", "success"]
if (chunk_type not in known_non_content_types and
chunk_subtype not in known_non_content_subtypes and
(chunk_type or chunk_subtype)): # Only warn if there's actually a type/subtype
logger.warning(f"Unhandled chunk format for content extraction: {json.dumps(chunk)}")
return None # Only if chunk has no content field
def cleanup_claude_session(sandbox_dir: str, session_id: str) -> bool:
"""Delete Claude Code session file for chat mode requests.
Args:
sandbox_dir: The sandbox directory path (e.g., /private/var/folders/.../claude_chat_sandbox_xxx)
session_id: The Claude session ID (UUID format)
Returns:
True if cleanup was successful, False otherwise
"""
try:
# Two places to check for session files:
# 1. In the sandbox-specific project directory
# 2. In the main wrapper project directory (if running from the wrapper directory)
files_removed = []
# First check sandbox-specific directory
# Claude transforms the path by:
# 1. Replacing all slashes with dashes
# 2. Replacing underscores with dashes
# 3. Prepending a dash to the whole path
transformed_path = sandbox_dir.replace('/', '-').replace('_', '-')
if not transformed_path.startswith('-'):
transformed_path = '-' + transformed_path
claude_project_dir = os.path.expanduser(f"~/.claude/projects/{transformed_path}")
session_file = os.path.join(claude_project_dir, f"{session_id}.jsonl")
if os.path.exists(session_file):
os.remove(session_file)
files_removed.append(session_file)
logger.info(f"Deleted Claude session file: {session_file}")
# Try to remove the project directory if empty
try:
if os.path.exists(claude_project_dir) and not os.listdir(claude_project_dir):
os.rmdir(claude_project_dir)
logger.info(f"Removed empty Claude project directory: {claude_project_dir}")
except Exception as dir_err:
logger.debug(f"Could not remove project directory (may not be empty): {dir_err}")
# Also check the main wrapper project directory
# This handles cases where Claude creates sessions in the current working directory
wrapper_project_dir = os.path.expanduser("~/.claude/projects/-Users-val-claude-code-openai-wrapper")
wrapper_session_file = os.path.join(wrapper_project_dir, f"{session_id}.jsonl")
if os.path.exists(wrapper_session_file):
# Check if this is a chat mode session by reading first line
try:
with open(wrapper_session_file, 'r') as f:
first_line = f.readline()
if first_line:
data = json.loads(first_line)
# Only remove if it's a Hello session or has our chat mode markers
content = data.get('message', {}).get('content', '')
if (content == 'Hello' or
'digital black hole' in str(content) or
'sandboxed environment' in str(content)):
os.remove(wrapper_session_file)
files_removed.append(wrapper_session_file)
logger.info(f"Deleted wrapper project session: {wrapper_session_file}")
except Exception as e:
logger.debug(f"Could not check/remove wrapper session: {e}")
if not files_removed:
logger.debug(f"No session files found to remove for session {session_id}")
return False
return True
except Exception as e:
logger.error(f"Failed to cleanup Claude session {session_id}: {e}")
return False
async def stream_final_content_only(
request: ChatCompletionRequest,
request_id: str,
claude_headers: Optional[Dict[str, Any]] = None,
requires_xml: bool = False
) -> AsyncGenerator[str, None]:
"""Generate SSE formatted streaming response with only final content (no intermediate tool uses)."""
sandbox_dir = None
session_id = None # Track Claude session ID for cleanup
final_content = ""
buffered_chunks = []
try:
# Get session info - sessions disabled in chat mode refactor
all_messages = request.messages
actual_session_id = None
logger.info("Sessions disabled - using messages directly")
# Convert messages to prompt
logger.debug(f"Converting {len(all_messages)} messages to prompt")
prompt, system_prompt = MessageAdapter.messages_to_prompt(all_messages)
logger.debug(f"Converted prompt length: {len(prompt)}, system prompt: {len(system_prompt) if system_prompt else 0} chars")
# Skip content filtering to preserve XML
logger.debug("Chat mode: Skipping content filtering to preserve XML tool definitions")
# Get Claude Code SDK options from request
claude_options = request.to_claude_options()
# Merge with Claude-specific headers if provided
if claude_headers:
claude_options.update(claude_headers)
# Handle tools - always use chat mode restricted tool set
logger.info("Chat mode: using restricted tool set")
claude_options['allowed_tools'] = ChatMode.get_allowed_tools()
claude_options['disallowed_tools'] = None
claude_options['max_turns'] = claude_options.get('max_turns', 10)
# Buffer SDK responses - Direct streaming without async task wrapper
sdk_chunks_received = 0
consume_start_time = asyncio.get_event_loop().time()
# Track assistant messages separately to find the LAST one
assistant_messages = [] # List of (index, content) tuples
current_assistant_content = ""
in_assistant_message = False
# Direct SDK streaming - no async task wrapper
logger.debug("Starting SDK stream for buffering")
logger.debug(f"SDK call parameters - prompt length: {len(prompt)}, system_prompt: {len(system_prompt) if system_prompt else 0}")
logger.debug(f"SDK call parameters - model: {claude_options.get('model')}, max_turns: {claude_options.get('max_turns', 10)}")
logger.debug(f"SDK call parameters - allowed_tools: {claude_options.get('allowed_tools')}")
logger.debug(f"SDK call parameters - disallowed_tools: {claude_options.get('disallowed_tools')}")
logger.debug(f"SDK call parameters - messages count: {len(all_messages)}")
# Log the exact prompt being sent
logger.info("=== SDK PROMPT START ===")
logger.info(f"Prompt (first 500 chars): {prompt[:500]}...")
if len(prompt) > 500:
logger.info(f"Prompt (last 500 chars): ...{prompt[-500:]}")
logger.info(f"System prompt: {system_prompt[:200] if system_prompt else 'None'}")
logger.info("=== SDK PROMPT END ===")
# CRITICAL: Log if we expect XML format
expects_xml = False
if prompt:
prompt_lower = prompt.lower()
expects_xml = any([
"tool uses are formatted" in prompt_lower,
"<tool_name>" in prompt_lower,
"xml-style tags" in prompt_lower,
"<attempt_completion>" in prompt_lower
])
if expects_xml:
logger.info("📋 Expecting XML tool format in response based on prompt patterns")
# Use a queue to communicate between SDK stream and main loop
chunk_queue = asyncio.Queue()
stream_complete = asyncio.Event()
last_keepalive_time = asyncio.get_event_loop().time()
# Task to consume the SDK stream and put chunks in queue
async def sdk_consumer():
try:
logger.debug("Starting SDK stream consumer loop")
async for chunk in claude_cli.run_completion(
prompt=prompt,
system_prompt=system_prompt,
model=claude_options.get('model'),
max_turns=claude_options.get('max_turns', 10),
allowed_tools=claude_options.get('allowed_tools'),
disallowed_tools=claude_options.get('disallowed_tools'),
stream=True,
messages=[msg.model_dump() if hasattr(msg, 'model_dump') else msg for msg in all_messages],
requires_xml=requires_xml
):
await chunk_queue.put(chunk)
logger.debug("SDK stream consumer completed normally")
except asyncio.CancelledError:
logger.warning("SDK stream consumer was cancelled")
raise
except Exception as e:
logger.error(f"SDK stream consumer error: {type(e).__name__}: {e}")
logger.error(f"Exception traceback: ", exc_info=True)
raise
finally:
stream_complete.set()
await chunk_queue.put(None) # Sentinel value
# Start the SDK consumer task
consumer_task = asyncio.create_task(sdk_consumer())
# Main loop that processes chunks and sends keepalives
try:
queue_task = asyncio.create_task(chunk_queue.get())
keepalive_task = asyncio.create_task(asyncio.sleep(SSE_KEEPALIVE_INTERVAL))
stream_ended = False
while not stream_ended:
# Wait for either a chunk or keepalive timeout
done, pending = await asyncio.wait(
[queue_task, keepalive_task],
return_when=asyncio.FIRST_COMPLETED
)
for task in done:
if task == queue_task:
# Got a chunk from the SDK
chunk = task.result()
if chunk is None:
# Stream ended
if keepalive_task and not keepalive_task.done():
keepalive_task.cancel()
try:
await keepalive_task
except asyncio.CancelledError:
pass
stream_ended = True
break
# Process the chunk
sdk_chunks_received += 1
current_time = asyncio.get_event_loop().time()
# Log detailed chunk information
chunk_type = chunk.get('type', 'unknown')
chunk_subtype = chunk.get('subtype', 'unknown')
logger.debug(f"SDK chunk #{sdk_chunks_received} received - type: {chunk_type}, subtype: {chunk_subtype}")
# Log full chunk for debugging
if chunk_type == 'system' or chunk_subtype == 'init':
logger.debug(f"Full chunk data: {chunk}")
elif chunk_type == 'assistant' or 'content' in chunk:
# Log content preview
content_preview = str(chunk).replace('\n', '\\n')[:200]
logger.debug(f"Chunk content preview: {content_preview}...")
buffered_chunks.append(chunk)
# Extract sandbox directory and session ID from init message
if chunk_subtype == "init":
data = chunk.get("data", {})
if isinstance(data, dict):
if "cwd" in data and not sandbox_dir:
sandbox_dir = data["cwd"]
logger.debug(f"Tracked sandbox directory: {sandbox_dir}")
if "session_id" in data and not session_id:
session_id = data["session_id"]
logger.debug(f"Tracked Claude session ID: {session_id}")
# Also check top-level session_id
if "session_id" in chunk and not session_id:
session_id = chunk["session_id"]
logger.debug(f"Tracked Claude session ID from chunk: {session_id}")
# More precise detection of assistant messages
# Check for content that could be assistant text
extracted_text = extract_content_from_chunk(chunk)
# Only process if we actually extracted text content
if extracted_text is not None and extracted_text.strip():
# Check if this is genuinely an assistant message (not tool results, etc.)
is_assistant_chunk = (
chunk_type == "assistant" or
(chunk_type != "tool_use" and chunk_type != "system" and chunk_type != "result" and
"content" in chunk and extracted_text)
)
if is_assistant_chunk:
if not in_assistant_message:
# Start of a new assistant message
if current_assistant_content:
# Save the previous assistant message
assistant_messages.append(current_assistant_content)
logger.debug(f"Completed assistant message #{len(assistant_messages)}: {len(current_assistant_content)} chars")
current_assistant_content = extracted_text
in_assistant_message = True
logger.debug(f"Started new assistant message from chunk #{sdk_chunks_received}")
else:
# Continue current assistant message
current_assistant_content += extracted_text
logger.debug(f"Assistant content from chunk #{sdk_chunks_received}: {len(extracted_text)} chars, type={chunk_type}")
# Check for message boundaries (tool use, system messages, etc.)
elif chunk_type in ["tool_use", "system", "result"] or chunk_subtype in ["tool_use", "init", "success"]:
if in_assistant_message and current_assistant_content:
# End of current assistant message
assistant_messages.append(current_assistant_content)
logger.debug(f"Completed assistant message #{len(assistant_messages)} due to {chunk_type}/{chunk_subtype}: {len(current_assistant_content)} chars")
current_assistant_content = ""
in_assistant_message = False
# Create new task to wait for next chunk
queue_task = asyncio.create_task(chunk_queue.get())
elif task == keepalive_task:
# Keepalive timeout - send keepalive
current_time = asyncio.get_event_loop().time()
yield create_sse_keepalive()
last_keepalive_time = current_time
logger.debug(f"📡 Sent SSE keepalive during SDK buffering (after {sdk_chunks_received} chunks)")
# Create new keepalive task
keepalive_task = asyncio.create_task(asyncio.sleep(SSE_KEEPALIVE_INTERVAL))
logger.info(f"SDK stream completed: {sdk_chunks_received} chunks processed")
except asyncio.CancelledError:
logger.warning("SDK stream was cancelled")
raise
except Exception as e:
logger.error(f"SDK stream error: {type(e).__name__}: {e}")
logger.error(f"Exception traceback: ", exc_info=True)
raise
# Ensure consumer task is complete
logger.debug("Waiting for consumer task to complete...")
await consumer_task
logger.debug("Consumer task completed")
# Don't forget the last assistant message if stream ended while in one
if in_assistant_message and current_assistant_content:
assistant_messages.append(current_assistant_content)
logger.debug(f"Final assistant message #{len(assistant_messages)}: {len(current_assistant_content)} chars")
# Use only the LAST assistant message as the final content
if assistant_messages:
final_content = assistant_messages[-1] # Get the last message
logger.info(f"Final content extracted: {len(final_content)} chars (from {len(assistant_messages)} assistant messages)")
# Debug logging for all assistant messages if multiple found
if len(assistant_messages) > 1:
logger.debug("Multiple assistant messages found. Details:")
for i, msg in enumerate(assistant_messages):
preview = msg[:200] + "..." if len(msg) > 200 else msg
logger.debug(f" Message #{i+1}: {len(msg)} chars - Preview: {preview}")
logger.debug(f"Selected final message preview: {final_content[:200]}...")
else:
final_content = ""
logger.warning("No assistant messages found in SDK stream")
consume_end_time = asyncio.get_event_loop().time()
total_consume_time = consume_end_time - consume_start_time
logger.info(f"Stream buffering completed: {sdk_chunks_received} chunks in {total_consume_time:.2f}s")
logger.info(f"Assistant messages found: {len(assistant_messages)}")
logger.info(f"Final content length: {len(final_content)}")
# Log buffered chunks summary
chunk_types = {}
for chunk in buffered_chunks:
chunk_type = f"{chunk.get('type', 'unknown')}/{chunk.get('subtype', 'unknown')}"
chunk_types[chunk_type] = chunk_types.get(chunk_type, 0) + 1
logger.info(f"Chunk type summary: {chunk_types}")
# Validate XML format if expected
if expects_xml and final_content:
# Check if response uses XML tool format
has_xml_format = MessageAdapter.validate_xml_tool_response(final_content)
if not has_xml_format:
logger.error(f"❌ Expected XML tool format but got plain text response!")
logger.error(f"Response preview: {final_content[:200]}...")
# Note: We can't retry here without changing the architecture significantly
# But at least we log it for debugging
else:
logger.info(f"✅ Response correctly uses XML tool format")
# Now yield the final response
if final_content:
# Send role chunk
initial_chunk = ChatCompletionStreamResponse(
id=request_id,
model=request.model,
choices=[StreamChoice(
index=0,
delta={"role": "assistant", "content": ""},
finish_reason=None
)]
)
yield f"data: {initial_chunk.model_dump_json()}\n\n"
# Filter content - always use chat mode filtering
from response_filter import ResponseFilter
response_filter = ResponseFilter()
filtered_content = response_filter.filter_text(final_content)
# Send content chunk
content_chunk = ChatCompletionStreamResponse(
id=request_id,
model=request.model,
choices=[StreamChoice(
index=0,
delta={"content": filtered_content},
finish_reason=None
)]
)
yield f"data: {content_chunk.model_dump_json()}\n\n"
else:
# No content - send empty response
logger.warning(f"No content found after buffering {sdk_chunks_received} SDK chunks")
initial_chunk = ChatCompletionStreamResponse(
id=request_id,
model=request.model,
choices=[StreamChoice(
index=0,
delta={"role": "assistant", "content": ""},
finish_reason=None
)]
)
yield f"data: {initial_chunk.model_dump_json()}\n\n"
# Send final chunk
final_chunk = ChatCompletionStreamResponse(
id=request_id,
model=request.model,
choices=[StreamChoice(
index=0,
delta={},
finish_reason="stop"