File size: 10,084 Bytes
2be8520
 
 
 
 
 
 
ef21765
2be8520
2ae943a
2be8520
dca87f5
 
 
ef21765
 
6920374
 
 
 
 
 
 
 
 
 
 
 
 
20b8ffd
 
 
ef21765
dca87f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be8520
 
5e8b843
446b8d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a59e41
 
bca188b
5f8e351
 
446b8d3
5f8e351
6487910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6920374
 
 
 
 
 
 
 
 
 
 
b88e499
6487910
bca188b
6487910
 
bca188b
d147990
 
 
 
 
 
 
 
 
 
 
6487910
 
 
8a59e41
 
1405c4c
2be8520
 
 
 
 
 
 
 
 
2ae943a
5c9db21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be8520
4fad1b7
2be8520
4fad1b7
5c9db21
2be8520
4fad1b7
5c9db21
 
4fad1b7
2be8520
 
 
 
5c9db21
2be8520
 
4fad1b7
5c9db21
2be8520
 
 
 
5c9db21
2be8520
 
4fad1b7
5c9db21
2be8520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef21765
 
46a5714
2be8520
9191e07
 
 
 
46a5714
2be8520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fe23c
2be8520
a5fe23c
2be8520
 
 
a5fe23c
2be8520
 
a5fe23c
2be8520
 
a5fe23c
2be8520
 
 
 
