File size: 6,195 Bytes
04f192c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-FileCopyrightText: Copyright contributors to the CopilotJ project.
#
# SPDX-License-Identifier: Apache-2.0

import uuid
from typing import Any, Optional

from copilotj.core import ToolCall
from copilotj.workflow.contract import (
    RUNS_DIR,
    WorkflowExecutionContext,
    bind_workflow_context,
    expand_batch_inputs,
    render_templates,
    template_uses_run_dir,
    verify_declared_outputs,
)
from copilotj.workflow.manager import Workflow, WorkflowManager, WorkflowStep


class WorkflowExecutor:
    """Execute a workflow after binding its runtime interface."""

    def __init__(self, leader_agent):
        self.leader_agent = leader_agent

    async def _exec_tool(self, action: dict):
        tool_obj = next((t for t in self.leader_agent.tools if getattr(t, "name", None) == action.get("name")), None)
        if not tool_obj:
            names = [getattr(t, "name", None) for t in self.leader_agent.tools]
            raise RuntimeError(f"Tool '{action.get('name')}' not found. Registered: {names}")
        if not isinstance(action.get("args"), dict):
            args = action.get("args")
            raise TypeError(f"Tool '{action.get('name')}' expects args as dict, got {type(args)}: {args}")

        args = tool_obj.args_type().model_validate(action.get("args"))
        tool_call = ToolCall(id=str(uuid.uuid4()), tool=tool_obj, args=args)
        return await self.leader_agent._call_tool(tool_call)

    async def execute_workflow(
        self,
        workflow: Workflow,
        stop_on_error: bool = True,
        inputs: Optional[dict[str, Any]] = None,
    ) -> list[dict[str, Any]]:
        batch_inputs = expand_batch_inputs(workflow.interface, inputs)
        if len(batch_inputs) == 1:
            return await self._execute_bound_workflow(workflow, stop_on_error, batch_inputs[0])
        return await self._execute_batch(workflow, stop_on_error, batch_inputs)

    async def _execute_batch(
        self,
        workflow: Workflow,
        stop_on_error: bool,
        batch_inputs: list[dict[str, Any]],
    ) -> list[dict[str, Any]]:
        results = [self._batch_start_result(batch_inputs)]
        for index, item_inputs in enumerate(batch_inputs, 1):
            item_results = await self._execute_bound_workflow(workflow, stop_on_error, item_inputs)
            results.extend(self._with_batch_metadata(index, item_inputs, item_results))
            if stop_on_error and any(not result["ok"] for result in item_results):
                break
        return results

    async def _execute_bound_workflow(
        self,
        workflow: Workflow,
        stop_on_error: bool,
        inputs: dict[str, Any],
    ) -> list[dict[str, Any]]:
        context = self._bind_context(workflow, inputs)
        results = []
        for step in workflow.steps:
            action = self._render_action(step, context)
            self._validate_args(step, action)
            try:
                res = await self._exec_tool(action)
                results.append({"step_id": step.id, "action": action, "ok": True, "result": res})
            except Exception as e:
                results.append({"step_id": step.id, "action": action, "ok": False, "error": str(e)})
                if stop_on_error:
                    break

        self._append_output_verification(results, context)
        return results

    async def execute_workflow_by_id(
        self,
        wf_id: str,
        stop_on_error: bool = True,
        inputs: Optional[dict[str, Any]] = None,
    ) -> list[dict[str, Any]]:
        workflow = WorkflowManager.load_workflow(wf_id)
        return await self.execute_workflow(workflow, stop_on_error, inputs)

    @staticmethod
    def _render_action(step: WorkflowStep, context: WorkflowExecutionContext) -> dict:
        action = render_templates(step.action, context.to_template_scope())
        if not isinstance(action, dict):
            raise TypeError(f"Workflow step {step.id} action must be dict, got {type(action)}")
        return action

    @staticmethod
    def _workflow_steps_use_run_dir(workflow: Workflow) -> bool:
        return any(template_uses_run_dir(step.action) for step in workflow.steps)

    @staticmethod
    def _bind_context(workflow: Workflow, inputs: dict[str, Any]) -> WorkflowExecutionContext:
        return bind_workflow_context(
            workflow.interface,
            inputs,
            RUNS_DIR,
            require_run_dir=WorkflowExecutor._workflow_steps_use_run_dir(workflow),
            run_name=workflow.meta.id,
        )

    @staticmethod
    def _validate_args(step: WorkflowStep, action: dict):
        args = action.get("args")
        if isinstance(args, dict):
            return
        raise TypeError(f"Workflow step {step.id} action.args must be dict, got {type(args)}: {args}")

    @staticmethod
    def _batch_start_result(batch_inputs: list[dict[str, Any]]) -> dict[str, Any]:
        return {
            "step_id": "batch",
            "action": {"name": "expand_batch_inputs"},
            "ok": True,
            "result": {"count": len(batch_inputs), "items": batch_inputs},
        }

    @staticmethod
    def _with_batch_metadata(
        index: int, item_inputs: dict[str, Any], results: list[dict[str, Any]]
    ) -> list[dict[str, Any]]:
        tagged = []
        for result in results:
            item_result = dict(result)
            item_result["batch_index"] = index
            item_result["batch_inputs"] = item_inputs
            item_result["step_id"] = f"{index}.{result['step_id']}"
            tagged.append(item_result)
        return tagged

    @staticmethod
    def _append_output_verification(results: list[dict[str, Any]], context: WorkflowExecutionContext):
        failed = any(not result["ok"] for result in results)
        if failed or not context.outputs:
            return
        try:
            outputs = verify_declared_outputs(context.outputs)
            results.append({"step_id": "outputs", "action": {"name": "verify_outputs"}, "ok": True, "result": outputs})
        except Exception as e:
            results.append({"step_id": "outputs", "action": {"name": "verify_outputs"}, "ok": False, "error": str(e)})