codecraftai-agent-kit 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. ccai/agentkit/__init__.py +304 -0
  2. ccai/agentkit/addressresolver.py +177 -0
  3. ccai/agentkit/agent.py +2945 -0
  4. ccai/agentkit/agentaddress.py +187 -0
  5. ccai/agentkit/agentconfiguration.py +581 -0
  6. ccai/agentkit/agentidentity.py +152 -0
  7. ccai/agentkit/agentregistry.py +221 -0
  8. ccai/agentkit/agentstatemachine.py +134 -0
  9. ccai/agentkit/alternateproviderstrategy.py +36 -0
  10. ccai/agentkit/approvalgate.py +238 -0
  11. ccai/agentkit/approvalrequest.py +250 -0
  12. ccai/agentkit/asyncagent.py +187 -0
  13. ccai/agentkit/breakpoint.py +150 -0
  14. ccai/agentkit/builtinagentmetrics.py +114 -0
  15. ccai/agentkit/builtins/__init__.py +11 -0
  16. ccai/agentkit/builtins/filereadtool.py +90 -0
  17. ccai/agentkit/builtins/filewritetool.py +93 -0
  18. ccai/agentkit/builtins/httprequesttool.py +169 -0
  19. ccai/agentkit/builtins/shellcommandtool.py +190 -0
  20. ccai/agentkit/cachedresultstrategy.py +43 -0
  21. ccai/agentkit/checkpointmanager.py +219 -0
  22. ccai/agentkit/circuitbreaker.py +230 -0
  23. ccai/agentkit/circuitbreakerconfiguration.py +158 -0
  24. ccai/agentkit/circuitbreakerevent.py +158 -0
  25. ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
  26. ccai/agentkit/circuitbreakerregistry.py +116 -0
  27. ccai/agentkit/circuitbreakerstate.py +44 -0
  28. ccai/agentkit/clearcacheaction.py +46 -0
  29. ccai/agentkit/concurrencybridge.py +143 -0
  30. ccai/agentkit/concurrencymodel.py +19 -0
  31. ccai/agentkit/conditionevaluator.py +594 -0
  32. ccai/agentkit/configurationchangeevent.py +179 -0
  33. ccai/agentkit/configurationerrors.py +152 -0
  34. ccai/agentkit/configurationlayer.py +160 -0
  35. ccai/agentkit/configurationlayersource.py +46 -0
  36. ccai/agentkit/configurationmanager.py +680 -0
  37. ccai/agentkit/configurationschema.py +224 -0
  38. ccai/agentkit/configurationschemafield.py +217 -0
  39. ccai/agentkit/configurationserializer.py +163 -0
  40. ccai/agentkit/configurationvalidationresult.py +118 -0
  41. ccai/agentkit/contextsummarizer.py +170 -0
  42. ccai/agentkit/contextwindow.py +264 -0
  43. ccai/agentkit/contextwindowstrategy.py +57 -0
  44. ccai/agentkit/correlationcontext.py +156 -0
  45. ccai/agentkit/costestimate.py +139 -0
  46. ccai/agentkit/costtracker.py +121 -0
  47. ccai/agentkit/deadletterentry.py +134 -0
  48. ccai/agentkit/deadletterquery.py +119 -0
  49. ccai/agentkit/deadletterqueue.py +123 -0
  50. ccai/agentkit/deadletterstore.py +86 -0
  51. ccai/agentkit/debuginspector.py +211 -0
  52. ccai/agentkit/debugsession.py +223 -0
  53. ccai/agentkit/defaultvaluestrategy.py +43 -0
  54. ccai/agentkit/degradationchangeevent.py +120 -0
  55. ccai/agentkit/degradationlevel.py +44 -0
  56. ccai/agentkit/degradationmanager.py +212 -0
  57. ccai/agentkit/degradationpolicy.py +130 -0
  58. ccai/agentkit/degradationstrategy.py +66 -0
  59. ccai/agentkit/embeddingprovider.py +106 -0
  60. ccai/agentkit/errors.py +95 -0
  61. ccai/agentkit/executionrecord.py +213 -0
  62. ccai/agentkit/executionrecorder.py +180 -0
  63. ccai/agentkit/executionrecording.py +230 -0
  64. ccai/agentkit/executionreplayer.py +187 -0
  65. ccai/agentkit/expirationpolicy.py +116 -0
  66. ccai/agentkit/fallbackchain.py +82 -0
  67. ccai/agentkit/featureflag.py +154 -0
  68. ccai/agentkit/featureflagevaluator.py +109 -0
  69. ccai/agentkit/featureflagregistry.py +258 -0
  70. ccai/agentkit/filedeadletterstore.py +112 -0
  71. ccai/agentkit/filememorystore.py +291 -0
  72. ccai/agentkit/healthcheck.py +46 -0
  73. ccai/agentkit/healthcheckregistry.py +51 -0
  74. ccai/agentkit/healthmonitor.py +258 -0
  75. ccai/agentkit/healthstatus.py +105 -0
  76. ccai/agentkit/hotreloadmonitor.py +214 -0
  77. ccai/agentkit/hotreloadpolicy.py +160 -0
  78. ccai/agentkit/inmemorydeadletterstore.py +61 -0
  79. ccai/agentkit/inmemorystore.py +173 -0
  80. ccai/agentkit/jsonmessageserializer.py +89 -0
  81. ccai/agentkit/jsonoutputparser.py +50 -0
  82. ccai/agentkit/lifecyclestate.py +22 -0
  83. ccai/agentkit/llmconversation.py +153 -0
  84. ccai/agentkit/llmerrors.py +193 -0
  85. ccai/agentkit/llmmessage.py +158 -0
  86. ccai/agentkit/llmprovider.py +158 -0
  87. ccai/agentkit/llmproviderregistry.py +200 -0
  88. ccai/agentkit/llmresponse.py +190 -0
  89. ccai/agentkit/llmstreamchunk.py +65 -0
  90. ccai/agentkit/llmstreamhandler.py +48 -0
  91. ccai/agentkit/llmtoolbridge.py +154 -0
  92. ccai/agentkit/logexporter.py +316 -0
  93. ccai/agentkit/logformatter.py +169 -0
  94. ccai/agentkit/memoryconfiguration.py +243 -0
  95. ccai/agentkit/memoryentry.py +254 -0
  96. ccai/agentkit/memoryerrors.py +135 -0
  97. ccai/agentkit/memoryindex.py +213 -0
  98. ccai/agentkit/memoryquery.py +248 -0
  99. ccai/agentkit/memoryqueryresult.py +86 -0
  100. ccai/agentkit/memoryscope.py +54 -0
  101. ccai/agentkit/memorystore.py +260 -0
  102. ccai/agentkit/memorystorehealthcheck.py +33 -0
  103. ccai/agentkit/memorystoreregistry.py +106 -0
  104. ccai/agentkit/message.py +310 -0
  105. ccai/agentkit/messageenvelope.py +144 -0
  106. ccai/agentkit/messagepattern.py +50 -0
  107. ccai/agentkit/messagerouter.py +290 -0
  108. ccai/agentkit/messageserializer.py +106 -0
  109. ccai/agentkit/messageserializerregistry.py +163 -0
  110. ccai/agentkit/messagingconfiguration.py +397 -0
  111. ccai/agentkit/messagingerrors.py +338 -0
  112. ccai/agentkit/metricdefinition.py +164 -0
  113. ccai/agentkit/metricmeasurement.py +178 -0
  114. ccai/agentkit/metricscollector.py +258 -0
  115. ccai/agentkit/metricsexporter.py +303 -0
  116. ccai/agentkit/metricsregistry.py +130 -0
  117. ccai/agentkit/metricssnapshot.py +155 -0
  118. ccai/agentkit/metrictype.py +51 -0
  119. ccai/agentkit/msgpackmessageserializer.py +97 -0
  120. ccai/agentkit/observabilityconfiguration.py +546 -0
  121. ccai/agentkit/observabilityerror.py +67 -0
  122. ccai/agentkit/observabilitypipeline.py +252 -0
  123. ccai/agentkit/outputparser.py +82 -0
  124. ccai/agentkit/outputschema.py +142 -0
  125. ccai/agentkit/parallelbranch.py +87 -0
  126. ccai/agentkit/platform/__init__.py +43 -0
  127. ccai/agentkit/platform/adapters/__init__.py +18 -0
  128. ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
  129. ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
  130. ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
  131. ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
  132. ccai/agentkit/platform/adapters/platformadapter.py +139 -0
  133. ccai/agentkit/platform/deployment/__init__.py +15 -0
  134. ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
  135. ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
  136. ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
  137. ccai/agentkit/platform/errors.py +224 -0
  138. ccai/agentkit/platform/platformconfiguration.py +412 -0
  139. ccai/agentkit/platform/platformdetector.py +125 -0
  140. ccai/agentkit/platform/platformruntime.py +331 -0
  141. ccai/agentkit/platform/platformserviceregistry.py +149 -0
  142. ccai/agentkit/platform/platformtype.py +60 -0
  143. ccai/agentkit/platform/services/__init__.py +19 -0
  144. ccai/agentkit/platform/services/computeservice.py +112 -0
  145. ccai/agentkit/platform/services/invocationresult.py +173 -0
  146. ccai/agentkit/platform/services/messagingservice.py +135 -0
  147. ccai/agentkit/platform/services/platformservice.py +111 -0
  148. ccai/agentkit/platform/services/queuemessage.py +193 -0
  149. ccai/agentkit/platform/services/storageobject.py +195 -0
  150. ccai/agentkit/platform/services/storageservice.py +159 -0
  151. ccai/agentkit/pluginconfiguration.py +241 -0
  152. ccai/agentkit/plugindependency.py +129 -0
  153. ccai/agentkit/plugindescriptor.py +225 -0
  154. ccai/agentkit/pluginlifecyclehook.py +41 -0
  155. ccai/agentkit/pluginmanager.py +360 -0
  156. ccai/agentkit/pluginstatus.py +47 -0
  157. ccai/agentkit/pooledagent.py +116 -0
  158. ccai/agentkit/prompttemplate.py +221 -0
  159. ccai/agentkit/prompttemplateregistry.py +145 -0
  160. ccai/agentkit/protobufmessageserializer.py +144 -0
  161. ccai/agentkit/pubsubbroker.py +311 -0
  162. ccai/agentkit/py.typed +0 -0
  163. ccai/agentkit/reconnecttransportaction.py +47 -0
  164. ccai/agentkit/regexoutputparser.py +68 -0
  165. ccai/agentkit/requestresponsehandler.py +274 -0
  166. ccai/agentkit/resetcircuitbreakeraction.py +48 -0
  167. ccai/agentkit/resilienceconfiguration.py +191 -0
  168. ccai/agentkit/resilienceerrors.py +103 -0
  169. ccai/agentkit/resiliencepipeline.py +201 -0
  170. ccai/agentkit/retryattempt.py +158 -0
  171. ccai/agentkit/retryexecutor.py +157 -0
  172. ccai/agentkit/retrypolicy.py +195 -0
  173. ccai/agentkit/retryresult.py +186 -0
  174. ccai/agentkit/selfhealingaction.py +42 -0
  175. ccai/agentkit/selfhealingpolicy.py +67 -0
  176. ccai/agentkit/selfhealingresult.py +130 -0
  177. ccai/agentkit/stepexecutionstatus.py +52 -0
  178. ccai/agentkit/stepresult.py +198 -0
  179. ccai/agentkit/steps/__init__.py +9 -0
  180. ccai/agentkit/steps/agentstep.py +247 -0
  181. ccai/agentkit/steps/approvalstep.py +276 -0
  182. ccai/agentkit/steps/llmstep.py +403 -0
  183. ccai/agentkit/steps/subworkflowstep.py +270 -0
  184. ccai/agentkit/steps/toolstep.py +265 -0
  185. ccai/agentkit/structuredlogentry.py +222 -0
  186. ccai/agentkit/structuredlogger.py +189 -0
  187. ccai/agentkit/subscription.py +141 -0
  188. ccai/agentkit/threadedagent.py +94 -0
  189. ccai/agentkit/tokenusage.py +136 -0
  190. ccai/agentkit/tool.py +203 -0
  191. ccai/agentkit/toolchain.py +268 -0
  192. ccai/agentkit/toolchainexecutor.py +134 -0
  193. ccai/agentkit/toolchainresult.py +166 -0
  194. ccai/agentkit/tooldescriptor.py +203 -0
  195. ccai/agentkit/toolerrors.py +160 -0
  196. ccai/agentkit/toolexecutor.py +168 -0
  197. ccai/agentkit/toolfactory.py +60 -0
  198. ccai/agentkit/toolregistry.py +184 -0
  199. ccai/agentkit/toolresult.py +142 -0
  200. ccai/agentkit/toolschema.py +197 -0
  201. ccai/agentkit/tracecontext.py +294 -0
  202. ccai/agentkit/traceevent.py +166 -0
  203. ccai/agentkit/traceexporter.py +305 -0
  204. ccai/agentkit/tracer.py +234 -0
  205. ccai/agentkit/tracespan.py +349 -0
  206. ccai/agentkit/transitionrecord.py +84 -0
  207. ccai/agentkit/transport.py +334 -0
  208. ccai/agentkit/transportconfiguration.py +436 -0
  209. ccai/agentkit/transporthealthcheck.py +36 -0
  210. ccai/agentkit/transportregistry.py +224 -0
  211. ccai/agentkit/transports/__init__.py +28 -0
  212. ccai/agentkit/transports/grpctransport.py +410 -0
  213. ccai/agentkit/transports/httptransport.py +423 -0
  214. ccai/agentkit/transports/messagequeuetransport.py +489 -0
  215. ccai/agentkit/transports/websockettransport.py +473 -0
  216. ccai/agentkit/workflowcheckpoint.py +208 -0
  217. ccai/agentkit/workflowconfiguration.py +295 -0
  218. ccai/agentkit/workflowcontext.py +249 -0
  219. ccai/agentkit/workflowdefinition.py +790 -0
  220. ccai/agentkit/workflowedge.py +128 -0
  221. ccai/agentkit/workflowerrors.py +295 -0
  222. ccai/agentkit/workflowexecutionstatus.py +48 -0
  223. ccai/agentkit/workflowexecutor.py +1121 -0
  224. ccai/agentkit/workflowregistry.py +185 -0
  225. ccai/agentkit/workflowresult.py +250 -0
  226. ccai/agentkit/workflowstep.py +195 -0
  227. codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
  228. codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
  229. codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
  230. codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,790 @@
