Spaces:
Running

File size: 28,492 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
"""DSL -> LangGraph: active workflow versions run as ordinary agent runs.



The main graph gets one static core node, ``workflow.run`` (event type and intent), which is a

subgraph::



    admit -> execute -> report



* ``admit`` loads the workflow version named by the event and refuses anything that is not

  the workflow's active version (so a rollback stops future runs at once).

* ``execute`` compiles the immutable definition into a LangGraph ``StateGraph`` with one node

  per step and invokes it as a nested graph. It inherits the run's Postgres checkpointer, so

  finished steps are never re-run after a pause or a crash, and their outputs (which later

  steps reference) are stable.

* ``report`` writes the run summary and, after a failure, a self-healing proposal.



Every tool call goes through the gateway (``ToolCaller`` / ``Gateway.execute``) with a

deterministic idempotency key per (run, step, item): a re-run node replays instead of

repeating. A ``for_each`` step submits every item first and pauses once for all items that

need a human, instead of one pause per item.

"""

from __future__ import annotations

import asyncio
import operator
import uuid
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Annotated, Any, TypedDict, cast

from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert

from core.agent.state import RunState, subgraph_builder
from core.agent.tools import EDITED, ToolCaller, action_record, step_key
from core.db.session import Database
from core.gateway.gateway import Gateway, GatewayOutcome, ToolCall
from core.gateway.taint import Tainted
from core.tools.preview import preview_hash
from core.tools.spec import RegisteredTool, RiskTier, ToolContext, ToolResult, ToolSpec
from core.workflows import refs
from core.workflows.catalog import tenant_registry
from core.workflows.dsl import Step, WorkflowDefinition, parse_definition
from core.workflows.models import Workflow, WorkflowVersion, WorkflowWait

if TYPE_CHECKING:
    from core.agent.runtime import AgentRuntime

WORKFLOW_INTENT = "workflow.run"
SIGNOFF_TOOL = "workflows.signoff"
OK_STATUSES = ("executed", "replayed")


# ------------------------------------------------------------------ sign-off tool


class SignoffIn(BaseModel):
    workflow: str = Field(max_length=120)
    version: int = Field(ge=1)
    step: str = Field(max_length=40)
    summary: str = Field(max_length=1000)


async def _signoff(args: BaseModel, ctx: ToolContext) -> ToolResult:
    a = SignoffIn.model_validate(args)
    effect = {"workflow": a.workflow, "version": a.version, "step": a.step, "signed_off": True}
    return ToolResult(ok=True, dry_run=ctx.dry_run, data=effect, preview_hash=preview_hash(effect))


def signoff_tool() -> RegisteredTool:
    """T3 no-op: the gateway sends it to the inbox, so a human signs off on a workflow step

    through the same bound, expiring, single-use approvals as every other action."""
    return RegisteredTool(
        ToolSpec(
            name=SIGNOFF_TOOL,
            description="A human signs off before a workflow step continues.",
            input_model=SignoffIn,
            risk_tier=RiskTier.T3_CRITICAL,
            pack=None,
            tags=("workflow", "approval"),
        ),
        _signoff,
    )


# ------------------------------------------------------------------ inner state


def _merge(a: dict[str, Any] | None, b: dict[str, Any] | None) -> dict[str, Any]:
    return {**(a or {}), **(b or {})}


class WorkflowState(TypedDict, total=False):
    tenant_id: str
    run_id: str
    thread_id: str
    workflow: dict[str, Any]  # {"id", "key", "version", "name"}
    event: dict[str, Any] | None
    trigger: dict[str, Any]
    start_after: str | None  # continuation after a wait: skip steps up to this one
    outputs: Annotated[dict[str, Any], _merge]
    log: Annotated[list[str], operator.add]
    actions: Annotated[list[dict[str, Any]], operator.add]
    calls: Annotated[int, operator.add]
    messages: Annotated[int, operator.add]
    status: str  # running | failed | waiting
    error: str | None
    failure: dict[str, Any] | None


class StepFailed(Exception):
    def __init__(self, reason: str, status: str = "failed", tool: str | None = None) -> None:
        super().__init__(reason)
        self.reason = reason
        self.status = status
        self.tool = tool


