""" ALLI Wave-1 Strict Type Casting & Workspace Env Handlers (SSOT) Single shared implementation for variable assignment, literal coercion, type_cast, and isolated workspace sys.env_get / sys.env_set runtime execution. """ import json import math from typing import Any, Dict, Tuple from language_core.input_transforms import parse_safe_literal_or_json from language_core.workspace_env_contracts import mask_env_value, validate_env_key, validate_env_value from runtime_environment.env_injection import get_active_run_env ALLOWED_TYPE_CAST_TARGETS: Tuple[str, ...] = ("int", "float", "str", "bool", "list", "dict", "json") _CAST_ALIASES: Dict[str, str] = { "integer": "int", "number": "float", "string": "str", "text": "str", "boolean": "bool", } _TRUTHY_BOOL_STRS = frozenset({"true", "1", "yes", "on"}) _FALSY_BOOL_STRS = frozenset({"false", "0", "no", "off"}) def normalize_cast_target(raw_target: Any, *, allow_any: bool = False) -> str: """Normalize type name to a safe allowlisted target type or raise ValueError.""" norm = str(raw_target or "str").strip().lower() norm = _CAST_ALIASES.get(norm, norm) if allow_any and norm in ("any", ""): return "any" if norm not in ALLOWED_TYPE_CAST_TARGETS: raise ValueError( f"[ERR-TYPE-CAST] Unsupported target_type '{raw_target}'. Allowed types: {', '.join(ALLOWED_TYPE_CAST_TARGETS)}." ) return norm def _parse_bool_strict(val: Any) -> bool: if isinstance(val, bool): return val if isinstance(val, (int, float)) and not isinstance(val, bool): if math.isnan(float(val)) or math.isinf(float(val)): raise ValueError("[ERR-TYPE-CAST] Non-finite number cannot be cast to bool.") if val in (0, 1, 0.0, 1.0): return bool(val) if isinstance(val, str): s = val.strip().lower() if s == "": return False if s in _TRUTHY_BOOL_STRS: return True if s in _FALSY_BOOL_STRS: return False raise ValueError(f"[ERR-TYPE-CAST] Cannot parse string '{val}' cleanly as bool (expected true/false/1/0/yes/no).") return bool(val) def strict_cast_value(val: Any, target_type: Any, *, allow_any: bool = False) -> Any: """Strictly convert a value into a canonical Python/JSON type without eval().""" ttype = normalize_cast_target(target_type, allow_any=allow_any) if ttype == "any": return val if ttype == "int": if isinstance(val, bool): return int(val) if isinstance(val, float): if not math.isfinite(val): raise ValueError("[ERR-TYPE-CAST] Non-finite float cannot be cast to int.") return int(val) try: return int(val) except (ValueError, TypeError) as exc: raise ValueError(f"[ERR-TYPE-CAST] Cannot convert {val!r} to int.") from exc if ttype == "float": try: f = float(val) except (ValueError, TypeError) as exc: raise ValueError(f"[ERR-TYPE-CAST] Cannot convert {val!r} to float.") from exc if not math.isfinite(f): raise ValueError("[ERR-TYPE-CAST] Non-finite value cannot be cast to float.") return f if ttype == "str": return str(val) if ttype == "bool": return _parse_bool_strict(val) if ttype == "list": if isinstance(val, list): return list(val) if isinstance(val, (tuple, set)): return list(val) if isinstance(val, str): if len(val) > 4096: raise ValueError("[ERR-TYPE-CAST] Literal payload exceeds 4096-character limit.") ok, parsed = parse_safe_literal_or_json(val) if ok and isinstance(parsed, list): return parsed return list(val) raise ValueError(f"[ERR-TYPE-CAST] Cannot convert {type(val).__name__} to list.") if ttype == "dict": if isinstance(val, dict): return dict(val) if isinstance(val, str): if len(val) > 4096: raise ValueError("[ERR-TYPE-CAST] Literal payload exceeds 4096-character limit.") ok, parsed = parse_safe_literal_or_json(val) if ok and isinstance(parsed, dict): return parsed raise ValueError(f"[ERR-TYPE-CAST] String '{val}' is not a valid dict/JSON object literal.") return dict(val) if ttype == "json": if isinstance(val, str): try: return json.loads(val) except Exception as exc: raise ValueError(f"[ERR-TYPE-CAST] Invalid JSON payload: {exc}") from exc return json.dumps(val) return val def exec_sys_env_get(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Read an environment variable strictly from active Workspace RunEnvContext or explicit fallback.""" raw_key = inputs.get("key") if inputs.get("key") is not None else (params.get("key") or "ENV_VAR") ok_key, clean_key_or_code, err_key = validate_env_key(raw_key) if not ok_key: raise ValueError(f"[{clean_key_or_code}] {err_key}") default_val = inputs.get("default_val") if "default_val" in inputs else params.get("default_val") active_env = get_active_run_env() if active_env and active_env.is_viewer: raise PermissionError("[ERR-RBAC-SECRET-DENIED] Viewers cannot read workspace environment variables.") if active_env: resolved = active_env.read_var(clean_key_or_code) if resolved is not None: return {"result": resolved, "val": resolved, "out": resolved, "key": clean_key_or_code, "found": True} if default_val not in (None, ""): return {"result": default_val, "val": default_val, "out": default_val, "key": clean_key_or_code, "found": False} raise PermissionError( f"[ERR-SECURITY-ENV-SANDBOX] Reading host env var '{clean_key_or_code}' is blocked in sandboxed preview; " f"configure '{clean_key_or_code}' in Workspace .env or set a non-empty 'default_val'." ) def exec_sys_env_set(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Bind an ephemeral run-scoped environment variable inside active RunEnvContext (never persists to DB or host).""" raw_key = inputs.get("key") if inputs.get("key") is not None else (params.get("key") or "APP_CONFIG_VAR") ok_key, clean_key_or_code, err_key = validate_env_key(raw_key) if not ok_key: raise ValueError(f"[{clean_key_or_code}] {err_key}") raw_val = inputs.get("value") if "value" in inputs else params.get("value") ok_val, clean_val_or_code, err_val = validate_env_value("" if raw_val is None else raw_val) if not ok_val: raise ValueError(f"[{clean_val_or_code}] {err_val}") active_env = get_active_run_env() if active_env and active_env.is_viewer: raise PermissionError("[ERR-RBAC-SECRET-DENIED] Viewers cannot set workspace environment variables.") if active_env: active_env.write_var(clean_key_or_code, clean_val_or_code) return { "result": mask_env_value(clean_val_or_code), "val": mask_env_value(clean_val_or_code), "out": clean_key_or_code, "key": clean_key_or_code, "applied": True, } def exec_sys_env(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Unified separate .env node dispatcher supporting mode='get' (default) or mode='set'.""" mode = str((inputs.get("mode") if "mode" in inputs else params.get("mode")) or "get").strip().lower() if mode == "set": return exec_sys_env_set(inputs, params) return exec_sys_env_get(inputs, params) _ENV_NODE_DEFINITION_CACHE: Any = None def get_env_node_definition(node_type: str) -> Any: """Return a validated NodeDefinition for the unified separate .env node without altering CANONICAL_NODE_COUNT.""" global _ENV_NODE_DEFINITION_CACHE norm = str(node_type or "").strip().lower() if norm not in ("sys.env", "alli.sys.env", "sys.env_get", "sys.env_set", "env", "dotenv"): return None if _ENV_NODE_DEFINITION_CACHE is None: from language_core.node_definition import NodeDefinition from language_core.schema_types import ParameterDefinition, ParameterOption, ParameterType, PortDefinition _ENV_NODE_DEFINITION_CACHE = NodeDefinition( type="sys.env", label=".env Environment", category="Environment", version="1.0.0", description="Dedicated .env node to read or configure environment variables safely via Workspace .env Vault.", icon="KeyRound", inputs=[ PortDefinition(id="value", name="Value", type="any", required=False, description="Optional runtime value when mode is set"), ], outputs=[ PortDefinition(id="result", name="Env Value", type="str", required=False, description="Resolved or masked environment value"), PortDefinition(id="key", name="Key", type="str", required=False, description="Environment key name"), PortDefinition(id="found", name="Found", type="bool", required=False, description="Whether key exists in Workspace .env"), ], parameters=[ ParameterDefinition( id="mode", name="Mode", type=ParameterType.SELECT, default="get", required=False, options=[ParameterOption(value="get", label="Read (.env / os.getenv)"), ParameterOption(value="set", label="Set Session (.env)")], description="Read from Workspace .env or bind a run-scoped key.", ), ParameterDefinition(id="key", name="Env Key", type=ParameterType.STRING, default="APP_MODE", required=True, description="UPPER_SNAKE_CASE environment key name."), ParameterDefinition(id="default_val", name="Default Fallback", type=ParameterType.STRING, default="", required=False, description="Safe fallback when unset (never store secrets here)."), ParameterDefinition(id="value", name="Session Value", type=ParameterType.STRING, default="", required=False, description="Run-scoped value used only when mode is set."), ParameterDefinition(id="var_name", name="Python Variable", type=ParameterType.STRING, default="env_val", required=False, is_identifier=True, description="Target Python identifier in generated code."), ParameterDefinition(id="is_secret", name="Mask Secret Output", type=ParameterType.BOOLEAN, default=False, required=False, description="Mask values in logs/output telemetry."), ], ) return _ENV_NODE_DEFINITION_CACHE