File size: 10,784 Bytes
8628c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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