ltcai 1.7.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ """Workflow engine — typed-node workflow definitions, validation, and a
2
+ deterministic execution interpreter with full run observability.
3
+
4
+ A workflow is a small directed graph of *nodes* starting from a ``trigger``.
5
+ Each node has a ``type`` (:data:`NODE_TYPES`), a ``config`` blob, and a ``next``
6
+ pointer (or a list of branches for ``condition`` nodes). The engine walks the
7
+ graph from the trigger, dispatching each node to an injected *runner* and
8
+ recording a step-by-step timeline so a run can be inspected, replayed, and
9
+ linked into the Workspace timeline / Knowledge Graph.
10
+
11
+ The engine is pure logic with injected runners, mirroring
12
+ :class:`latticeai.core.agent.AgentRuntime`:
13
+
14
+ * production wires runners that call the real tool registry, skill registry,
15
+ plugin registry, and multi-agent orchestrator;
16
+ * tests pass fakes and drive a full trigger→...→output run with no server,
17
+ no LLM, and no network.
18
+
19
+ Backward compatibility: legacy workflows persisted as a flat ``steps`` list
20
+ (pre-2.0) still validate and run — :func:`normalize_definition` lifts them into
21
+ a linear node chain so existing workflow history keeps working.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass, field
27
+ from datetime import datetime
28
+ from typing import Any, Callable, Dict, List, Optional
29
+
30
+
31
+ WORKFLOW_ENGINE_VERSION = "2.1.0"
32
+
33
+ # The node vocabulary a workflow can be built from. ``trigger`` and ``output``
34
+ # are structural; the rest dispatch to an injected runner of the same family.
35
+ NODE_TYPES = (
36
+ "trigger",
37
+ "tool",
38
+ "skill",
39
+ "plugin",
40
+ "agent",
41
+ "condition",
42
+ "output",
43
+ )
44
+
45
+ # Which runner family handles each executable node type.
46
+ _RUNNER_FOR = {
47
+ "tool": "tool",
48
+ "skill": "skill",
49
+ "plugin": "plugin",
50
+ "agent": "agent",
51
+ }
52
+
53
+ _MAX_STEPS = 100 # hard cap so a mis-wired ``next`` cycle can never hang a run.
54
+
55
+
56
+ class WorkflowError(Exception):
57
+ """Raised for invalid workflow definitions."""
58
+
59
+
60
+ def _now() -> str:
61
+ return datetime.now().isoformat(timespec="seconds")
62
+
63
+
64
+ def normalize_definition(workflow: Dict[str, Any]) -> Dict[str, Any]:
65
+ """Return a node-based definition, lifting legacy ``steps`` lists if needed.
66
+
67
+ Never mutates the input. A legacy ``{"steps": [...]}`` workflow becomes a
68
+ linear ``trigger -> tool... -> output`` node chain so it validates and runs
69
+ under the v2.0 engine without rewriting stored history.
70
+ """
71
+ nodes = workflow.get("nodes")
72
+ if isinstance(nodes, list) and nodes:
73
+ return {
74
+ "id": workflow.get("id"),
75
+ "name": workflow.get("name") or "Untitled workflow",
76
+ "nodes": nodes,
77
+ "metadata": workflow.get("metadata") or {},
78
+ }
79
+
80
+ steps = workflow.get("steps") or []
81
+ lifted: List[Dict[str, Any]] = [{
82
+ "id": "trigger",
83
+ "type": "trigger",
84
+ "name": "Start",
85
+ "config": {"trigger": "manual"},
86
+ "next": "step-0" if steps else "output",
87
+ }]
88
+ for index, step in enumerate(steps):
89
+ action = str(step.get("action") or "tool") if isinstance(step, dict) else "tool"
90
+ nxt = f"step-{index + 1}" if index + 1 < len(steps) else "output"
91
+ lifted.append({
92
+ "id": f"step-{index}",
93
+ "type": "tool",
94
+ "name": action,
95
+ "config": {"tool": action, "args": step if isinstance(step, dict) else {"value": step}},
96
+ "next": nxt,
97
+ })
98
+ lifted.append({"id": "output", "type": "output", "name": "Output", "config": {}, "next": None})
99
+ return {
100
+ "id": workflow.get("id"),
101
+ "name": workflow.get("name") or "Untitled workflow",
102
+ "nodes": lifted,
103
+ "metadata": {**(workflow.get("metadata") or {}), "lifted_from_steps": True},
104
+ }
105
+
106
+
107
+ def validate_definition(workflow: Dict[str, Any]) -> List[str]:
108
+ """Return a list of validation errors ([] means valid)."""
109
+ errors: List[str] = []
110
+ definition = normalize_definition(workflow)
111
+ nodes = definition["nodes"]
112
+ if not isinstance(nodes, list) or not nodes:
113
+ return ["workflow has no nodes"]
114
+
115
+ ids = [node.get("id") for node in nodes]
116
+ if len(set(ids)) != len(ids):
117
+ errors.append("duplicate node ids")
118
+ id_set = {nid for nid in ids if nid}
119
+
120
+ triggers = [node for node in nodes if node.get("type") == "trigger"]
121
+ if not triggers:
122
+ errors.append("workflow must have a trigger node")
123
+ elif len(triggers) > 1:
124
+ errors.append("workflow must have exactly one trigger node")
125
+
126
+ for node in nodes:
127
+ nid = node.get("id")
128
+ ntype = node.get("type")
129
+ if not nid:
130
+ errors.append("node missing id")
131
+ if ntype not in NODE_TYPES:
132
+ errors.append(f"node '{nid}': unknown type '{ntype}'")
133
+ # Validate edges point at real nodes (None terminates a branch).
134
+ targets: List[Any] = []
135
+ if ntype == "condition":
136
+ branches = node.get("branches") or {}
137
+ if not isinstance(branches, dict) or not branches:
138
+ errors.append(f"condition node '{nid}' must define branches (e.g. true/false)")
139
+ else:
140
+ targets.extend(branches.values())
141
+ else:
142
+ targets.append(node.get("next"))
143
+ for target in targets:
144
+ if target is not None and target not in id_set:
145
+ errors.append(f"node '{nid}' points at unknown node '{target}'")
146
+ return errors
147
+
148
+
149
+ def _entry_node(nodes: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
150
+ for node in nodes:
151
+ if node.get("type") == "trigger":
152
+ return node
153
+ return nodes[0] if nodes else None
154
+
155
+
156
+ def _evaluate_condition(config: Dict[str, Any], context: Dict[str, Any]) -> bool:
157
+ """Safe condition evaluation — NO eval. Compares a context value to a literal.
158
+
159
+ config: ``{"left": "<context key>", "op": "==|!=|>|<|>=|<=|contains|truthy",
160
+ "right": <literal>}``. Unknown keys / ops resolve to ``False`` so a
161
+ mis-configured condition fails closed onto the ``false`` branch.
162
+ """
163
+ left_key = config.get("left")
164
+ op = str(config.get("op") or "truthy")
165
+ right = config.get("right")
166
+ left = context.get(left_key) if left_key in context else config.get("left_value")
167
+ try:
168
+ if op == "truthy":
169
+ return bool(left)
170
+ if op == "==":
171
+ return left == right
172
+ if op == "!=":
173
+ return left != right
174
+ if op == "contains":
175
+ return right in left # type: ignore[operator]
176
+ if op in (">", "<", ">=", "<="):
177
+ lf, rf = float(left), float(right) # type: ignore[arg-type]
178
+ return {">": lf > rf, "<": lf < rf, ">=": lf >= rf, "<=": lf <= rf}[op]
179
+ except Exception:
180
+ return False
181
+ return False
182
+
183
+
184
+ @dataclass
185
+ class WorkflowRun:
186
+ workflow_id: Optional[str]
187
+ name: str
188
+ status: str = "ok" # ok | failed | partial
189
+ timeline: List[Dict[str, Any]] = field(default_factory=list)
190
+ outputs: Dict[str, Any] = field(default_factory=dict)
191
+ started_at: str = field(default_factory=_now)
192
+ finished_at: Optional[str] = None
193
+
194
+ def as_dict(self) -> Dict[str, Any]:
195
+ return {
196
+ "workflow_id": self.workflow_id,
197
+ "name": self.name,
198
+ "status": self.status,
199
+ "timeline": self.timeline,
200
+ "outputs": self.outputs,
201
+ "started_at": self.started_at,
202
+ "finished_at": self.finished_at,
203
+ "step_count": len(self.timeline),
204
+ }
205
+
206
+
207
+ class WorkflowEngine:
208
+ """Interprets a validated workflow definition over injected runners.
209
+
210
+ ``runners`` maps a family ("tool" / "skill" / "plugin" / "agent") to a
211
+ callable ``runner(node, context) -> Any``. A missing runner records the
212
+ node as ``skipped`` with a reason rather than failing the whole run, so a
213
+ workflow that references a capability the host has not wired degrades
214
+ gracefully (and the gap is visible in the timeline).
215
+ """
216
+
217
+ def __init__(self, runners: Optional[Dict[str, Callable[..., Any]]] = None):
218
+ self.runners = runners or {}
219
+
220
+ def run(self, workflow: Dict[str, Any], *, inputs: Optional[Dict[str, Any]] = None) -> WorkflowRun:
221
+ definition = normalize_definition(workflow)
222
+ errors = validate_definition(definition)
223
+ run = WorkflowRun(workflow_id=definition.get("id"), name=definition.get("name") or "workflow")
224
+ if errors:
225
+ run.status = "failed"
226
+ run.timeline.append({"node": None, "type": "validation", "status": "failed", "errors": errors, "timestamp": _now()})
227
+ run.finished_at = _now()
228
+ return run
229
+
230
+ nodes = {node["id"]: node for node in definition["nodes"]}
231
+ context: Dict[str, Any] = {"inputs": inputs or {}, **(inputs or {})}
232
+
233
+ current = _entry_node(definition["nodes"])
234
+ steps = 0
235
+ had_error = False
236
+ had_skip = False
237
+ while current is not None and steps < _MAX_STEPS:
238
+ steps += 1
239
+ ntype = current.get("type")
240
+ nid = current.get("id")
241
+ entry: Dict[str, Any] = {
242
+ "node": nid,
243
+ "type": ntype,
244
+ "name": current.get("name") or nid,
245
+ "timestamp": _now(),
246
+ }
247
+
248
+ if ntype == "trigger":
249
+ entry["status"] = "ok"
250
+ entry["trigger"] = (current.get("config") or {}).get("trigger", "manual")
251
+ run.timeline.append(entry)
252
+ current = nodes.get(current.get("next")) if current.get("next") else None
253
+ continue
254
+
255
+ if ntype == "output":
256
+ entry["status"] = "ok"
257
+ payload = (current.get("config") or {}).get("value")
258
+ entry["output"] = payload if payload is not None else context.get("last_output")
259
+ run.outputs[nid] = entry["output"]
260
+ run.timeline.append(entry)
261
+ current = nodes.get(current.get("next")) if current.get("next") else None
262
+ continue
263
+
264
+ if ntype == "condition":
265
+ result = _evaluate_condition(current.get("config") or {}, context)
266
+ entry["status"] = "ok"
267
+ entry["result"] = result
268
+ run.timeline.append(entry)
269
+ branches = current.get("branches") or {}
270
+ target = branches.get("true" if result else "false")
271
+ current = nodes.get(target) if target else None
272
+ continue
273
+
274
+ # Executable node → dispatch to its runner family.
275
+ family = _RUNNER_FOR.get(ntype)
276
+ runner = self.runners.get(family) if family else None
277
+ if runner is None:
278
+ entry["status"] = "skipped"
279
+ entry["reason"] = f"no '{family}' runner configured"
280
+ had_skip = True
281
+ run.timeline.append(entry)
282
+ current = nodes.get(current.get("next")) if current.get("next") else None
283
+ continue
284
+ try:
285
+ result = runner(node=current, context=context)
286
+ entry["status"] = "ok"
287
+ entry["result"] = result
288
+ context["last_output"] = result
289
+ context[nid] = result
290
+ except Exception as exc:
291
+ entry["status"] = "error"
292
+ entry["reason"] = str(exc)
293
+ had_error = True
294
+ run.timeline.append(entry)
295
+ current = nodes.get(current.get("next")) if current.get("next") else None
296
+
297
+ if steps >= _MAX_STEPS:
298
+ run.timeline.append({"node": None, "type": "guard", "status": "error", "reason": f"exceeded {_MAX_STEPS} steps (cycle?)", "timestamp": _now()})
299
+ had_error = True
300
+
301
+ run.status = "failed" if had_error else ("partial" if had_skip else "ok")
302
+ run.finished_at = _now()
303
+ return run
304
+
305
+
306
+ def export_workflow(workflow: Dict[str, Any]) -> Dict[str, Any]:
307
+ """Portable JSON representation (definition only — no run history / scope)."""
308
+ definition = normalize_definition(workflow)
309
+ return {
310
+ "lattice_workflow_export": WORKFLOW_ENGINE_VERSION,
311
+ "name": definition.get("name"),
312
+ "nodes": definition.get("nodes"),
313
+ "metadata": {k: v for k, v in (definition.get("metadata") or {}).items() if k != "lifted_from_steps"},
314
+ }
315
+
316
+
317
+ def import_workflow(data: Dict[str, Any]) -> Dict[str, Any]:
318
+ """Validate an exported workflow and return a definition ready to persist."""
319
+ if not isinstance(data, dict):
320
+ raise WorkflowError("import payload must be a JSON object")
321
+ definition = {
322
+ "name": data.get("name") or "Imported workflow",
323
+ "nodes": data.get("nodes") or [],
324
+ "metadata": {**(data.get("metadata") or {}), "imported": True},
325
+ }
326
+ errors = validate_definition(definition)
327
+ if errors:
328
+ raise WorkflowError("; ".join(errors))
329
+ return definition