RATE_LIMIT_MARKERS = ("quota", "rate limit", "rate-limit", "429", "too many requests")


def is_rate_limited(reason: str | None) -> bool:
    r = (reason or "").lower()
    return any(m in r for m in RATE_LIMIT_MARKERS)


# Failures worth another attempt: the upstream or the database was briefly unreachable.
# (A failed call rolls back its savepoint, idempotency claim and approval use in the
# gateway, so re-running it with the same key is safe on our side.)
TRANSIENT_MARKERS = (
    "timeout",
    "timed out",
    "temporarily",
    "service unavailable",
    "bad gateway",
    "gateway timeout",
    " 502",
    " 503",
    " 504",
    "operationalerror",
    "connection reset",
    "connection refused",
    "connection is bad",
    "server closed the connection",
)


def is_transient(reason: str | None) -> bool:
    r = (reason or "").lower()
    return any(m in r for m in TRANSIENT_MARKERS)


def split_args(args: dict[str, Any], scope: refs.Scope) -> tuple[dict[str, Any], bool]:
    """Render each top-level argument; tainted ones are wrapped for the gateway."""
    out: dict[str, Any] = {}
    any_taint = False
    for k, v in args.items():
        value, tainted = refs.render(v, scope)
        out[k] = Tainted(value, "event") if tainted else value
        any_taint = any_taint or tainted
    return out, any_taint


def is_message_tool(spec: ToolSpec) -> bool:
    return "message" in spec.tags or "whatsapp" in spec.tags or "email" in spec.tags


# ------------------------------------------------------------------ compiled steps


