auto / language_core /nodes /nodes_data.py
rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98
Raw History Blame Contribute Delete
10.2 kB
"""
ALLI Domain Nodes: Variables, Constants, Type Casting & Data Structures.
Covers: core.variable, core.constant, constant.*, core.type_cast, data.list, data.dict, data.tuple, data.set.
"""
import ast
import json
from typing import Any, Dict
from language_core.node_definition import PossibleException
from language_core.nodes.loader import parse_safe_literal_or_json, register_domain_nodes
CONST_METADATA_MAP = {
"int": {
"summary": "Signed integer constant value.",
"description": "Emits an immutable Python signed integer numerical constant.",
"url": "https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex",
"sample": 42,
"raw_str": "42",
"time_c": "O(1)",
"space_c": "O(1)",
"assumptions": "Primitive integer constant allocation",
"exceptions": [PossibleException(type="ValueError", condition="literal_value is not a valid integer representation")],
},
"float": {
"summary": "Floating-point numeric constant value.",
"description": "Emits an immutable IEEE 754 double-precision floating-point constant.",
"url": "https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex",
"sample": 3.14159,
"raw_str": "3.14159",
"time_c": "O(1)",
"space_c": "O(1)",
"assumptions": "IEEE 754 double-precision constant allocation",
"exceptions": [PossibleException(type="ValueError", condition="literal_value cannot be parsed into a float")],
},
"str": {
"summary": "Text string literal constant.",
"description": "Emits an immutable Unicode UTF-8 string literal constant.",
"url": "https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str",
"sample": "hello",
"raw_str": "hello",
"time_c": "O(1)",
"space_c": "O(N)",
"assumptions": "N is string character count",
"exceptions": [],
},
"bool": {
"summary": "Boolean truth value constant.",
"description": "Emits an immutable boolean truth value constant (True or False).",
"url": "https://docs.python.org/3/library/stdtypes.html#boolean-type-bool",
"sample": True,
"raw_str": "True",
"time_c": "O(1)",
"space_c": "O(1)",
"assumptions": "Singleton boolean instance reference",
"exceptions": [],
},
}
def _exec_core_variable(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
from language_core.executor.wave1_handlers import strict_cast_value
val = inputs.get("in_val") if "in_val" in inputs else inputs.get("in")
if val is None:
val = params.get("literal_value")
if val is None:
val = params.get("value", 0)
cast_type = str(params.get("var_type") or "any").strip().lower()
if cast_type and cast_type != "any":
val = strict_cast_value(val, cast_type, allow_any=True)
var_name = str(params.get("var_name") or "variable")
return {"out_val": val, "val": val, "result": val, "out": val, "value": val, "name": var_name}
def _exec_core_constant(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
raw = params.get("literal_value")
if raw is None:
raw = params.get("value")
if raw is None:
raw = params.get("val", "100")
ctype = params.get("const_type")
if not ctype:
if isinstance(raw, bool) or str(raw).lower() in ("true", "false"):
ctype = "bool"
elif isinstance(raw, float) or ("." in str(raw) and str(raw).replace(".", "", 1).replace("-", "", 1).isdigit()):
ctype = "float"
elif str(raw).lstrip("-").isdigit():
ctype = "int"
else:
ctype = "str"
if ctype == "int":
try:
val = int(raw)
except (ValueError, TypeError):
val = int(float(raw))
elif ctype == "float":
val = float(raw)
elif ctype == "str":
val = str(raw)
elif ctype == "bool":
val = str(raw).lower() in ("true", "1", "yes")
elif ctype in ("list", "dict"):
raw_str = str(raw)
if len(raw_str) > 4096:
raise ValueError("Constant literal payload exceeds maximum limit of 4096 characters.")
try:
val = json.loads(raw_str)
except Exception:
val = ast.literal_eval(raw_str)
else:
val = raw
return {"out": val, "val": val, "result": val, "value": val}
def _exec_type_cast(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
from language_core.executor.wave1_handlers import strict_cast_value
val = inputs["value"] if "value" in inputs else inputs.get("in_val", params.get("value", 0))
ttype = params.get("target_type", "int")
res = strict_cast_value(val, ttype)
return {"result": res}
def _parse_collection(raw: Any) -> Any:
if isinstance(raw, (list, tuple, set, dict)):
return raw
ok, parsed = parse_safe_literal_or_json(raw)
if ok:
return parsed
raise ValueError(f"Cannot safely parse collection literal: {raw!r}")
def _exec_data_list(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
op = params.get("operation", "create")
if inputs.get("items") is not None:
raw_items = inputs["items"]
lst = list(_parse_collection(raw_items)) if isinstance(raw_items, str) else list(raw_items)
else:
init_val = params.get("initial_items") or params.get("initial_list", "[10, 20, 30]")
lst = list(init_val) if isinstance(init_val, (list, tuple)) else list(_parse_collection(init_val))
if op == "append":
lst.append(inputs.get("item", 99))
res: Any = lst
elif op == "get_index":
idx = int(inputs.get("index", params.get("index", 0)))
res = lst[idx] if 0 <= idx < len(lst) else None
elif op == "length":
res = len(lst)
else:
res = lst
return {"list_out": lst, "result": res, "val": res, "item": inputs.get("item"), "length": len(lst), "count": len(lst), "out": lst}
def _exec_data_dict(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
op = params.get("operation", "create")
if inputs.get("dict_in") is not None:
raw_d = inputs["dict_in"]
d = dict(_parse_collection(raw_d)) if isinstance(raw_d, str) else dict(raw_d)
else:
init_val = params.get("initial_pairs") or params.get("initial_dict", '{"status": "ok", "code": 200}')
d = dict(init_val) if isinstance(init_val, dict) else dict(_parse_collection(init_val))
k = inputs.get("key") or params.get("key", "status")
if op == "get":
res: Any = d.get(k)
elif op == "set":
d[k] = inputs.get("value") if inputs.get("value") is not None else params.get("value", "updated")
res = d
elif op == "keys":
res = list(d.keys())
elif op == "values":
res = list(d.values())
else:
res = d
return {"dict_out": d, "result": res, "val": res, "keys": list(d.keys()), "values": list(d.values()), "length": len(d), "out": d}
def _exec_data_tuple(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
has_explicit = any(
inputs.get(k) is not None or k in params for k in ("item_1", "item_2", "item_3")
)
raw_items = inputs.get("items") if inputs.get("items") is not None else params.get("items")
if not has_explicit and raw_items is not None:
parsed = _parse_collection(raw_items) if isinstance(raw_items, str) else raw_items
t = tuple(parsed) if isinstance(parsed, (list, tuple, set)) else (parsed,)
i1 = t[0] if len(t) > 0 else None
i2 = t[1] if len(t) > 1 else None
else:
i1 = inputs.get("item_1") if inputs.get("item_1") is not None else params.get("item_1", 1)
i2 = inputs.get("item_2") if inputs.get("item_2") is not None else params.get("item_2", 2)
i3 = inputs.get("item_3") if inputs.get("item_3") is not None else params.get("item_3", 3)
t = (i1, i2, i3)
return {"tuple_out": t, "item_1": i1, "item_2": i2, "result": t, "val": t, "length": len(t), "count": len(t), "out": t}
def _exec_data_set(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:
op = params.get("operation", "create")
if inputs.get("set_a") is not None:
raw_a = inputs["set_a"]
s = set(_parse_collection(raw_a)) if isinstance(raw_a, str) else set(raw_a)
else:
raw_init = params.get("initial_elements") if params.get("initial_elements") is not None else params.get("initial_items", "[1, 2, 3, 2, 1]")
s = set(_parse_collection(raw_init))
raw_b = inputs.get("set_b")
set_b = set(_parse_collection(raw_b)) if isinstance(raw_b, str) else (set(raw_b) if raw_b is not None else set())
add_el = (
inputs.get("element") if inputs.get("element") is not None
else (inputs.get("add_item") if inputs.get("add_item") is not None else (params.get("add_item") if params.get("add_item") is not None else params.get("element")))
)
if op == "add" or (op == "create" and add_el is not None):
s.add(add_el if add_el is not None else 4)
elif op == "union":
s = s.union(set_b)
elif op == "intersection":
s = s.intersection(set_b)
elif op == "difference":
s = s.difference(set_b)
is_mem = add_el in s if add_el is not None else False
return {"set_out": s, "cardinality": len(s), "count": len(s), "result": s, "val": s, "size": len(s), "is_member": is_mem, "out": s}
EXECUTORS = {
"core.variable": _exec_core_variable,
"core.constant": _exec_core_constant,
"constant.int": _exec_core_constant,
"constant.float": _exec_core_constant,
"constant.str": _exec_core_constant,
"constant.bool": _exec_core_constant,
"core.type_cast": _exec_type_cast,
"custom.type_cast": _exec_type_cast,
"data.list": _exec_data_list,
"data.dict": _exec_data_dict,
"data.tuple": _exec_data_tuple,
"data.set": _exec_data_set,
}
def register_data_nodes(registry: Any) -> None:
register_domain_nodes(registry, "data", EXECUTORS)