File size: 29,260 Bytes
04bb755
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Workflow execution engine β€” runs multi-step agent pipelines."""

import logging
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from src.core.exceptions import (
    InsufficientCreditsError,
    MarketplaceError,
    RunTerminalError,
)
from src.models.task import Task
from src.models.workflow import Workflow, WorkflowRun, WorkflowStep, WorkflowStepRun
from src.schemas.task import TaskCreate as TaskCreateSchema, TaskMessage, MessagePart

logger = logging.getLogger(__name__)

# Fallback timeouts when workflow has no user-configured values
DEFAULT_WORKFLOW_TIMEOUT = 1800  # 30 minutes
DEFAULT_STEP_TIMEOUT = 120  # 2 minutes


class WorkflowExecutionService:
    def __init__(self, db: AsyncSession):
        self.db = db

    # ------------------------------------------------------------------
    # Execute β€” kick off a workflow run
    # ------------------------------------------------------------------

    async def execute_workflow(
        self,
        workflow_id: UUID,
        user_id: UUID,
        input_message: str,
        schedule_id: UUID | None = None,
        parent_run_id: UUID | None = None,
        depth: int = 0,
        channel_connection_id: UUID | None = None,
        channel_chat_id: str | None = None,
    ) -> WorkflowRun:
        if depth >= 10:  # safety cap
            raise ValueError("Maximum nesting depth (10) exceeded")

        from src.services.workflow_service import WorkflowService

        wf_svc = WorkflowService(self.db)
        wf = await wf_svc.get_workflow(workflow_id)

        if not wf.steps:
            raise MarketplaceError(status_code=400, detail="Workflow has no steps")

        # Build snapshot of workflow definition (includes timeout config)
        snapshot = {
            "name": wf.name,
            "timeout_seconds": wf.timeout_seconds or DEFAULT_WORKFLOW_TIMEOUT,
            "step_timeout_seconds": wf.step_timeout_seconds or DEFAULT_STEP_TIMEOUT,
            "failure_mode": wf.failure_mode or "stop",
            "steps": [
                {
                    "id": str(s.id),
                    "agent_id": str(s.agent_id) if s.agent_id else None,
                    "skill_id": str(s.skill_id) if s.skill_id else None,
                    "sub_workflow_id": str(s.sub_workflow_id) if s.sub_workflow_id else None,
                    "step_group": s.step_group,
                    "position": s.position,
                    "input_mode": s.input_mode,
                    "input_template": s.input_template,
                    "label": s.label,
                    "instructions": s.instructions,
                    "agent_name": s.agent.name if s.agent else None,
                    "skill_name": s.skill.name if s.skill else None,
                }
                for s in wf.steps
            ],
        }

        # Upfront cost estimate
        total_estimate = self._estimate_cost(wf)
        if wf.max_total_credits and total_estimate > wf.max_total_credits:
            raise MarketplaceError(
                status_code=400,
                detail=f"Estimated cost ({total_estimate} credits) exceeds workflow limit "
                       f"({wf.max_total_credits} credits)",
            )

        # Check user balance
        from src.services.credit_ledger import CreditLedgerService
        ledger = CreditLedgerService(self.db)
        balance_info = await ledger.get_balance(user_id)
        available = balance_info["available"]
        if total_estimate > 0 and available < total_estimate:
            raise InsufficientCreditsError(
                required=float(total_estimate),
                available=float(available),
            )

        # Create workflow run
        run = WorkflowRun(
            workflow_id=workflow_id,
            user_id=user_id,
            schedule_id=schedule_id,
            parent_run_id=parent_run_id,
            depth=depth,
            status="running",
            current_step_group=0,
            input_message=input_message,
            workflow_snapshot=snapshot,
            channel_connection_id=channel_connection_id,
            channel_chat_id=channel_chat_id,
        )
        self.db.add(run)
        await self.db.flush()

        # Create step runs for ALL steps (pending)
        step_groups = {}
        for s in wf.steps:
            step_groups.setdefault(s.step_group, []).append(s)

        for group_num, steps in step_groups.items():
            for step in steps:
                sr = WorkflowStepRun(
                    run_id=run.id,
                    step_id=step.id,
                    step_group=group_num,
                    status="pending",
                )
                self.db.add(sr)

        await self.db.commit()
        await self.db.refresh(run)

        # Dispatch step_group 0
        await self._dispatch_step_group(run, wf, group_num=0, input_text=input_message)

        return run

    # ------------------------------------------------------------------
    # Pump β€” advance all running workflows
    # ------------------------------------------------------------------

    async def pump_running_workflows(self) -> None:
        now = datetime.now(timezone.utc)

        result = await self.db.execute(
            select(WorkflowRun)
            .where(WorkflowRun.status == "running")
            .with_for_update(skip_locked=True)
            .options(selectinload(WorkflowRun.step_runs))
            .order_by(WorkflowRun.depth.desc())
            .limit(20)
        )
        runs = list(result.scalars().unique().all())

        for run in runs:
            try:
                await self._pump_single_run(run, now)
            except Exception:
                logger.exception("Error pumping workflow run %s", run.id)
                run.status = "failed"
                run.error = "Internal error during execution"
                run.completed_at = now
                self._tally_credits(run)
                await self._settle_ucp_run(run)

        await self.db.commit()

    async def _pump_single_run(self, run: WorkflowRun, now: datetime) -> None:
        # Read timeout from snapshot (user-configured), fallback to defaults
        snapshot = run.workflow_snapshot or {}
        wf_timeout = snapshot.get("timeout_seconds", DEFAULT_WORKFLOW_TIMEOUT)
        step_timeout = snapshot.get("step_timeout_seconds", DEFAULT_STEP_TIMEOUT)

        # Check workflow-level timeout
        created = run.created_at.replace(
            tzinfo=timezone.utc if run.created_at.tzinfo is None else run.created_at.tzinfo
        )
        elapsed = (now - created).total_seconds()
        if elapsed > wf_timeout:
            run.status = "failed"
            run.error = (
                f"Workflow timed out after {int(elapsed)}s "
                f"(limit: {wf_timeout}s). "
                f"You can increase the timeout in workflow settings."
            )
            run.completed_at = now
            # Mark any running steps as timed out too
            for sr in run.step_runs:
                if sr.status == "running":
                    sr.status = "failed"
                    sr.error = "Workflow-level timeout reached"
                    sr.completed_at = now
            self._tally_credits(run)
            await self._settle_ucp_run(run)
            return

        current_group = run.current_step_group
        group_step_runs = [sr for sr in run.step_runs if sr.step_group == current_group]

        if not group_step_runs:
            run.status = "failed"
            run.error = "No step runs found for current group"
            run.completed_at = now
            self._tally_credits(run)
            await self._settle_ucp_run(run)
            return

        # Check per-step timeouts for running steps
        self._check_step_timeouts(group_step_runs, step_timeout, now, snapshot)

        # Check if all step runs in current group are terminal
        all_terminal = all(sr.status in ("completed", "failed") for sr in group_step_runs)
        if not all_terminal:
            # Check tasks for status updates
            await self._sync_step_run_statuses(group_step_runs, snapshot)
            # Re-check step timeouts after syncing
            self._check_step_timeouts(group_step_runs, step_timeout, now, snapshot)
            all_terminal = all(sr.status in ("completed", "failed") for sr in group_step_runs)
            if not all_terminal:
                return

        # Check for failures β€” collect error details
        failed_steps = [sr for sr in group_step_runs if sr.status == "failed"]
        if failed_steps:
            failure_mode = snapshot.get("failure_mode", "stop")
            error_details = []
            for sr in failed_steps:
                step_info = self._step_info_from_snapshot(snapshot, sr.step_id)
                label = step_info.get("agent_name", "Unknown") if step_info else "Unknown"
                if sr.error:
                    error_details.append(f"{label}: {sr.error}")
                else:
                    error_details.append(f"{label}: failed (no details)")

            if failure_mode == "continue":
                # Log warning but allow the run to advance to the next group
                logger.warning(
                    "Workflow run %s step group %d had failures (failure_mode=continue, advancing): %s",
                    run.id, current_group, "; ".join(error_details),
                )
            else:
                # "stop" (default) β€” fail the entire run
                run.status = "failed"
                run.error = f"Step {current_group + 1} failed β€” " + "; ".join(error_details)
                run.completed_at = now
                self._tally_credits(run)
                await self._settle_ucp_run(run)
                return

        # All completed β€” advance to next group
        all_groups = sorted(set(sr.step_group for sr in run.step_runs))
        current_idx = all_groups.index(current_group)

        if current_idx + 1 >= len(all_groups):
            # All groups done
            run.status = "completed"
            run.completed_at = now
            self._tally_credits(run)
            await self._settle_ucp_run(run)
            return

        # Advance to next group
        next_group = all_groups[current_idx + 1]
        run.current_step_group = next_group

        # Collect output from completed group
        prev_output = self._collect_group_output(group_step_runs)

        # We need the workflow to resolve step details
        wf_result = await self.db.execute(
            select(Workflow)
            .where(Workflow.id == run.workflow_id)
            .options(
                selectinload(Workflow.steps).selectinload(WorkflowStep.agent),
                selectinload(Workflow.steps).selectinload(WorkflowStep.skill),
            )
        )
        wf = wf_result.scalar_one_or_none()

        if wf:
            await self._dispatch_step_group(
                run, wf, group_num=next_group,
                input_text=run.input_message, prev_output=prev_output,
            )

    def _check_step_timeouts(
        self,
        step_runs: list[WorkflowStepRun],
        step_timeout: int,
        now: datetime,
        snapshot: dict,
    ) -> None:
        for sr in step_runs:
            if sr.status != "running" or not sr.started_at:
                continue
            started = sr.started_at.replace(
                tzinfo=timezone.utc if sr.started_at.tzinfo is None else sr.started_at.tzinfo
            )
            elapsed = (now - started).total_seconds()
            if elapsed > step_timeout:
                step_info = self._step_info_from_snapshot(snapshot, sr.step_id)
                agent_name = step_info.get("agent_name", "Unknown") if step_info else "Unknown"
                skill_name = step_info.get("skill_name", "Unknown") if step_info else "Unknown"
                sr.status = "failed"
                sr.error = (
                    f"Step timed out after {int(elapsed)}s (limit: {step_timeout}s). "
                    f"Agent '{agent_name}' with skill '{skill_name}' did not respond in time. "
                    f"The agent may be offline or overloaded."
                )
                sr.completed_at = now
                logger.warning(
                    "Step run %s timed out after %ds (agent: %s, skill: %s)",
                    sr.id, int(elapsed), agent_name, skill_name,
                )

    def _step_info_from_snapshot(self, snapshot: dict, step_id: UUID | None) -> dict | None:
        if not step_id or not snapshot.get("steps"):
            return None
        step_id_str = str(step_id)
        for s in snapshot["steps"]:
            if s.get("id") == step_id_str:
                return s
        return None

    async def _sync_step_run_statuses(
        self, step_runs: list[WorkflowStepRun], snapshot: dict
    ) -> None:
        for sr in step_runs:
            if sr.status in ("completed", "failed"):
                continue

            if sr.child_run_id:
                # Use select+options, NOT db.get() β€” avoids MissingGreenlet
                result = await self.db.execute(
                    select(WorkflowRun)
                    .options(selectinload(WorkflowRun.step_runs))
                    .where(WorkflowRun.id == sr.child_run_id)
                )
                child_run = result.scalar_one_or_none()
                if child_run and child_run.status == "completed":
                    sr.status = "completed"
                    sr.output_text = self._collect_child_output(child_run)
                    sr.credits_charged = child_run.total_credits_charged
                    sr.completed_at = datetime.now(timezone.utc)
                elif child_run and child_run.status in ("failed", "canceled"):
                    sr.status = "failed"
                    sr.error = f"Sub-workflow {child_run.status}: {child_run.error or 'unknown'}"
                    sr.completed_at = datetime.now(timezone.utc)
            elif sr.task_id:
                result = await self.db.execute(
                    select(Task).where(Task.id == sr.task_id)
                )
                task = result.scalar_one_or_none()
                if not task:
                    continue

                task_status = task.status.value if hasattr(task.status, "value") else str(task.status)

                if task_status == "completed":
                    sr.status = "completed"
                    sr.completed_at = datetime.now(timezone.utc)
                    sr.output_text = self._extract_task_output(task)
                    sr.credits_charged = task.credits_charged
                elif task_status in ("failed", "canceled"):
                    sr.status = "failed"
                    sr.completed_at = datetime.now(timezone.utc)
                    step_info = self._step_info_from_snapshot(snapshot, sr.step_id)
                    agent_name = step_info.get("agent_name", "Unknown") if step_info else "Unknown"
                    sr.error = (
                        f"Task {task_status} β€” agent '{agent_name}' "
                        f"could not complete the request."
                    )

    # ------------------------------------------------------------------
    # Dispatch helpers
    # ------------------------------------------------------------------

    async def _dispatch_step_group(
        self,
        run: WorkflowRun,
        wf: Workflow,
        group_num: int,
        input_text: str,
        prev_output: str | None = None,
    ) -> None:
        from src.services.task_broker import TaskBrokerService

        broker = TaskBrokerService(self.db)
        group_steps = [s for s in wf.steps if s.step_group == group_num]
        group_step_runs = [sr for sr in run.step_runs if sr.step_group == group_num]

        # Map step_id -> step_run for quick lookup
        sr_by_step = {sr.step_id: sr for sr in group_step_runs}

        # Collect all previous step outputs for custom templates
        all_outputs = {}
        for sr in run.step_runs:
            if sr.status == "completed" and sr.output_text:
                all_outputs[sr.step_group] = sr.output_text

        for step in group_steps:
            resolved_input = self._resolve_input(
                step, input_text, prev_output, all_outputs
            )
            final_input = self._apply_instructions(resolved_input, step.instructions)

            step_run = sr_by_step.get(step.id)

            # Check for invalid step (deleted sub-workflow leaves both null)
            if step.agent_id is None and step.skill_id is None and step.sub_workflow_id is None:
                if step_run:
                    step_run.status = "failed"
                    step_run.error = f"Step '{step.label or step.id}' has no agent or sub-workflow (may have been deleted)"
                continue

            if step.sub_workflow_id:
                # Hierarchical: dispatch sub-workflow
                try:
                    child_run = await self.execute_workflow(
                        workflow_id=step.sub_workflow_id,
                        input_message=resolved_input,
                        user_id=run.user_id,
                        parent_run_id=run.id,
                        depth=run.depth + 1,
                    )
                    if step_run:
                        step_run.child_run_id = child_run.id
                        step_run.status = "running"
                        step_run.started_at = datetime.now(timezone.utc)
                except Exception as exc:
                    logger.exception(
                        "Failed to dispatch sub-workflow %s in workflow run %s",
                        step.sub_workflow_id, run.id,
                    )
                    if step_run:
                        step_run.status = "failed"
                        step_run.error = f"Failed to start sub-workflow: {exc}"
                        step_run.completed_at = datetime.now(timezone.utc)
                continue

            message = TaskMessage(
                role="user",
                parts=[MessagePart(type="text", content=final_input)],
            )
            task_data = TaskCreateSchema(
                provider_agent_id=step.agent_id,
                skill_id=str(step.skill_id),
                messages=[message],
                confirmed=True,
            )

            try:
                task = await broker.create_task(
                    data=task_data, user_id=run.user_id
                )
                sr = sr_by_step.get(step.id)
                if sr:
                    sr.task_id = task.id
                    sr.status = "running"
                    sr.started_at = datetime.now(timezone.utc)
            except Exception as exc:
                logger.exception(
                    "Failed to dispatch step %s in workflow run %s", step.id, run.id
                )
                sr = sr_by_step.get(step.id)
                if sr:
                    sr.status = "failed"
                    sr.error = (
                        f"Failed to dispatch task to agent "
                        f"'{step.agent.name if step.agent else 'Unknown'}': {exc}"
                    )
                    sr.completed_at = datetime.now(timezone.utc)

        await self.db.commit()

    def _apply_instructions(self, base_text: str, instructions: str | None) -> str:
        """Prepend per-step instructions to the resolved input text."""
        if not instructions or not instructions.strip():
            return base_text
        return (
            f"## Instructions\n{instructions.strip()}\n\n"
            f"## Task\n{base_text}"
        )

    def _resolve_input(
        self,
        step: WorkflowStep,
        original_input: str,
        prev_output: str | None,
        all_outputs: dict[int, str],
    ) -> str:
        mode = step.input_mode or "chain"

        if mode == "original":
            return original_input
        elif mode == "custom" and step.input_template:
            result = step.input_template
            result = result.replace("{{input}}", original_input)
            result = result.replace("{{prev_output}}", prev_output or "")
            for group_num, output in all_outputs.items():
                result = result.replace(f"{{{{step_{group_num}_output}}}}", output)
            return result
        else:
            # chain (default) β€” use previous output if available, else original
            return prev_output if prev_output else original_input

    def _collect_group_output(self, step_runs: list[WorkflowStepRun]) -> str:
        outputs = []
        for sr in sorted(step_runs, key=lambda x: x.step_group):
            if sr.output_text:
                outputs.append(sr.output_text)
        return "\n\n---\n\n".join(outputs) if outputs else ""

    def _collect_child_output(self, child_run) -> str:
        """Collect output from a completed child workflow run."""
        if not child_run.step_runs:
            return ""
        last_group = max(sr.step_group for sr in child_run.step_runs)
        outputs = [
            sr.output_text for sr in child_run.step_runs
            if sr.step_group == last_group and sr.output_text
        ]
        return "\n\n---\n\n".join(outputs)

    def _extract_task_output(self, task: Task) -> str:
        if task.artifacts:
            parts = []
            for artifact in task.artifacts:
                if isinstance(artifact, dict):
                    for part in artifact.get("parts", []):
                        if isinstance(part, dict) and part.get("type") == "text":
                            # A2A artifacts use "content" field; fall back to "data"
                            text = part.get("content") or part.get("data") or ""
                            parts.append(text)
            return "\n".join(parts) if parts else ""
        return ""

    def _estimate_cost(self, wf: Workflow) -> int:
        total = 0
        for step in wf.steps:
            if step.agent and step.skill:
                avg = getattr(step.skill, "avg_credits", None)
                total += int(avg) if avg else 1
            else:
                total += 1
        return total

    def _tally_credits(self, run: WorkflowRun) -> None:
        total = Decimal("0")
        for sr in run.step_runs:
            if sr.credits_charged:
                total += sr.credits_charged
        run.total_credits_charged = total

    async def _settle_ucp_run(self, run: "WorkflowRun") -> None:
        """Settle UCP credit reservation after workflow run reaches terminal state.

        Releases unused portion of pre-reserved budget and updates the
        linked schedule's UCP counters.
        """
        if not run.schedule_id:
            return

        from src.models.schedule import Schedule
        result = await self.db.execute(
            select(Schedule).where(Schedule.id == run.schedule_id)
        )
        schedule = result.scalar_one_or_none()
        if not schedule or schedule.credit_budget_per_run is None:
            return  # Not a UCP schedule

        budget = float(schedule.credit_budget_per_run)
        actual_cost = float(run.total_credits_charged or 0)
        unused = budget - actual_cost

        # Release unused portion of the pre-reserved budget
        if unused > 0:
            from src.services.credit_ledger import CreditLedgerService
            ledger = CreditLedgerService(self.db)
            await ledger.release_credits(
                owner_id=run.user_id,
                amount=unused,
                task_id=None,
            )

        # Update schedule counters
        if run.status == "completed":
            schedule.successful_runs += 1
        else:
            schedule.failed_runs += 1
        schedule.total_runs += 1
        schedule.total_credits_spent += Decimal(str(actual_cost))
        schedule.last_run_id = run.id

    # ------------------------------------------------------------------
    # Cancel run
    # ------------------------------------------------------------------

    async def cancel_run(self, run_id: UUID, user_id: UUID) -> WorkflowRun:
        result = await self.db.execute(
            select(WorkflowRun)
            .where(WorkflowRun.id == run_id)
            .options(selectinload(WorkflowRun.step_runs))
        )
        run = result.scalar_one_or_none()
        if not run:
            raise MarketplaceError(status_code=404, detail="Workflow run not found")
        if run.user_id != user_id:
            raise MarketplaceError(status_code=403, detail="Not your workflow run")
        # Guard: cancel is only meaningful while the run is still active.
        # Terminal runs (completed / failed / canceled) surface a structured
        # 409 (RunTerminalError) so the frontend can branch on
        # ``detail.code == "RUN_TERMINAL"`` and render a friendly toast
        # instead of silently swallowing a plain-string 400. Mirrors the
        # TaskTerminalError pattern on task cancel.
        if run.status in ("completed", "failed", "canceled"):
            raise RunTerminalError(status=run.status)
        if run.status != "running":
            raise MarketplaceError(status_code=400, detail="Run is not in running state")

        now = datetime.now(timezone.utc)
        run.status = "canceled"
        run.completed_at = now
        for sr in run.step_runs:
            if sr.status in ("pending", "running"):
                sr.status = "failed"
                sr.error = "Canceled by user"
                sr.completed_at = now
                if sr.child_run_id:
                    await self.cancel_run(sr.child_run_id, user_id)
        self._tally_credits(run)
        await self.db.commit()
        return run

    # ------------------------------------------------------------------
    # Cancel individual step run
    # ------------------------------------------------------------------

    async def cancel_step_run(
        self, run_id: UUID, step_run_id: UUID, user_id: UUID
    ) -> WorkflowRun:
        result = await self.db.execute(
            select(WorkflowRun)
            .where(WorkflowRun.id == run_id)
            .options(selectinload(WorkflowRun.step_runs))
        )
        run = result.scalar_one_or_none()
        if not run:
            raise MarketplaceError(status_code=404, detail="Workflow run not found")
        if run.user_id != user_id:
            raise MarketplaceError(status_code=403, detail="Not your workflow run")
        if run.status != "running":
            raise MarketplaceError(status_code=400, detail="Run is not in running state")

        target_sr = None
        for sr in run.step_runs:
            if sr.id == step_run_id:
                target_sr = sr
                break

        if not target_sr:
            raise MarketplaceError(status_code=404, detail="Step run not found")
        if target_sr.status not in ("pending", "running"):
            raise MarketplaceError(
                status_code=400,
                detail=f"Step is already {target_sr.status}, cannot cancel"
            )

        now = datetime.now(timezone.utc)
        snapshot = run.workflow_snapshot or {}
        step_info = self._step_info_from_snapshot(snapshot, target_sr.step_id)
        agent_name = step_info.get("agent_name", "Unknown") if step_info else "Unknown"

        target_sr.status = "failed"
        target_sr.error = f"Canceled by user (agent: {agent_name})"
        target_sr.completed_at = now

        await self.db.commit()

        # Re-query with eager-loaded step_runs (refresh doesn't load relations in async)
        result2 = await self.db.execute(
            select(WorkflowRun)
            .where(WorkflowRun.id == run_id)
            .options(selectinload(WorkflowRun.step_runs))
        )
        return result2.scalar_one()

    # ------------------------------------------------------------------
    # Startup recovery
    # ------------------------------------------------------------------

    async def recover_stale_runs(self) -> int:
        now = datetime.now(timezone.utc)
        result = await self.db.execute(
            select(WorkflowRun)
            .where(WorkflowRun.status == "running")
            .options(selectinload(WorkflowRun.step_runs))
        )
        runs = list(result.scalars().unique().all())

        count = 0
        for run in runs:
            run.status = "failed"
            run.error = "Process restarted during execution"
            run.completed_at = now
            for sr in run.step_runs:
                if sr.status == "running":
                    sr.status = "failed"
                    sr.error = "Process restarted during execution"
                    sr.completed_at = now
            count += 1

        if count:
            await self.db.commit()
            logger.info("Recovered %d stale workflow runs after restart", count)
        return count