@dataclass
class Executor:
    """Builds and runs the per-definition graph. One per runtime."""

    db: Database
    gateway: Gateway
    tools: ToolCaller

    # ---- graph

    def compile(self, defn: WorkflowDefinition) -> Any:
        g: StateGraph = StateGraph(WorkflowState)
        prev = START
        for index, step in enumerate(defn.steps):
            name = f"step__{step.id}"
            g.add_node(name, cast(Any, self._node(defn, step, index)))
            g.add_edge(prev, name)
            prev = name
        g.add_edge(prev, END)
        return g.compile()

    def _node(

        self, defn: WorkflowDefinition, step: Step, index: int

    ) -> Callable[[WorkflowState], Awaitable[dict[str, Any]]]:
        order = [s.id for s in defn.steps]

        async def node(state: WorkflowState) -> dict[str, Any]:
            if state.get("status") in ("failed", "waiting"):
                return {}
            after = state.get("start_after")
            if after and after in order and index <= order.index(after):
                return {}
            try:
                return await self._run_step(defn, step, state)
            except StepFailed as exc:
                return self._failed(step, exc)
            except refs.RefError as exc:
                return self._failed(step, StepFailed(f"reference error: {exc}", "schema"))

        return node

    @staticmethod
    def _failed(step: Step, exc: StepFailed) -> dict[str, Any]:
        failure = {
            "step": step.id,
            "tool": exc.tool or step.tool,
            "status": exc.status,
            "reason": exc.reason,
        }
        return {
            "status": "failed",
            "error": f"step {step.id}: {exc.reason}",
            "failure": failure,
            "log": [f"{step.id}: failed: {exc.reason}"],
        }

    @staticmethod
    def scope(state: WorkflowState) -> refs.Scope:
        return refs.Scope(
            steps=dict(state.get("outputs") or {}),
            event=state.get("event"),
            trigger=dict(state.get("trigger") or {}),
            workflow=dict(state.get("workflow") or {}),
        )

    async def _run_step(

        self, defn: WorkflowDefinition, step: Step, state: WorkflowState

    ) -> dict[str, Any]:
        scope = self.scope(state)
        if step.kind == "wait":
            return await self._wait(step, state)
        if step.kind == "approval":
            assert step.approval is not None
            if not refs.all_hold(step.when, scope):
                return {"log": [f"{step.id}: skipped (condition)"]}
            summary, _ = refs.render(step.approval.summary, scope)
            out = await self._signoff_gate(defn, step, state, str(summary))
            return {
                "outputs": {step.id: out},
                "log": [f"{step.id}: signed off"],
                "actions": [out.pop("_action")],
            }
        tool = await self._spec(state, str(step.tool))
        if step.for_each is not None:
            return await self._for_each(defn, step, tool, state, scope)
        if not refs.all_hold(step.when, scope):
            return {"log": [f"{step.id}: skipped (condition)"]}
        self._check_limits(defn, tool, state, extra=1)
        actions: list[dict[str, Any]] = []
        if self._needs_signoff(defn, step, tool):
            gate = await self._signoff_gate(defn, step, state, f"run {step.tool}")
            actions.append(gate.pop("_action"))
        args, _ = split_args(step.args, scope)
        run_state = cast(RunState, state)
        outcome = await self._with_retry(
            step, lambda: self.tools.call(run_state, f"wf:{step.id}", str(step.tool), args)
        )
        actions.append(action_record(step.id, str(step.tool), outcome))
        upd: dict[str, Any] = {
            "actions": actions,
            "calls": 1,
            "messages": 1 if is_message_tool(tool) else 0,
        }
        if outcome.status in OK_STATUSES:
            data = outcome.result.data if outcome.result else None
            upd["outputs"] = {step.id: data or {}}
            upd["log"] = [f"{step.id}: {step.tool} {outcome.status}"]
            return upd
        reason = outcome.reason or (outcome.result.error if outcome.result else None) or ""
        if step.on_error == "continue":
            upd["outputs"] = {step.id: {"error": reason, "status": outcome.status}}
            upd["log"] = [f"{step.id}: {step.tool} {outcome.status} ({reason}); continuing"]
            return upd
        failed = self._failed(step, StepFailed(reason, outcome.status, step.tool))
        return {**failed, "actions": actions, "calls": 1}

    # ---- limits and approval gates

    @staticmethod
    def _check_limits(

        defn: WorkflowDefinition, tool: ToolSpec, state: WorkflowState, *, extra: int

    ) -> None:
        po = defn.policy_overrides
        if int(tool.risk_tier) > po.max_tier:
            raise StepFailed(f"{tool.name} is above max_tier T{po.max_tier}", "denied")
        if (state.get("calls") or 0) + extra > po.max_tool_calls:
            raise StepFailed(f"max_tool_calls {po.max_tool_calls} reached", "denied")
        if is_message_tool(tool) and (state.get("messages") or 0) + extra > po.max_messages:
            raise StepFailed(f"max_messages {po.max_messages} reached", "denied")

    @staticmethod
    def _needs_signoff(defn: WorkflowDefinition, step: Step, tool: ToolSpec) -> bool:
        if tool.risk_tier >= RiskTier.T3_CRITICAL:
            return False  # the gateway already asks a human for every T3 call
        return step.requires_approval or tool.name in defn.policy_overrides.require_approval_for

    async def _signoff_gate(

        self, defn: WorkflowDefinition, step: Step, state: WorkflowState, summary: str

    ) -> dict[str, Any]:
        wf = state.get("workflow") or {}
        args = {
            "workflow": str(wf.get("name") or defn.name)[:120],
            "version": int(wf.get("version") or 1),
            "step": step.id,
            "summary": summary[:1000],
        }
        outcome = await self.tools.call(
            cast(RunState, state), f"wf:{step.id}:signoff", SIGNOFF_TOOL, args
        )
        if outcome.status not in OK_STATUSES:
            raise StepFailed(
                f"sign-off {outcome.status}: {outcome.reason or ''}".strip(),
                outcome.status,
                SIGNOFF_TOOL,
            )
        return {
            "signed_off": True,
            "_action": action_record(f"{step.id}:signoff", SIGNOFF_TOOL, outcome),
        }

    async def _with_retry(

        self, step: Step, call: Callable[[], Awaitable[GatewayOutcome]]

    ) -> GatewayOutcome:
        attempts = step.retry.max_attempts
        for attempt in range(attempts):
            outcome = await call()
            reason = outcome.reason or (outcome.result.error if outcome.result else None)
            limited = outcome.status in ("denied", "failed") and is_rate_limited(reason)
            transient = outcome.status == "failed" and is_transient(reason)
            if (limited or transient) and attempt + 1 < attempts:
                await asyncio.sleep(min(step.retry.backoff_s * (2**attempt), 60.0))
                continue
            return outcome
        raise AssertionError("unreachable")

    # ---- for_each

    async def _execute_once(

        self, state: WorkflowState, key: str, tool: str, args: dict[str, Any]

    ) -> GatewayOutcome:
        """Like ``ToolCaller.call`` but never pauses: the caller collects every item that

        needs a human and pauses once."""
        from core.gateway.taint import split_taint

        plain, taint = split_taint(args)
        run_id = state["run_id"]
        call = ToolCall(
            tenant_id=uuid.UUID(state["tenant_id"]),
            actor=f"agent:{run_id}",
            tool=tool,
            args=plain,
            taint=taint,
            idempotency_key=step_key(run_id, key),
            run_id=uuid.UUID(run_id),
            thread_id=state.get("thread_id"),
        )
        outcome = await self.gateway.execute(call)
        if outcome.status == "rejected" and outcome.reason == EDITED and outcome.approval_id:
            edited = await self.tools._replacement_args(call.tenant_id, outcome.approval_id)
            if edited is not None:
                outcome = await self.gateway.execute(
                    call.model_copy(
                        update={
                            "args": edited,
                            "taint": {},
                            "idempotency_key": step_key(run_id, f"{key}:edited"),
                        }
                    )
                )
        return outcome

    async def _spec(self, state: WorkflowState, name: str) -> ToolSpec:
        """Registry tools and the tenant's runtime tools (Phase 16)."""
        from core.tools.registry import ToolNotFound
        from core.tools.tenant_tools import ToolUnavailable

        try:
            tool = await self.gateway.resolve_tool(uuid.UUID(state["tenant_id"]), name)
        except (ToolNotFound, ToolUnavailable) as exc:
            raise StepFailed(f"unknown tool {name}: {exc}", "schema", name) from exc
        return tool.spec

    def _bind(

        self, state: WorkflowState, key: str, tool: str, args: dict[str, Any]

    ) -> Callable[[], Awaitable[GatewayOutcome]]:
        return lambda: self._execute_once(state, key, tool, args)

    async def _for_each(

        self,

        defn: WorkflowDefinition,

        step: Step,

        tool: ToolSpec,

        state: WorkflowState,

        scope: refs.Scope,

    ) -> dict[str, Any]:
        assert step.for_each is not None
        items, tainted = refs.resolve(step.for_each, scope)
        if items is None:
            items = []
        if not isinstance(items, list):
            raise StepFailed(f"for_each {step.for_each} is not a list", "schema")
        cap = min(step.max_items or 10**9, defn.policy_overrides.max_items_per_step)
        if len(items) > cap:
            raise StepFailed(f"{len(items)} items exceed max_items {cap}", "denied")
        chosen = [
            (i, it)
            for i, it in enumerate(items)
            if refs.all_hold(step.when, scope.with_item(it, i, tainted))
        ]
        self._check_limits(defn, tool, state, extra=len(chosen))
        actions: list[dict[str, Any]] = []
        if chosen and self._needs_signoff(defn, step, tool):
            gate = await self._signoff_gate(
                defn, step, state, f"run {step.tool} for {len(chosen)} item(s)"
            )
            actions.append(gate.pop("_action"))
        wanted = {i for i, _ in chosen}
        while True:
            results, item_actions, pending, stop = await self._pass(
                step, state, scope, items, wanted, tainted
            )
            if not pending or stop is not None:
                break
            first = pending[0]
            interrupt(
                {
                    "type": "approval",
                    "approval_id": first["approval_id"],
                    "tool": step.tool,
                    "reason": first["reason"],
                    "step": step.id,
                    "pending": pending,
                }
            )
        done = sum(1 for r in results if r["status"] in OK_STATUSES)
        out = {"results": results, "count": len(items), "done": done}
        upd: dict[str, Any] = {
            "outputs": {step.id: out},
            "actions": actions + item_actions,
            "calls": sum(1 for r in results if r["status"] != "skipped"),
            "messages": done if is_message_tool(tool) else 0,
            "log": [
                f"{step.id}: {step.tool} x{len(chosen)}: {done} done, {len(chosen) - done} not done"
            ],
        }
        if stop is not None:
            upd.update(self._failed(step, stop))
            upd["log"] = upd["log"]
        return upd

    async def _pass(

        self,

        step: Step,

        state: WorkflowState,

        scope: refs.Scope,

        items: list[Any],

        wanted: set[int],

        tainted: bool,

    ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], StepFailed | None]:
        results: list[dict[str, Any]] = []
        actions: list[dict[str, Any]] = []
        pending: list[dict[str, Any]] = []
        for i, item in enumerate(items):
            if i not in wanted:
                results.append({"item": item, "status": "skipped"})
                continue
            args, _ = split_args(step.args, scope.with_item(item, i, tainted))
            key = f"wf:{step.id}:{i}"
            outcome = await self._with_retry(step, self._bind(state, key, str(step.tool), args))
            actions.append(action_record(f"{step.id}[{i}]", str(step.tool), outcome))
            data = outcome.result.data if outcome.result else None
            reason = outcome.reason or (outcome.result.error if outcome.result else None)
            results.append(
                {
                    "item": item,
                    "status": outcome.status,
                    "data": data if outcome.status in OK_STATUSES else None,
                    "reason": reason,
                }
            )
            if outcome.status == "needs_approval":
                pending.append(
                    {"index": i, "approval_id": str(outcome.approval_id), "reason": reason}
                )
            elif outcome.status in ("denied", "failed") and step.on_error == "stop":
                return (
                    results,
                    actions,
                    pending,
                    StepFailed(f"item {i}: {reason}", outcome.status, step.tool),
                )
        return results, actions, pending, None

    # ---- wait

    async def _wait(self, step: Step, state: WorkflowState) -> dict[str, Any]:
        assert step.wait is not None
        wf = state.get("workflow") or {}
        resume_at = datetime.now(UTC) + timedelta(seconds=step.wait.seconds)
        tid = uuid.UUID(state["tenant_id"])
        async with self.db.session(tenant_id=tid) as s, s.begin():
            await s.execute(
                insert(WorkflowWait)
                .values(
                    id=uuid.uuid4(),
                    tenant_id=tid,
                    workflow_id=uuid.UUID(str(wf["id"])),
                    version=int(wf["version"]),
                    run_id=uuid.UUID(state["run_id"]),
                    step_id=step.id,
                    resume_at=resume_at,
                    outputs=dict(state.get("outputs") or {}),
                    event=state.get("event"),
                    status="waiting",
                )
                .on_conflict_do_nothing(constraint="uq_workflow_waits_run_step")
            )
        return {
            "status": "waiting",
            "log": [f"{step.id}: waiting {step.wait.seconds}s (continues in a new run)"],
        }


