Spaces:
Running

File size: 10,919 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""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:



* ``$.<step_id>.<path>``: 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.<path>``: 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