a5fe23c
2be8520
1405c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Error handling utilities for HuggingClaw - Cain.
Provides specific exception handlers for common operations.
"""
import json
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse

# CRITICAL: Set up sys.path for agents imports at module load time
# This ensures `from agents import brain_minimal` works regardless of import order
# Dynamic path resolution with fallbacks for different Docker contexts
_script_dir = Path(os.path.abspath(os.path.dirname(__file__)))  # Absolute path of this script

# Try multiple possible locations for .openclaw directory
_possible_openclaw_paths = [
    _script_dir / ".openclaw",           # /app/.openclaw (legacy/flat structure)
    _script_dir / "openclaw" / ".openclaw",  # /app/openclaw/.openclaw (nested structure)
    Path("/app/openclaw/.openclaw"),     # Absolute Docker path (nested)
    Path("/app/.openclaw"),              # Absolute Docker path (flat)
]

# Add all valid paths to sys.path
for path_dir in _possible_openclaw_paths:
    path_str = str(path_dir)
    if path_str not in sys.path and path_dir.exists():
        sys.path.insert(0, path_str)


async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    """
    FastAPI exception handler for HTTPException.

    Args:
        request: The incoming request.
        exc: The HTTPException that was raised.

    Returns:
        JSONResponse with error details.
    """
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": True,
            "message": exc.detail,
            "status_code": exc.status_code,
            "agent": "cain"
        },
    )


async def generic_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """
    FastAPI exception handler for generic exceptions.

    Args:
        request: The incoming request.
        exc: The Exception that was raised.

    Returns:
        JSONResponse with error details.
    """
    return JSONResponse(
        status_code=500,
        content={
            "error": True,
            "message": "Internal server error",
            "detail": str(exc),
            "type": type(exc).__name__,
            "agent": "cain"
        },
    )


# Configuration path - cain_status.json location
def _get_base_dir() -> Path:
    """Determine the correct base directory dynamically."""
    # Priority 1: OPENCLAW_DATA_DIR (set by Docker environment)
    data_dir = os.environ.get('OPENCLAW_DATA_DIR')
    if data_dir:
        return Path(data_dir)

    # Priority 2: /data (standard Docker volume mount)
    data_path = Path("/data")
    if data_path.exists():
        return data_path

    # Priority 3: Use this script's directory as fallback
    return Path(os.path.dirname(__file__))


def _resolve_status_file() -> Path:
    """Find cain_status.json by searching common locations."""
    # Priority 1: CAIN_STATUS_PATH env var (set by app.py from OPENCLAW_DATA_DIR)
    env_path = os.environ.get('CAIN_STATUS_PATH')
    if env_path:
        return Path(env_path)

    # Priority 2: CAIN_STATUS_FILE env var (legacy)
    env_path = os.environ.get('CAIN_STATUS_FILE')
    if env_path:
        return Path(env_path)

    # Priority 3: OPENCLAW_DATA_DIR + cain_status.json
    data_dir = os.environ.get('OPENCLAW_DATA_DIR')
    if data_dir:
        data_path = Path(data_dir) / "cain_status.json"
        if data_path.exists():
            return data_path

    # Priority 4: /data/cain_status.json (Docker volume mount, default)
    data_path = Path("/data/cain_status.json")
    if data_path.exists():
        return data_path

    # Priority 5: /app/.openclaw/agents/cain_status.json OR /app/openclaw/.openclaw/agents/cain_status.json
    _script_dir = Path(os.path.abspath(os.path.dirname(__file__)))
    _possible_status_paths = [
        Path("/app/.openclaw/agents/cain_status.json"),         # Flat structure
        Path("/app/openclaw/.openclaw/agents/cain_status.json"), # Nested structure
        _script_dir / ".openclaw" / "agents" / "cain_status.json",
        _script_dir / "openclaw" / ".openclaw" / "agents" / "cain_status.json",
    ]
    for openclaw_status in _possible_status_paths:
        if openclaw_status.exists():
            return openclaw_status

    # Priority 6: /app/cain_status.json (legacy location)
    app_path = Path("/app/cain_status.json")
    if app_path.parent.exists():
        return app_path

    # Priority 6.5: Memory directory paths (CRITICAL: can have stale 'unknown' errors)
    _script_dir = Path(os.path.abspath(os.path.dirname(__file__)))
    _memory_paths = [
        Path("/app/memory/cain_status.json"),
        Path("/data/memory/cain_status.json"),
        _script_dir / "memory" / "cain_status.json",
    ]
    for mem_path in _memory_paths:
        if mem_path.exists():
            return mem_path

    # Priority 7: Script directory as final fallback
    script_dir = Path(os.path.dirname(__file__))
    return script_dir / "cain_status.json"

STATUS_FILE = _resolve_status_file()


def handle_status_file_read() -> Dict[str, Any]:
    """
    Handle reading Cain's status file with specific exception handling.

    Returns:
        Status dictionary with current_state, last_updated, and agent fields.
    """
    try:
        with open(str(STATUS_FILE), "r") as f:
            data = json.load(f)

        # CRITICAL: Clean stale "unknown" error strings immediately after reading
        # This prevents "Error: unknown" display issues
        error = data.get('error')
        if isinstance(error, str) and error.strip().lower() in ('unknown', 'none', 'null', ''):
            data['error'] = None
            data['_cleaned_at'] = 'handle_status_file_read'
            # Write back the cleaned data
            try:
                with open(str(STATUS_FILE), "w") as f:
                    json.dump(data, f, indent=2)
            except Exception:
                pass  # Don't fail if we can't write back

        return data
    except FileNotFoundError:
        # Status file not found is not an error - return healthy default
        return {
            "current_state": "idle",
            "stage": "STATUS_FILE_NOT_FOUND",
            "last_updated": datetime.utcnow().isoformat() + "+00:00",
            "agent": "cain",
            "error": None,
            "status_file": str(STATUS_FILE),
            "note": "Status file not found - using default"
        }
    except PermissionError as e:
        return {
            "current_state": "error",
            "stage": "PERMISSION_ERROR",
            "last_updated": datetime.utcnow().isoformat() + "+00:00",
            "agent": "cain",
            "error": f"Permission denied reading status file: {str(e)}",
            "status_file": str(STATUS_FILE)
        }
    except json.JSONDecodeError as e:
        return {
            "current_state": "error",
            "stage": "JSON_DECODE_ERROR",
            "last_updated": datetime.utcnow().isoformat() + "+00:00",
            "agent": "cain",
            "error": f"Invalid JSON in status file: {str(e)}",
            "status_file": str(STATUS_FILE)
        }


def handle_brain_response(message: str) -> str:
    """
    Handle brain processing with specific exception handling.

    Args:
        message: The user message to process.

    Returns:
        Response string from the brain or error message.

    Raises:
        ImportError: If brain module cannot be imported.
        AttributeError: If required brain methods are missing.
    """
    try:
        # sys.path is already set up at module level (see top of file)
        # Import agents directly - no need to import openclaw first
        from agents import brain_minimal

        # Verify brain has required method before calling
        if not hasattr(brain_minimal, 'get_brain'):
            return "Brain interface error: get_brain method not found"

        brain = brain_minimal.get_brain(agent_name="cain", legacy_mode=True)
        result = brain._conversation_process(message)

        if result.get("success"):
            return result.get("response", f"Processed: {message}")
        else:
            return f"Error: {result.get('error', 'Unknown error')}"

    except ImportError as e:
        return f"Brain module import error: {str(e)}"
    except AttributeError as e:
        return f"Brain interface error: {str(e)}"
    except KeyError as e:
        return f"Brain response format error: missing key {str(e)}"
    except Exception as e:
        return f"Brain processing error: {type(e).__name__}: {str(e)}"


async def handle_websocket_send(websocket, status_data: dict) -> bool:
    """
    Handle websocket send with specific exception handling.

    Args:
        websocket: The WebSocket connection object.
        status_data: Status data to send.

    Returns:
        True if send succeeded, False if connection should close.
    """
    try:
        await websocket.send_json({
            "type": "heartbeat",
            "status": status_data
        })
        return True
    except (ConnectionError, RuntimeError, Exception):
        return False


def write_cain_status(status_data: Dict[str, Any]) -> bool:
    """
    Write Cain's status to the status file.

    Args:
        status_data: Dictionary with status information to write.

    Returns:
        True if write succeeded, False otherwise.
    """
    try:
        # Ensure directory exists
        STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)

        # Add timestamp if not present
        if "last_updated" not in status_data:
            status_data["last_updated"] = datetime.utcnow().isoformat() + "+00:00"

        # Write to file
        with open(str(STATUS_FILE), "w") as f:
            json.dump(status_data, f, indent=2)

        return True
    except (PermissionError, OSError, json.JSONDecodeError) as e:
        print(f"Error writing status file: {e}")
        return False