# ------------------------------------------------------------------ outer subgraph


def _trigger_context(payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any]]:
    kind = str(payload.get("trigger") or "manual")
    trigger = {"type": kind, "fire_time": payload.get("fire_time")}
    if kind == "event":
        ev = payload.get("event") or {}
        return {"type": ev.get("type"), "payload": ev.get("payload") or {}}, trigger
    if kind == "manual":
        return {"type": "manual", "payload": payload.get("input") or {}}, trigger
    return None, trigger


async def load_active(

    db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID, version: int

) -> tuple[Workflow, WorkflowVersion]:
    async with db.session(tenant_id=tenant_id) as s:
        wf = await s.get(Workflow, workflow_id)
        v = (
            await s.execute(
                select(WorkflowVersion).where(
                    WorkflowVersion.workflow_id == workflow_id, WorkflowVersion.version == version
                )
            )
        ).scalar_one_or_none()
    if wf is None or v is None:
        raise LookupError(f"workflow {workflow_id} version {version} not found")
    if wf.status != "active" or wf.active_version != version or v.status != "active":
        raise LookupError(f"workflow {wf.key} version {version} is not the active version")
    return wf, v


def build_workflow_subgraph(executor: Executor, db: Database) -> Any:
    async def admit(state: RunState) -> dict[str, Any]:
        event = state.get("event") or {}
        payload = dict(event.get("payload") or {})
        tid = uuid.UUID(state["tenant_id"])
        try:
            wf_id = uuid.UUID(str(payload["workflow_id"]))
            version = int(payload["version"])
            wf, v = await load_active(db, tid, wf_id, version)
        except (KeyError, ValueError, LookupError) as exc:
            return {
                "status": "failed",
                "error": f"workflow not admitted: {exc}",
                "log": [f"workflow not admitted: {exc}"],
            }
        wf_event, trigger = _trigger_context(payload)
        ctx: dict[str, Any] = {
            "workflow": {"id": str(wf.id), "key": wf.key, "version": v.version, "name": wf.name},
            "definition": v.definition,
            "event": wf_event,
            "trigger": trigger,
            "outputs": {},
            "start_after": None,
        }
        resume = payload.get("resume")
        if resume:
            async with db.session(tenant_id=tid) as s:
                w = await s.get(WorkflowWait, uuid.UUID(str(resume)))
            if w is None or w.workflow_id != wf.id or w.status != "fired":
                return {
                    "status": "failed",
                    "error": "unknown or unfired wait",
                    "log": ["workflow continuation refused"],
                }
            ctx.update(outputs=w.outputs, event=w.event, start_after=w.step_id)
        return {
            "facts": {**(state.get("facts") or {}), "workflow": ctx},
            "log": [f"workflow {wf.key} v{v.version} ({trigger['type']})"],
        }

    async def execute(state: RunState) -> dict[str, Any]:
        if state.get("status") == "failed":
            return {}
        ctx = (state.get("facts") or {})["workflow"]
        defn = parse_definition(ctx["definition"])
        inner = executor.compile(defn)
        result = await inner.ainvoke(
            {
                "tenant_id": state["tenant_id"],
                "run_id": state["run_id"],
                "thread_id": state.get("thread_id", ""),
                "workflow": ctx["workflow"],
                "event": ctx["event"],
                "trigger": ctx["trigger"],
                "start_after": ctx["start_after"],
                "outputs": ctx["outputs"],
                "log": [],
                "actions": [],
                "calls": 0,
                "messages": 0,
                "status": "running",
            }
        )
        status = result.get("status", "running")
        summary = {
            "status": status,
            "failure": result.get("failure"),
            "steps": sorted((result.get("outputs") or {}).keys()),
        }
        upd: dict[str, Any] = {
            "log": list(result.get("log") or []),
            "actions": list(result.get("actions") or []),
            "facts": {**(state.get("facts") or {}), "workflow_result": summary},
        }
        if status in ("failed", "waiting"):
            upd["status"] = status
            upd["error"] = result.get("error")
        return upd

    async def report(state: RunState) -> dict[str, Any]:
        facts = state.get("facts") or {}
        ctx, res = facts.get("workflow"), facts.get("workflow_result")
        if not ctx or not res:
            return {}
        wf = ctx["workflow"]
        head = f"Workflow {wf['name']} v{wf['version']}"
        if res["status"] == "failed" and res.get("failure"):
            from core.workflows.healing import handle_failure

            note = await handle_failure(
                db,
                uuid.UUID(state["tenant_id"]),
                uuid.UUID(state["run_id"]),
                ctx,
                res["failure"],
                registry=await tenant_registry(executor.gateway, uuid.UUID(state["tenant_id"])),
            )
            return {"output": f"{head} failed: {state.get('error')}. {note}".strip()}
        if res["status"] == "waiting":
            return {"output": f"{head} is waiting; it continues in a new run."}
        return {"output": f"{head} completed: {len(state.get('actions') or [])} gateway calls."}

    g = subgraph_builder()
    g.add_node("admit", admit)
    g.add_node("execute", execute)
    g.add_node("report", report)
    g.add_edge(START, "admit")
    g.add_edge("admit", "execute")
    g.add_edge("execute", "report")
    g.add_edge("report", END)
    return g.compile()


def install(runtime: AgentRuntime) -> None:
    """Add the ``workflow.run`` intent + subgraph to a runtime (called from its constructor).

    Registers the sign-off tool on the runtime's gateway registry if it is missing."""
    from core.packs.loader import IntentInfo

    gateway = runtime.deps.tools.gateway
    if not gateway.registry.has(SIGNOFF_TOOL):
        t = signoff_tool()
        gateway.registry.register(t.spec, t.handler)
    executor = Executor(db=runtime.db, gateway=gateway, tools=runtime.deps.tools)
    runtime.intents.append(
        IntentInfo(WORKFLOW_INTENT, "Run an owner-approved workflow version.", chat_enabled=False)
    )
    runtime.subgraphs[WORKFLOW_INTENT] = build_workflow_subgraph(executor, runtime.db)