1
+ """
2
+ Defines the WorkflowDefinition class representing an immutable
3
+ directed acyclic graph (DAG) of WorkflowStep nodes connected by
4
+ WorkflowEdge edges in the Workflow & Orchestration feature.
5
+
6
+ A WorkflowDefinition contains a name, version, optional description,
7
+ a dictionary of WorkflowStep objects keyed by step identifier, a list
8
+ of WorkflowEdge objects, a designated start step identifier, and an
9
+ optional list of ParallelBranch declarations.
10
+
11
+ The WorkflowDefinition validates structural integrity at construction
12
+ time, checking that the start step exists, all edge references are
13
+ valid, the graph contains no cycles, all steps are reachable from
14
+ the start step, and all ParallelBranch fork/join steps are valid
15
+ with converging paths.
16
+
17
+ .. module:: ccai.agentkit.workflowdefinition
18
+ :platform: Darwin, Linux, Unix, Windows
19
+ :synopsis: Immutable DAG workflow definition with validation.
20
+ """
21
+
22
+ import json
23
+
24
+ from collections import deque
25
+ from typing import Optional
26
+
27
+ import yaml
28
+
29
+ from ccai.agentkit.workflowstep import WorkflowStep
30
+ from ccai.agentkit.workflowedge import WorkflowEdge
31
+ from ccai.agentkit.parallelbranch import ParallelBranch
32
+ from ccai.agentkit.workflowerrors import WorkflowDefinitionError
33
+ from ccai.agentkit.stepexecutionstatus import StepExecutionStatus
34
+
35
+
36
+ class _PassthroughStep(WorkflowStep):
37
+ """
38
+ A minimal concrete WorkflowStep subclass used for round-trip
39
+ deserialization when no step_type_registry is provided.
40
+
41
+ The _PassthroughStep stores the raw step data dictionary and
42
+ returns a dummy StepResult from execute. This allows
43
+ WorkflowDefinition instances to be reconstructed from
44
+ serialized data without requiring the original step classes.
45
+
46
+ :param step_id: The unique identifier for this step.
47
+ :param name: The human-readable name for this step.
48
+ :param step_type: The step type string.
49
+ :param step_data: The raw dictionary of step data from
50
+ deserialization.
51
+ :param input_schema: An optional input schema dictionary.
52
+ :param output_schema: An optional output schema dictionary.
53
+ :param tags: An optional tags dictionary.
54
+ :param retry_policy: An optional retry policy.
55
+ """
56
+
57
+ def __init__(self, step_id: str, name: str, step_type: str,
58
+ step_data: Optional[dict] = None,
59
+ input_schema: Optional[dict] = None,
60
+ output_schema: Optional[dict] = None,
61
+ tags: Optional[dict] = None,
62
+ retry_policy=None) -> None:
63
+ super().__init__(
64
+ step_id=step_id, name=name, step_type=step_type,
65
+ input_schema=input_schema, output_schema=output_schema,
66
+ tags=tags, retry_policy=retry_policy
67
+ )
68
+ self._step_data = dict(step_data) if step_data is not None else {}
69
+ return
70
+
71
+ @property
72
+ def step_data(self) -> dict:
73
+ """
74
+ The raw step data dictionary from deserialization.
75
+
76
+ :returns: A dictionary of step data fields.
77
+ """
78
+ return self._step_data
79
+
80
+ def execute(self, context) -> "StepResult":
81
+ """
82
+ Returns a dummy StepResult with COMPLETED status.
83
+
84
+ This implementation exists only to satisfy the abstract
85
+ interface requirement. _PassthroughStep is not intended
86
+ for actual workflow execution.
87
+
88
+ :param context: The WorkflowContext (unused).
89
+
90
+ :returns: A StepResult with COMPLETED status.
91
+ """
92
+ from ccai.agentkit.stepresult import StepResult
93
+
94
+ rtnval = StepResult(
95
+ step_id=self._step_id,
96
+ step_name=self._name,
97
+ status=StepExecutionStatus.COMPLETED
98
+ )
99
+ return rtnval
100
+
101
+
102
+
103
+ class WorkflowDefinition:
104
+ """
105
+ Immutable DAG of WorkflowStep nodes connected by WorkflowEdge
106
+ edges. Validates structural integrity at construction time.
107
+
108
+ A WorkflowDefinition represents a complete workflow as a directed
109
+ acyclic graph. It contains a name, version, optional description,
110
+ a dictionary of WorkflowStep objects keyed by step identifier,
111
+ a list of WorkflowEdge objects defining the connections between
112
+ steps, a designated start step identifier, and an optional list
113
+ of ParallelBranch declarations for concurrent execution
114
+ boundaries.
115
+
116
+ At construction time the definition validates that:
117
+
118
+ 1. The start step identifier references a step in the steps
119
+ dictionary.
120
+ 2. All edge source and target step identifiers reference valid
121
+ steps.
122
+ 3. The graph contains no cycles (DFS-based cycle detection).
123
+ 4. All steps are reachable from the start step (BFS from start).
124
+ 5. All ParallelBranch fork/join steps are valid and paths
125
+ converge at the join step.
126
+
127
+ :param name: The workflow name string.
128
+ :param version: The workflow version string.
129
+ :param steps: A dictionary of WorkflowStep objects keyed by
130
+ step identifier.
131
+ :param edges: A list of WorkflowEdge objects defining the
132
+ connections between steps.
133
+ :param start_step_id: The identifier of the step where
134
+ execution begins.
135
+ :param parallel_branches: An optional list of ParallelBranch
136
+ declarations. Defaults to an empty list.
137
+ :param description: An optional description string for the
138
+ workflow.
139
+
140
+ :raises WorkflowDefinitionError: When any structural validation
141
+ fails.
142
+ """
143
+
144
+ def __init__(self, name: str, version: str, steps: dict,
145
+ edges: list, start_step_id: str,
146
+ parallel_branches: Optional[list] = None,
147
+ description: Optional[str] = None) -> None:
148
+ self._name = name
149
+ self._version = version
150
+ self._description = description
151
+ self._steps = dict(steps)
152
+ self._edges = list(edges)
153
+ self._start_step_id = start_step_id
154
+ self._parallel_branches = list(parallel_branches) if parallel_branches is not None else []
155
+
156
+ self._validate()
157
+
158
+ return
159
+
160
+ def _validate(self) -> None:
161
+ """
162
+ Validates the workflow DAG structural integrity.
163
+
164
+ Checks are performed in the following order:
165
+
166
+ 1. Start step exists in the steps dictionary.
167
+ 2. All edge source and target step identifiers reference
168
+ valid steps.
169
+ 3. No cycles exist in the graph (DFS with WHITE/GRAY/BLACK
170
+ coloring).
171
+ 4. All steps are reachable from the start step (BFS from
172
+ start).
173
+ 5. ParallelBranch fork/join steps are valid and all paths
174
+ from fork converge at join.
175
+
176
+ :raises WorkflowDefinitionError: When any validation check
177
+ fails.
178
+ """
179
+ self._validate_start_step()
180
+ self._validate_edge_references()
181
+ self._validate_no_cycles()
182
+ self._validate_reachability()
183
+ self._validate_parallel_branches()
184
+
185
+ return
186
+
187
+ def _validate_start_step(self) -> None:
188
+ """
189
+ Validates that the start step identifier references a step
190
+ present in the steps dictionary.
191
+
192
+ :raises WorkflowDefinitionError: When the start step
193
+ identifier is not found in the steps dictionary.
194
+ """
195
+ if self._start_step_id not in self._steps:
196
+ detail = "Start step '{}' not found in steps dictionary".format(
197
+ self._start_step_id
198
+ )
199
+ raise WorkflowDefinitionError(self._name, detail)
200
+
201
+ return
202
+
203
+ def _validate_edge_references(self) -> None:
204
+ """
205
+ Validates that all edge source and target step identifiers
206
+ reference steps present in the steps dictionary.
207
+
208
+ :raises WorkflowDefinitionError: When an edge references
209
+ a step identifier not in the steps dictionary.
210
+ """
211
+ for edge in self._edges:
212
+ if edge.source_step_id not in self._steps:
213
+ detail = "Edge references invalid step '{}'".format(
214
+ edge.source_step_id
215
+ )
216
+ raise WorkflowDefinitionError(self._name, detail)
217
+
218
+ if edge.target_step_id not in self._steps:
219
+ detail = "Edge references invalid step '{}'".format(
220
+ edge.target_step_id
221
+ )
222
+ raise WorkflowDefinitionError(self._name, detail)
223
+
224
+ return
225
+
226
+ def _validate_no_cycles(self) -> None:
227
+ """
228
+ Validates that the graph contains no cycles using DFS
229
+ with WHITE/GRAY/BLACK coloring.
230
+
231
+ WHITE = not visited, GRAY = in current DFS path,
232
+ BLACK = fully processed.
233
+
234
+ :raises WorkflowDefinitionError: When a cycle is detected,
235
+ identifying the steps involved.
236
+ """
237
+ WHITE = 0
238
+ GRAY = 1
239
+ BLACK = 2
240
+
241
+ color = {}
242
+ for step_id in self._steps:
243
+ color[step_id] = WHITE
244
+
245
+ adjacency = {}
246
+ for step_id in self._steps:
247
+ adjacency[step_id] = []
248
+
249
+ for edge in self._edges:
250
+ adjacency[edge.source_step_id].append(edge.target_step_id)
251
+
252
+ cycle_steps = []
253
+
254
+ def dfs(node: str) -> bool:
255
+ """
256
+ Performs depth-first search from the given node to
257
+ detect cycles.
258
+
259
+ :param node: The step identifier to visit.
260
+
261
+ :returns: True if a cycle is detected, False otherwise.
262
+ """
263
+ color[node] = GRAY
264
+
265
+ for neighbor in adjacency[node]:
266
+ if color[neighbor] == GRAY:
267
+ cycle_steps.append(neighbor)
268
+ cycle_steps.append(node)
269
+ return True
270
+
271
+ if color[neighbor] == WHITE:
272
+ found_cycle = dfs(neighbor)
273
+ if found_cycle:
274
+ cycle_steps.append(node)
275
+ return True
276
+
277
+ color[node] = BLACK
278
+ return False
279
+
280
+ for step_id in self._steps:
281
+ if color[step_id] == WHITE:
282
+ found_cycle = dfs(step_id)
283
+ if found_cycle:
284
+ unique_cycle_steps = []
285
+ seen = set()
286
+ for sid in cycle_steps:
287
+ if sid not in seen:
288
+ unique_cycle_steps.append(sid)
289
+ seen.add(sid)
290
+
291
+ step_list = ", ".join(unique_cycle_steps)
292
+ detail = "Cycle detected involving steps: {}".format(
293
+ step_list
294
+ )
295
+ raise WorkflowDefinitionError(self._name, detail)
296
+
297
+ return
298
+
299
+ def _validate_reachability(self) -> None:
300
+ """
301
+ Validates that all steps are reachable from the start step
302
+ using breadth-first search.
303
+
304
+ :raises WorkflowDefinitionError: When unreachable steps
305
+ are detected, identifying the unreachable step
306
+ identifiers.
307
+ """
308
+ adjacency = {}
309
+ for step_id in self._steps:
310
+ adjacency[step_id] = []
311
+
312
+ for edge in self._edges:
313
+ adjacency[edge.source_step_id].append(edge.target_step_id)
314
+
315
+ visited = set()
316
+ queue = deque()
317
+ queue.append(self._start_step_id)
318
+ visited.add(self._start_step_id)
319
+
320
+ while len(queue) > 0:
321
+ current = queue.popleft()
322
+ for neighbor in adjacency[current]:
323
+ if neighbor not in visited:
324
+ visited.add(neighbor)
325
+ queue.append(neighbor)
326
+
327
+ all_step_ids = set(self._steps.keys())
328
+ unreachable = all_step_ids - visited
329
+
330
+ if len(unreachable) > 0:
331
+ unreachable_list = ", ".join(sorted(unreachable))
332
+ detail = "Unreachable steps: {}".format(unreachable_list)
333
+ raise WorkflowDefinitionError(self._name, detail)
334
+
335
+ return
336
+
337
+ def _validate_parallel_branches(self) -> None:
338
+ """
339
+ Validates that all ParallelBranch declarations have valid
340
+ fork and join step identifiers and that all paths from the
341
+ fork step converge at the join step.
342
+
343
+ :raises WorkflowDefinitionError: When a ParallelBranch
344
+ references an invalid step or paths do not converge.
345
+ """
346
+ for branch in self._parallel_branches:
347
+ fork_id = branch.fork_step_id
348
+ join_id = branch.join_step_id
349
+
350
+ if fork_id not in self._steps:
351
+ detail = "ParallelBranch references invalid fork step '{}'".format(
352
+ fork_id
353
+ )
354
+ raise WorkflowDefinitionError(self._name, detail)
355
+
356
+ if join_id not in self._steps:
357
+ detail = "ParallelBranch references invalid join step '{}'".format(
358
+ join_id
359
+ )
360
+ raise WorkflowDefinitionError(self._name, detail)
361
+
362
+ self._validate_paths_converge(fork_id, join_id)
363
+
364
+ return
365
+
366
+ def _validate_paths_converge(self, fork_id: str, join_id: str) -> None:
367
+ """
368
+ Validates that all paths from the fork step converge at
369
+ the join step using BFS. Every path from the fork must
370
+ reach the join step.
371
+
372
+ :param fork_id: The fork step identifier.
373
+ :param join_id: The join step identifier.
374
+
375
+ :raises WorkflowDefinitionError: When paths from the fork
376
+ do not all converge at the join step.
377
+ """
378
+ adjacency = {}
379
+ for step_id in self._steps:
380
+ adjacency[step_id] = []
381
+
382
+ for edge in self._edges:
383
+ adjacency[edge.source_step_id].append(edge.target_step_id)
384
+
385
+ outgoing_from_fork = adjacency.get(fork_id, [])
386
+
387
+ if len(outgoing_from_fork) == 0:
388
+ detail = "ParallelBranch fork step '{}' has no outgoing edges".format(
389
+ fork_id
390
+ )
391
+ raise WorkflowDefinitionError(self._name, detail)
392
+
393
+ for branch_start in outgoing_from_fork:
394
+ reached_join = self._can_reach(branch_start, join_id, adjacency)
395
+
396
+ if not reached_join:
397
+ detail = ("ParallelBranch paths from fork '{}' do not all "
398
+ "converge at join '{}'".format(fork_id, join_id))
399
+ raise WorkflowDefinitionError(self._name, detail)
400
+
401
+ return
402
+
403
+ def _can_reach(self, start_id: str, target_id: str, adjacency: dict) -> bool:
404
+ """
405
+ Determines whether the target step is reachable from the
406
+ start step using BFS.
407
+
408
+ :param start_id: The step identifier to start from.
409
+ :param target_id: The step identifier to reach.
410
+ :param adjacency: The adjacency list dictionary.
411
+
412
+ :returns: True if the target is reachable from start,
413
+ False otherwise.
414
+ """
415
+ if start_id == target_id:
416
+ return True
417
+
418
+ visited = set()
419
+ queue = deque()
420
+ queue.append(start_id)
421
+ visited.add(start_id)
422
+
423
+ while len(queue) > 0:
424
+ current = queue.popleft()
425
+
426
+ for neighbor in adjacency.get(current, []):
427
+ if neighbor == target_id:
428
+ return True
429
+
430
+ if neighbor not in visited:
431
+ visited.add(neighbor)
432
+ queue.append(neighbor)
433
+
434
+ return False
435
+
436
+ @property
437
+ def name(self) -> str:
438
+ """
439
+ The workflow name string.
440
+
441
+ :returns: The workflow name.
442
+ """
443
+ return self._name
444
+
445
+ @property
446
+ def version(self) -> str:
447
+ """
448
+ The workflow version string.
449
+
450
+ :returns: The workflow version.
451
+ """
452
+ return self._version
453
+
454
+ @property
455
+ def description(self) -> Optional[str]:
456
+ """
457
+ The optional description string for the workflow.
458
+
459
+ :returns: The description string or None.
460
+ """
461
+ return self._description
462
+
463
+ @property
464
+ def steps(self) -> dict:
465
+ """
466
+ The dictionary of WorkflowStep objects keyed by step
467
+ identifier.
468
+
469
+ :returns: A dictionary of step identifier to WorkflowStep
470
+ mappings.
471
+ """
472
+ return self._steps
473
+
474
+ @property
475
+ def edges(self) -> list:
476
+ """
477
+ The list of WorkflowEdge objects defining the connections
478
+ between steps.
479
+
480
+ :returns: A list of WorkflowEdge objects.
481
+ """
482
+ return self._edges
483
+
484
+ @property
485
+ def start_step_id(self) -> str:
486
+ """
487
+ The identifier of the step where execution begins.
488
+
489
+ :returns: The start step identifier string.
490
+ """
491
+ return self._start_step_id
492
+
493
+ @property
494
+ def parallel_branches(self) -> list:
495
+ """
496
+ The list of ParallelBranch declarations for concurrent
497
+ execution boundaries.
498
+
499
+ :returns: A list of ParallelBranch objects.
500
+ """
501
+ return self._parallel_branches
502
+
503
+ def get_step(self, step_id: str) -> Optional[WorkflowStep]:
504
+ """
505
+ Returns the WorkflowStep for the given step identifier,
506
+ or None when the identifier is not found.
507
+
508
+ :param step_id: The step identifier to look up.
509
+
510
+ :returns: The WorkflowStep instance or None.
511
+ """
512
+ rtnval = self._steps.get(step_id, None)
513
+ return rtnval
514
+
515
+ def get_outgoing_edges(self, step_id: str) -> list:
516
+ """
517
+ Returns the list of WorkflowEdge objects originating from
518
+ the given step, ordered by edge priority in ascending order.
519
+
520
+ :param step_id: The step identifier to get outgoing edges
521
+ for.
522
+
523
+ :returns: A list of WorkflowEdge objects sorted by priority
524
+ ascending.
525
+ """
526
+ matching_edges = []
527
+
528
+ for edge in self._edges:
529
+ if edge.source_step_id == step_id:
530
+ matching_edges.append(edge)
531
+
532
+ matching_edges.sort(key=lambda e: e.priority)
533
+
534
+ return matching_edges
535
+
536
+ def get_incoming_edges(self, step_id: str) -> list:
537
+ """
538
+ Returns the list of WorkflowEdge objects targeting the
539
+ given step.
540
+
541
+ :param step_id: The step identifier to get incoming edges
542
+ for.
543
+
544
+ :returns: A list of WorkflowEdge objects.
545
+ """
546
+ matching_edges = []
547
+
548
+ for edge in self._edges:
549
+ if edge.target_step_id == step_id:
550
+ matching_edges.append(edge)
551
+
552
+ return matching_edges
553
+
554
+ def get_terminal_steps(self) -> list:
555
+ """
556
+ Returns the list of step identifiers that have no outgoing
557
+ edges.
558
+
559
+ :returns: A list of step identifier strings.
560
+ """
561
+ steps_with_outgoing = set()
562
+
563
+ for edge in self._edges:
564
+ steps_with_outgoing.add(edge.source_step_id)
565
+
566
+ terminal_steps = []
567
+
568
+ for step_id in self._steps:
569
+ if step_id not in steps_with_outgoing:
570
+ terminal_steps.append(step_id)
571
+
572
+ return terminal_steps
573
+
574
+ def as_dict(self) -> dict:
575
+ """
576
+ Returns a dictionary representation of the workflow
577
+ definition including steps, edges, and parallel branches.
578
+
579
+ Steps are serialized as a dictionary of step identifier
580
+ to step data dictionaries. Edges are serialized as a list
581
+ of edge dictionaries. Parallel branches are serialized as
582
+ a list of branch dictionaries.
583
+
584
+ :returns: A dictionary containing name, version, description,
585
+ steps, edges, start_step_id, and parallel_branches.
586
+ """
587
+ steps_dict = {}
588
+
589
+ for step_id, step in self._steps.items():
590
+ step_entry = {
591
+ "step_type": step.step_type,
592
+ "name": step.name,
593
+ "input_schema": step.input_schema,
594
+ "output_schema": step.output_schema,
595
+ "tags": step.tags
596
+ }
597
+
598
+ if isinstance(step, _PassthroughStep) and len(step.step_data) > 0:
599
+ step_entry["step_data"] = step.step_data
600
+
601
+ steps_dict[step_id] = step_entry
602
+
603
+ edges_list = []
604
+ for edge in self._edges:
605
+ edges_list.append(edge.as_dict())
606
+
607
+ branches_list = []
608
+ for branch in self._parallel_branches:
609
+ branches_list.append(branch.as_dict())
610
+
611
+ rtnval = {
612
+ "name": self._name,
613
+ "version": self._version,
614
+ "description": self._description,
615
+ "steps": steps_dict,
616
+ "edges": edges_list,
617
+ "start_step_id": self._start_step_id,
618
+ "parallel_branches": branches_list
619
+ }
620
+
621
+ return rtnval
622
+
623
+ def to_json(self) -> str:
624
+ """
625
+ Serializes the workflow definition to a JSON string.
626
+
627
+ :returns: A JSON string representation of the workflow
628
+ definition.
629
+ """
630
+ data = self.as_dict()
631
+ rtnval = json.dumps(data)
632
+ return rtnval
633
+
634
+ def to_yaml(self) -> str:
635
+ """
636
+ Serializes the workflow definition to a YAML string.
637
+
638
+ :returns: A YAML string representation of the workflow
639
+ definition.
640
+ """
641
+ data = self.as_dict()
642
+ rtnval = yaml.safe_dump(data, default_flow_style=False)
643
+ return rtnval
644
+
645
+ @classmethod
646
+ def from_dict(cls, data: dict,
647
+ step_type_registry: Optional[dict] = None) -> "WorkflowDefinition":
648
+ """
649
+ Constructs a WorkflowDefinition from a dictionary
650
+ representation.
651
+
652
+ When a step_type_registry is provided, it is used to
653
+ reconstruct WorkflowStep subclasses by looking up the
654
+ step_type string in the registry. When no registry is
655
+ provided, a _PassthroughStep is created for each step
656
+ to enable round-trip serialization.
657
+
658
+ :param data: A dictionary containing the workflow
659
+ definition fields.
660
+ :param step_type_registry: An optional dictionary mapping
661
+ step type strings to WorkflowStep subclass factories.
662
+
663
+ :returns: A WorkflowDefinition instance.
664
+ """
665
+ name = data["name"]
666
+ version = data["version"]
667
+ description = data.get("description")
668
+ start_step_id = data["start_step_id"]
669
+
670
+ steps = {}
671
+ steps_data = data.get("steps", {})
672
+
673
+ for step_id, step_info in steps_data.items():
674
+ step_type = step_info.get("step_type", "passthrough")
675
+ step_name = step_info.get("name", step_id)
676
+
677
+ if step_type_registry is not None and step_type in step_type_registry:
678
+ factory = step_type_registry[step_type]
679
+ step = factory(step_id=step_id, step_info=step_info)
680
+ else:
681
+ step = _PassthroughStep(
682
+ step_id=step_id,
683
+ name=step_name,
684
+ step_type=step_type,
685
+ step_data=step_info,
686
+ input_schema=step_info.get("input_schema"),
687
+ output_schema=step_info.get("output_schema"),
688
+ tags=step_info.get("tags")
689
+ )
690
+
691
+ steps[step_id] = step
692
+
693
+ edges = []
694
+ edges_data = data.get("edges", [])
695
+
696
+ for edge_info in edges_data:
697
+ edge = WorkflowEdge(
698
+ source_step_id=edge_info["source_step_id"],
699
+ target_step_id=edge_info["target_step_id"],
700
+ condition=edge_info.get("condition"),
701
+ priority=edge_info.get("priority", 0)
702
+ )
703
+ edges.append(edge)
704
+
705
+ parallel_branches = []
706
+ branches_data = data.get("parallel_branches", [])
707
+
708
+ for branch_info in branches_data:
709
+ branch = ParallelBranch(
710
+ fork_step_id=branch_info["fork_step_id"],
711
+ join_step_id=branch_info["join_step_id"]
712
+ )
713
+ parallel_branches.append(branch)
714
+
715
+ rtnval = cls(
716
+ name=name,
717
+ version=version,
718
+ steps=steps,
719
+ edges=edges,
720
+ start_step_id=start_step_id,
721
+ parallel_branches=parallel_branches,
722
+ description=description
723
+ )
724
+
725
+ return rtnval
726
+
727
+ @classmethod
728
+ def from_json(cls, json_str: str,
729
+ step_type_registry: Optional[dict] = None) -> "WorkflowDefinition":
730
+ """
731
+ Deserializes a JSON string into a WorkflowDefinition
732
+ instance.
733
+
734
+ :param json_str: A JSON string containing the workflow
735
+ definition fields.
736
+ :param step_type_registry: An optional dictionary mapping
737
+ step type strings to WorkflowStep subclass factories.
738
+
739
+ :returns: A WorkflowDefinition instance.
740
+ """
741
+ data = json.loads(json_str)
742
+ rtnval = cls.from_dict(data, step_type_registry=step_type_registry)
743
+ return rtnval
744
+
745
+ @classmethod
746
+ def from_yaml(cls, yaml_str: str,
747
+ step_type_registry: Optional[dict] = None) -> "WorkflowDefinition":
748
+ """
749
+ Deserializes a YAML string into a WorkflowDefinition
750
+ instance.
751
+
752
+ :param yaml_str: A YAML string containing the workflow
753
+ definition fields.
754
+ :param step_type_registry: An optional dictionary mapping
755
+ step type strings to WorkflowStep subclass factories.
756
+
757
+ :returns: A WorkflowDefinition instance.
758
+ """
759
+ data = yaml.safe_load(yaml_str)
760
+ rtnval = cls.from_dict(data, step_type_registry=step_type_registry)
761
+ return rtnval
762
+
763
+ def __repr__(self) -> str:
764
+ """
765
+ Returns a detailed string representation including the
766
+ class name, workflow name, version, and step count.
767
+
768
+ :returns: A repr string for debugging.
769
+ """
770
+ step_count = len(self._steps)
771
+ repr_str = "{}(name={!r}, version={!r}, steps={})".format(
772
+ self.__class__.__name__, self._name, self._version,
773
+ step_count
774
+ )
775
+ return repr_str
776
+
777
+ def __str__(self) -> str:
778
+ """
779
+ Returns a human-readable summary including the workflow
780
+ name, version, step count, and edge count.
781
+
782
+ :returns: A human-readable string describing the workflow
783
+ definition.
784
+ """
785
+ step_count = len(self._steps)
786
+ edge_count = len(self._edges)
787
+ str_val = "WorkflowDefinition: {} v{} [{} steps, {} edges]".format(
788
+ self._name, self._version, step_count, edge_count
789
+ )
790
+ return str_val