"""The workflow DSL (master plan §3.5): a JSON document, validated by Pydantic. Example:: {"id": "unconfirmed_cod_morning", "name": "Morning unconfirmed COD follow-up", "trigger": {"type": "schedule", "cron": "0 9 * * *", "tz": "Asia/Karachi"}, "steps": [ {"id": "find", "tool": "ecommerce.search_orders", "args": {"payment_method": "COD", "confirmation_status": "pending", "min_total": 5001}}, {"id": "notify", "for_each": "$.find.orders", "tool": "ecommerce.send_whatsapp", "args": {"to": "$.item.phone", "template": "cod_confirm", "template_params": ["$.item.customer_name", "$.item.number"]}}], "policy_overrides": {"max_messages": 200}} References: a string that starts with ``$.`` is replaced by a value at run time: * ``$..``: the output (tool result data) of an earlier step. A ``for_each`` step's output is ``{"results": [{"item", "data", "status"}...], "count", "done"}``. * ``$.item`` / ``$.index``: the current element inside a ``for_each`` step. * ``$.event.``: the triggering event (``type``, ``payload``); untrusted for webhooks. * ``$.trigger.fire_time``: the schedule slot that started the run. Inside a longer string, ``{{ $.ref }}`` interpolates a value as text. Path segments are separated by dots; list indexes are numbers (``$.find.orders.0.number``). Policy overrides can only TIGHTEN limits: every field has a hard ceiling and there is no way to grant a permission (extra keys are rejected). The gateway still decides every call. """ from __future__ import annotations import re from typing import Annotated, Any, Literal from zoneinfo import ZoneInfo from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from core.tools.preview import canonical_json, sha256_hex MAX_STEPS = 25 MAX_ITEMS = 500 # per for_each step MAX_TOOL_CALLS = 1000 # per run MAX_MESSAGES = 500 # per run, tools tagged "message" MAX_WAIT_S = 7 * 24 * 3600 STEP_ID = r"^[a-z][a-z0-9_]{0,39}$" # Roots that are not step ids. RESERVED_ROOTS = frozenset({"item", "index", "event", "trigger", "workflow", "run", "now"}) ConditionOp = Literal[ "eq", "ne", "gt", "gte", "lt", "lte", "in", "not_in", "contains", "exists", "not_exists", "truthy", "falsy", ] class _Strict(BaseModel): model_config = ConfigDict(extra="forbid") class Condition(_Strict): """``left`` is a ``$.`` reference; ``right`` is a literal (or a reference).""" left: str = Field(pattern=r"^\$\.", max_length=300) op: ConditionOp right: Any = None class ScheduleTrigger(_Strict): type: Literal["schedule"] = "schedule" cron: str = Field(min_length=9, max_length=100, description="5-field cron, e.g. 0 9 * * *") tz: str = Field(default="Asia/Karachi", max_length=64) @field_validator("cron") @classmethod def _cron(cls, v: str) -> str: from croniter import croniter if len(v.split()) != 5 or not croniter.is_valid(v): raise ValueError(f"invalid 5-field cron expression {v!r}") return v @field_validator("tz") @classmethod def _tz(cls, v: str) -> str: try: ZoneInfo(v) except Exception as exc: raise ValueError(f"unknown timezone {v!r}") from exc return v class EventTrigger(_Strict): type: Literal["event"] = "event" event_type: str = Field(pattern=r"^[a-z][a-z0-9_.\-]{1,199}$") when: list[Condition] = Field(default_factory=list, max_length=10) @field_validator("event_type") @classmethod def _not_workflow(cls, v: str) -> str: if v.startswith("workflow."): raise ValueError("workflows cannot trigger on workflow.* events (loops)") return v class ManualTrigger(_Strict): type: Literal["manual"] = "manual" Trigger = Annotated[ScheduleTrigger | EventTrigger | ManualTrigger, Field(discriminator="type")] class Retry(_Strict): max_attempts: int = Field(default=1, ge=1, le=5) backoff_s: float = Field(default=0.0, ge=0.0, le=60.0) class Wait(_Strict): seconds: int = Field(ge=1, le=MAX_WAIT_S) class ApprovalGate(_Strict): summary: str = Field(min_length=1, max_length=500, description="what the owner signs off") StepKind = Literal["tool", "wait", "approval"] class Step(_Strict): id: str = Field(pattern=STEP_ID) title: str | None = Field(default=None, max_length=120) tool: str | None = Field(default=None, max_length=200) args: dict[str, Any] = Field(default_factory=dict) for_each: str | None = Field(default=None, pattern=r"^\$\.", max_length=300) when: list[Condition] = Field(default_factory=list, max_length=10) wait: Wait | None = None approval: ApprovalGate | None = None requires_approval: bool = Field( default=False, description="ask a human before this step runs (required for T3 tools)" ) max_items: int | None = Field(default=None, ge=1, le=MAX_ITEMS) on_error: Literal["stop", "continue"] = "stop" retry: Retry = Field(default_factory=Retry) @field_validator("id") @classmethod def _not_reserved(cls, v: str) -> str: if v in RESERVED_ROOTS: raise ValueError(f"step id {v!r} is reserved") return v @model_validator(mode="after") def _one_kind(self) -> Step: kinds = [ k for k, v in (("tool", self.tool), ("wait", self.wait), ("approval", self.approval)) if v is not None ] if len(kinds) != 1: raise ValueError(f"step {self.id}: give exactly one of tool, wait or approval") if kinds[0] != "tool" and (self.args or self.for_each or self.requires_approval): raise ValueError(f"step {self.id}: args/for_each only go with a tool step") return self @property def kind(self) -> StepKind: if self.tool is not None: return "tool" return "wait" if self.wait is not None else "approval" class PolicyOverrides(_Strict): """Limits for this workflow. Each can only be lowered below the hard ceiling.""" max_tier: int = Field(default=3, ge=0, le=3, description="highest tool risk tier allowed") max_items_per_step: int = Field(default=MAX_ITEMS, ge=1, le=MAX_ITEMS) max_tool_calls: int = Field(default=MAX_TOOL_CALLS, ge=1, le=MAX_TOOL_CALLS) max_messages: int = Field(default=MAX_MESSAGES, ge=0, le=MAX_MESSAGES) require_approval_for: list[str] = Field( default_factory=list, max_length=50, description="tools that always need a sign-off" ) class WorkflowDefinition(_Strict): id: str = Field(pattern=r"^[a-z][a-z0-9_]{1,62}$", description="stable slug") version: int | None = Field(default=None, description="assigned when saved") name: str = Field(min_length=1, max_length=120) description: str = Field(default="", max_length=1000) trigger: Trigger steps: list[Step] = Field(min_length=1, max_length=MAX_STEPS) policy_overrides: PolicyOverrides = Field(default_factory=PolicyOverrides) @model_validator(mode="after") def _unique_ids(self) -> WorkflowDefinition: seen: set[str] = set() for s in self.steps: if s.id in seen: raise ValueError(f"duplicate step id {s.id!r}") seen.add(s.id) return self def step(self, step_id: str) -> Step: for s in self.steps: if s.id == step_id: return s raise KeyError(step_id) def content(self) -> dict[str, Any]: """The definition without its version number (what approval and hashes cover).""" return self.model_dump(mode="json", exclude={"version"}) def content_hash(self) -> str: return sha256_hex(canonical_json(self.content())) def parse_definition(data: dict[str, Any] | WorkflowDefinition) -> WorkflowDefinition: if isinstance(data, WorkflowDefinition): return data return WorkflowDefinition.model_validate(data) def slugify(text: str, fallback: str = "workflow") -> str: s = re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_") if not s or not s[0].isalpha(): s = f"{fallback}_{s}".strip("_") return s[:63] if len(s) > 1 else fallback # ------------------------------------------------------------------ plain language def _ref_text(v: Any) -> str: if isinstance(v, str) and v.startswith("$."): return f"«{v[2:]}»" if isinstance(v, list): return "[" + ", ".join(_ref_text(x) for x in v) + "]" if isinstance(v, dict): return "{" + ", ".join(f"{k}: {_ref_text(x)}" for k, x in v.items()) + "}" return str(v) _OPS = { "eq": "is", "ne": "is not", "gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "in": "is one of", "not_in": "is not one of", "contains": "contains", "exists": "exists", "not_exists": "is missing", "truthy": "is set", "falsy": "is not set", } def describe_condition(c: Condition) -> str: if c.op in ("exists", "not_exists", "truthy", "falsy"): return f"{_ref_text(c.left)} {_OPS[c.op]}" return f"{_ref_text(c.left)} {_OPS[c.op]} {_ref_text(c.right)}" def describe_trigger(t: ScheduleTrigger | EventTrigger | ManualTrigger) -> str: if isinstance(t, ScheduleTrigger): return f"On schedule '{t.cron}' ({t.tz})" if isinstance(t, EventTrigger): extra = " when " + " and ".join(describe_condition(c) for c in t.when) if t.when else "" return f"When event '{t.event_type}' arrives{extra}" return "When started by hand" def describe(defn: WorkflowDefinition) -> list[str]: """Deterministic plain-language rendering (the third view next to canvas and JSON).""" lines = [describe_trigger(defn.trigger) + ":"] for i, s in enumerate(defn.steps, 1): if s.kind == "wait": assert s.wait is not None text = f"wait {s.wait.seconds} seconds" elif s.kind == "approval": assert s.approval is not None text = f"ask the owner to sign off: {s.approval.summary}" else: args = ", ".join(f"{k}={_ref_text(v)}" for k, v in s.args.items()) text = f"call {s.tool}({args})" if s.for_each: text = f"for each item in {_ref_text(s.for_each)}, {text}" if s.requires_approval: text += " after a human approves" if s.when: text += " only if " + " and ".join(describe_condition(c) for c in s.when) lines.append(f"{i}. [{s.id}] {text}") return lines