""" Turso HTTP API layer for remembering skill. This module handles: - Credential initialization via configuring skill - HTTP request retry logic (_retry_with_backoff) - SQL execution via Turso HTTP API (_exec, _exec_batch) - JSON field parsing (_parse_memory_row) Imports from: state, configuring """ import json import os import sys import time import requests from . import state # Import from configuring skill (must be on Python path) try: sys.path.insert(0, '/path/to/claude-skills') # Adjust path as needed from configuring import detect_environment, get_env except ImportError: # Fallback if configuring skill not available from pathlib import Path def _fallback_get_env(key, default=None, required=False): """Minimal fallback if configuring skill not installed.""" value = os.environ.get(key) if not value: # Try /mnt/project/*.env for env_file in Path("/mnt/project").glob("*.env"): for line in env_file.read_text().splitlines(): if line.strip().startswith(f"{key}="): value = line.partition("=")[2].strip() break if required and not value: raise ValueError(f"Required environment variable '{key}' not found") return value or default get_env = _fallback_get_env detect_environment = lambda: "unknown" def _init(): """Lazy-load credentials and URL using getting-env skill.""" if state._TOKEN is None: # Load TURSO_URL (with default) state._URL = get_env("TURSO_URL", default=state._DEFAULT_URL) # Load TURSO_TOKEN (required) try: state._TOKEN = get_env("TURSO_TOKEN", required=True) except ValueError as e: raise RuntimeError(str(e)) from e # Clean token: remove any whitespace if state._TOKEN: state._TOKEN = state._TOKEN.strip().replace(" ", "") state._HEADERS = {"Authorization": f"Bearer {state._TOKEN}", "Content-Type": "application/json"} def _retry_with_backoff(fn, max_retries=3, base_delay=1.0): """Retry a function with exponential backoff on transient errors. Args: fn: Callable that may raise exceptions max_retries: Maximum number of retry attempts (default 3) base_delay: Initial delay in seconds (default 1.0) Returns: Result of fn() if successful Raises: Last exception if all retries exhausted """ for attempt in range(max_retries): try: return fn() except Exception as e: if attempt == max_retries - 1: # Last attempt failed, re-raise raise # Check if it's a retriable error (503, 429, SSL handshake failures) error_str = str(e) is_retriable = ( '503' in error_str or '429' in error_str or 'Service Unavailable' in error_str or 'SSL' in error_str or 'SSLError' in error_str or 'HANDSHAKE_FAILURE' in error_str ) if is_retriable: delay = base_delay * (2 ** attempt) print(f"Warning: API request failed (attempt {attempt + 1}/{max_retries}), retrying in {delay}s: {e}") time.sleep(delay) else: # Non-retriable error, fail immediately raise def _parse_memory_row(row: dict) -> dict: """Parse JSON fields in a memory row (tags, entities, refs). Args: row: Raw row dict from database Returns: Row dict with parsed JSON fields """ # Parse tags field if 'tags' in row and row['tags'] is not None: if isinstance(row['tags'], str): try: row['tags'] = json.loads(row['tags']) except json.JSONDecodeError: row['tags'] = [] # Parse entities field if 'entities' in row and row['entities'] is not None: if isinstance(row['entities'], str): try: row['entities'] = json.loads(row['entities']) except json.JSONDecodeError: row['entities'] = [] # Parse refs field if 'refs' in row and row['refs'] is not None: if isinstance(row['refs'], str): try: row['refs'] = json.loads(row['refs']) except json.JSONDecodeError: row['refs'] = [] return row def _exec_batch(statements: list) -> list: """Execute multiple SQL statements in a single pipeline request. Args: statements: List of SQL strings or (sql, args) tuples Returns: List of result lists (one per statement) Example: results = _exec_batch([ "SELECT * FROM config WHERE category = 'profile'", ("SELECT * FROM memories WHERE type = ?", ["decision"]) ]) profile_data = results[0] decisions = results[1] """ _init() requests_list = [] for stmt in statements: if isinstance(stmt, tuple): sql, args = stmt else: sql, args = stmt, [] request = {"type": "execute", "stmt": {"sql": sql}} if args: request["stmt"]["args"] = [ {"type": "text", "value": str(v)} if v is not None else {"type": "null"} for v in args ] requests_list.append(request) # Add close request requests_list.append({"type": "close"}) try: resp = requests.post( f"{state._URL}/v2/pipeline", headers=state._HEADERS, json={"requests": requests_list}, timeout=30 ).json() except requests.exceptions.SSLError as e: raise RuntimeError( f"SSL error connecting to Turso database. This often indicates missing or invalid credentials.\n" f"Check that TURSO_TOKEN is set correctly.\n" f"Original error: {e}" ) from e except requests.exceptions.RequestException as e: raise RuntimeError( f"Network error connecting to Turso database at {state._URL}\n" f"Check network connectivity and credentials (TURSO_TOKEN).\n" f"Original error: {e}" ) from e # Parse results (exclude the close response) results = [] for r in resp.get("results", [])[:-1]: # Exclude close result if r["type"] != "ok": error_msg = r.get("error", {}).get("message", "Unknown error") error_code = r.get("error", {}).get("code", "UNKNOWN") raise RuntimeError(f"Database error [{error_code}]: {error_msg}") res = r["response"]["result"] cols = [c["name"] for c in res["cols"]] rows = [ {cols[i]: (row[i].get("value") if row[i].get("type") != "null" else None) for i in range(len(cols))} for row in res["rows"] ] # Parse JSON fields if this is a memory query if rows and 'tags' in rows[0]: rows = [_parse_memory_row(row) for row in rows] results.append(rows) return results def _exec(sql, args=None, parse_json: bool = True): """Execute SQL, return list of dicts. Args: sql: SQL query args: Query arguments parse_json: If True, parse JSON fields (tags, entities, refs) in memory rows """ _init() stmt = {"sql": sql} if args: stmt["args"] = [ {"type": "text", "value": str(v)} if v is not None else {"type": "null"} for v in args ] try: resp = requests.post( f"{state._URL}/v2/pipeline", headers=state._HEADERS, json={"requests": [{"type": "execute", "stmt": stmt}]}, timeout=30 ).json() except requests.exceptions.SSLError as e: raise RuntimeError( f"SSL error connecting to Turso database. This often indicates missing or invalid credentials.\n" f"Check that TURSO_TOKEN is set correctly.\n" f"Original error: {e}" ) from e except requests.exceptions.RequestException as e: raise RuntimeError( f"Network error connecting to Turso database at {state._URL}\n" f"Check network connectivity and credentials (TURSO_TOKEN).\n" f"Original error: {e}" ) from e r = resp["results"][0] if r["type"] != "ok": error_msg = r.get("error", {}).get("message", "Unknown error") error_code = r.get("error", {}).get("code", "UNKNOWN") raise RuntimeError(f"Database error [{error_code}]: {error_msg}") res = r["response"]["result"] cols = [c["name"] for c in res["cols"]] rows = [ {cols[i]: (row[i].get("value") if row[i].get("type") != "null" else None) for i in range(len(cols))} for row in res["rows"] ] # Parse JSON fields if this is a memory query if parse_json and rows and 'tags' in rows[0]: rows = [_parse_memory_row(row) for row in rows] return rows