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,238 @@
1
+ """
2
+ Defines the ApprovalGate class responsible for managing the
3
+ lifecycle of approval requests within workflow execution in
4
+ the Workflow & Orchestration feature.
5
+
6
+ The ApprovalGate creates, approves, rejects, and lists pending
7
+ ApprovalRequest objects. It supports registration of handler
8
+ callbacks that are invoked when new approval requests are
9
+ created. All approval events are logged under the
10
+ ``ccai.agentkit.workflow.approval`` logger hierarchy.
11
+ """
12
+
13
+ import logging
14
+
15
+ from ccai.agentkit.approvalrequest import ApprovalRequest
16
+
17
+
18
+ class ApprovalGate:
19
+ """
20
+ Manages the lifecycle of approval requests within workflow
21
+ execution.
22
+
23
+ The ApprovalGate maintains a dictionary of pending
24
+ ApprovalRequest objects keyed by request identifier and a
25
+ list of registered handler callbacks. When a new request
26
+ is created, all registered handlers are invoked with the
27
+ request. Approval and rejection operations resolve pending
28
+ requests by creating new ApprovalRequest instances with
29
+ the updated status.
30
+
31
+ Approval events are logged under the
32
+ ``ccai.agentkit.workflow.approval`` logger.
33
+ """
34
+
35
+ def __init__(self) -> None:
36
+ self._pending_requests = {}
37
+ self._handlers = []
38
+ self._logger = logging.getLogger("ccai.agentkit.workflow.approval")
39
+ return
40
+
41
+ def create_request(self, execution_id: str, step_id: str,
42
+ description: str,
43
+ requesting_agent_id: str) -> ApprovalRequest:
44
+ """
45
+ Creates a pending ApprovalRequest and invokes all
46
+ registered handlers.
47
+
48
+ A new ApprovalRequest is created with status "pending"
49
+ and stored in the internal pending requests dictionary.
50
+ All registered handler callbacks are then invoked with
51
+ the new request.
52
+
53
+ :param execution_id: The unique identifier of the
54
+ workflow execution.
55
+ :param step_id: The identifier of the workflow step
56
+ that requires approval.
57
+ :param description: A human-readable description of
58
+ what is being approved.
59
+ :param requesting_agent_id: The identifier of the
60
+ agent requesting approval.
61
+
62
+ :returns: The newly created ApprovalRequest instance.
63
+ """
64
+ request = ApprovalRequest(
65
+ execution_id=execution_id,
66
+ step_id=step_id,
67
+ description=description,
68
+ requesting_agent_id=requesting_agent_id,
69
+ status="pending"
70
+ )
71
+
72
+ self._pending_requests[request.identifier] = request
73
+
74
+ self._logger.info(
75
+ "ApprovalRequest created: id=%s, execution=%s, "
76
+ "step=%s, description='%s'.",
77
+ request.identifier, execution_id, step_id, description
78
+ )
79
+
80
+ for handler in self._handlers:
81
+ handler(request)
82
+
83
+ rtnval = request
84
+ return rtnval
85
+
86
+ def approve(self, request_id: str, metadata: dict = None) -> None:
87
+ """
88
+ Resolves a pending approval as approved.
89
+
90
+ Removes the pending request and replaces it with a new
91
+ ApprovalRequest instance that has status "approved" and
92
+ the provided metadata merged in.
93
+
94
+ :param request_id: The unique identifier of the
95
+ approval request to approve.
96
+ :param metadata: An optional dictionary of approval
97
+ metadata to attach to the resolved request.
98
+ """
99
+ if request_id not in self._pending_requests:
100
+ return
101
+
102
+ original = self._pending_requests.pop(request_id)
103
+
104
+ merged_metadata = dict(original.metadata)
105
+ if metadata is not None:
106
+ merged_metadata.update(metadata)
107
+
108
+ resolved = ApprovalRequest(
109
+ identifier=original.identifier,
110
+ execution_id=original.execution_id,
111
+ step_id=original.step_id,
112
+ description=original.description,
113
+ requesting_agent_id=original.requesting_agent_id,
114
+ status="approved",
115
+ metadata=merged_metadata,
116
+ rejection_reason=None,
117
+ timestamp=original.timestamp
118
+ )
119
+
120
+ self._pending_requests[request_id] = resolved
121
+
122
+ self._logger.info(
123
+ "ApprovalRequest approved: id=%s, metadata=%r.",
124
+ request_id, metadata
125
+ )
126
+
127
+ return
128
+
129
+ def reject(self, request_id: str, reason: str) -> None:
130
+ """
131
+ Resolves a pending approval as rejected.
132
+
133
+ Removes the pending request and replaces it with a new
134
+ ApprovalRequest instance that has status "rejected" and
135
+ the provided rejection reason.
136
+
137
+ :param request_id: The unique identifier of the
138
+ approval request to reject.
139
+ :param reason: A string describing the reason for
140
+ rejection.
141
+ """
142
+ if request_id not in self._pending_requests:
143
+ return
144
+
145
+ original = self._pending_requests.pop(request_id)
146
+
147
+ resolved = ApprovalRequest(
148
+ identifier=original.identifier,
149
+ execution_id=original.execution_id,
150
+ step_id=original.step_id,
151
+ description=original.description,
152
+ requesting_agent_id=original.requesting_agent_id,
153
+ status="rejected",
154
+ metadata=original.metadata,
155
+ rejection_reason=reason,
156
+ timestamp=original.timestamp
157
+ )
158
+
159
+ self._pending_requests[request_id] = resolved
160
+
161
+ self._logger.warning(
162
+ "ApprovalRequest rejected: id=%s, reason='%s'.",
163
+ request_id, reason
164
+ )
165
+
166
+ return
167
+
168
+ def list_pending(self) -> list:
169
+ """
170
+ Returns all ApprovalRequest objects with status
171
+ "pending".
172
+
173
+ :returns: A list of ApprovalRequest instances that
174
+ have status "pending".
175
+ """
176
+ rtnval = [
177
+ req for req in self._pending_requests.values()
178
+ if req.status == "pending"
179
+ ]
180
+ return rtnval
181
+
182
+ def register_handler(self, handler: callable) -> None:
183
+ """
184
+ Registers an ApprovalHandler callback that is invoked
185
+ when a new ApprovalRequest is created.
186
+
187
+ :param handler: A callable that accepts an
188
+ ApprovalRequest as its single argument.
189
+ """
190
+ if handler not in self._handlers:
191
+ self._handlers.append(handler)
192
+ return
193
+
194
+ def deregister_handler(self, handler: callable) -> None:
195
+ """
196
+ Removes a previously registered ApprovalHandler
197
+ callback.
198
+
199
+ :param handler: The handler callable to remove.
200
+ """
201
+ if handler in self._handlers:
202
+ self._handlers.remove(handler)
203
+ return
204
+
205
+ @property
206
+ def pending_count(self) -> int:
207
+ """
208
+ The count of approval requests with status "pending".
209
+
210
+ :returns: An integer count of pending requests.
211
+ """
212
+ rtnval = len(self.list_pending())
213
+ return rtnval
214
+
215
+ def __repr__(self) -> str:
216
+ """
217
+ Returns a detailed string representation including the
218
+ class name and the count of pending approvals.
219
+
220
+ :returns: A repr string for debugging.
221
+ """
222
+ repr_str = "{}(pending_count={})".format(
223
+ self.__class__.__name__, self.pending_count
224
+ )
225
+ return repr_str
226
+
227
+ def __str__(self) -> str:
228
+ """
229
+ Returns a human-readable summary including the count
230
+ of pending approvals.
231
+
232
+ :returns: A human-readable string describing the
233
+ approval gate.
234
+ """
235
+ str_val = "ApprovalGate: {} pending approval(s)".format(
236
+ self.pending_count
237
+ )
238
+ return str_val
@@ -0,0 +1,250 @@
1
+ """
2
+ Defines the ApprovalRequest class representing an immutable
3
+ pending approval within a workflow in the Workflow &
4
+ Orchestration feature.
5
+
6
+ An ApprovalRequest contains a unique identifier, the workflow
7
+ execution identifier, the step identifier, a description of
8
+ what is being approved, the requesting agent identifier, the
9
+ approval status, optional metadata, an optional rejection
10
+ reason, and a UTC timestamp. The class provides JSON
11
+ serialization and deserialization for persistence and
12
+ reconstruction.
13
+ """
14
+
15
+ import json
16
+ import uuid
17
+
18
+ from datetime import datetime, timezone
19
+ from typing import Optional
20
+
21
+
22
+ class ApprovalRequest:
23
+ """
24
+ Immutable object representing a pending approval within a
25
+ workflow.
26
+
27
+ An ApprovalRequest captures the details of an approval
28
+ that must be resolved before a workflow can continue. All
29
+ fields are exposed as read-only properties. The identifier
30
+ defaults to an auto-generated UUID and the timestamp
31
+ defaults to the current UTC time when not provided.
32
+
33
+ :param identifier: An optional unique identifier for the
34
+ request. Defaults to an auto-generated UUID string.
35
+ :param execution_id: The unique identifier of the workflow
36
+ execution that created this request.
37
+ :param step_id: The identifier of the workflow step that
38
+ requires approval.
39
+ :param description: A human-readable description of what
40
+ is being approved.
41
+ :param requesting_agent_id: The identifier of the agent
42
+ that requested the approval.
43
+ :param status: The approval status string. Must be one of
44
+ the VALID_STATUSES values. Defaults to "pending".
45
+ :param metadata: An optional dictionary of approval
46
+ metadata. Defaults to an empty dictionary.
47
+ :param rejection_reason: An optional string describing
48
+ the reason for rejection.
49
+ :param timestamp: An optional UTC datetime for the
50
+ request. Defaults to the current UTC time.
51
+ """
52
+
53
+ VALID_STATUSES = {"pending", "approved", "rejected", "expired"}
54
+
55
+ def __init__(self, execution_id: str, step_id: str,
56
+ description: str, requesting_agent_id: str,
57
+ identifier: Optional[str] = None,
58
+ status: str = "pending",
59
+ metadata: Optional[dict] = None,
60
+ rejection_reason: Optional[str] = None,
61
+ timestamp: Optional[datetime] = None) -> None:
62
+ self._identifier = identifier if identifier is not None else str(uuid.uuid4())
63
+ self._execution_id = execution_id
64
+ self._step_id = step_id
65
+ self._description = description
66
+ self._requesting_agent_id = requesting_agent_id
67
+ self._status = status
68
+ self._metadata = dict(metadata) if metadata is not None else {}
69
+ self._rejection_reason = rejection_reason
70
+ self._timestamp = timestamp if timestamp is not None else datetime.now(timezone.utc)
71
+ return
72
+
73
+ @property
74
+ def identifier(self) -> str:
75
+ """
76
+ The unique identifier for this approval request.
77
+
78
+ :returns: The identifier string.
79
+ """
80
+ return self._identifier
81
+
82
+ @property
83
+ def execution_id(self) -> str:
84
+ """
85
+ The unique identifier of the workflow execution that
86
+ created this request.
87
+
88
+ :returns: The execution identifier string.
89
+ """
90
+ return self._execution_id
91
+
92
+ @property
93
+ def step_id(self) -> str:
94
+ """
95
+ The identifier of the workflow step that requires
96
+ approval.
97
+
98
+ :returns: The step identifier string.
99
+ """
100
+ return self._step_id
101
+
102
+ @property
103
+ def description(self) -> str:
104
+ """
105
+ A human-readable description of what is being approved.
106
+
107
+ :returns: The description string.
108
+ """
109
+ return self._description
110
+
111
+ @property
112
+ def requesting_agent_id(self) -> str:
113
+ """
114
+ The identifier of the agent that requested the approval.
115
+
116
+ :returns: The requesting agent identifier string.
117
+ """
118
+ return self._requesting_agent_id
119
+
120
+ @property
121
+ def status(self) -> str:
122
+ """
123
+ The current approval status.
124
+
125
+ :returns: A status string, one of "pending", "approved",
126
+ "rejected", or "expired".
127
+ """
128
+ return self._status
129
+
130
+ @property
131
+ def metadata(self) -> dict:
132
+ """
133
+ Optional approval metadata.
134
+
135
+ Returns a defensive copy to preserve immutability.
136
+
137
+ :returns: A dictionary of metadata.
138
+ """
139
+ rtnval = dict(self._metadata)
140
+ return rtnval
141
+
142
+ @property
143
+ def rejection_reason(self) -> Optional[str]:
144
+ """
145
+ The reason for rejection, or None when the request
146
+ has not been rejected.
147
+
148
+ :returns: The rejection reason string or None.
149
+ """
150
+ return self._rejection_reason
151
+
152
+ @property
153
+ def timestamp(self) -> datetime:
154
+ """
155
+ The UTC timestamp when the request was created.
156
+
157
+ :returns: A datetime object in UTC.
158
+ """
159
+ return self._timestamp
160
+
161
+ def as_dict(self) -> dict:
162
+ """
163
+ Returns a dictionary representation of the approval
164
+ request fields.
165
+
166
+ The timestamp is serialized as an ISO format string.
167
+
168
+ :returns: A dictionary containing all request fields.
169
+ """
170
+ rtnval = {
171
+ "identifier": self._identifier,
172
+ "execution_id": self._execution_id,
173
+ "step_id": self._step_id,
174
+ "description": self._description,
175
+ "requesting_agent_id": self._requesting_agent_id,
176
+ "status": self._status,
177
+ "metadata": dict(self._metadata),
178
+ "rejection_reason": self._rejection_reason,
179
+ "timestamp": self._timestamp.isoformat()
180
+ }
181
+ return rtnval
182
+
183
+ def to_json(self) -> str:
184
+ """
185
+ Returns a JSON string representation of the approval
186
+ request fields.
187
+
188
+ :returns: A JSON string containing all request fields.
189
+ """
190
+ data = self.as_dict()
191
+ rtnval = json.dumps(data)
192
+ return rtnval
193
+
194
+ @classmethod
195
+ def from_json(cls, json_str: str) -> "ApprovalRequest":
196
+ """
197
+ Deserializes a JSON string into an ApprovalRequest
198
+ instance.
199
+
200
+ The timestamp is parsed from an ISO format string.
201
+
202
+ :param json_str: A JSON string containing approval
203
+ request fields.
204
+
205
+ :returns: An ApprovalRequest instance reconstructed
206
+ from the JSON data.
207
+ """
208
+ data = json.loads(json_str)
209
+
210
+ timestamp = datetime.fromisoformat(data["timestamp"])
211
+
212
+ rtnval = cls(
213
+ identifier=data["identifier"],
214
+ execution_id=data["execution_id"],
215
+ step_id=data["step_id"],
216
+ description=data["description"],
217
+ requesting_agent_id=data["requesting_agent_id"],
218
+ status=data["status"],
219
+ metadata=data.get("metadata"),
220
+ rejection_reason=data.get("rejection_reason"),
221
+ timestamp=timestamp
222
+ )
223
+ return rtnval
224
+
225
+ def __repr__(self) -> str:
226
+ """
227
+ Returns a detailed string representation including the
228
+ class name, identifier, step identifier, and approval
229
+ status.
230
+
231
+ :returns: A repr string for debugging.
232
+ """
233
+ repr_str = "{}(identifier={!r}, step_id={!r}, status={!r})".format(
234
+ self.__class__.__name__, self._identifier,
235
+ self._step_id, self._status
236
+ )
237
+ return repr_str
238
+
239
+ def __str__(self) -> str:
240
+ """
241
+ Returns a human-readable summary including the
242
+ identifier, description, and approval status.
243
+
244
+ :returns: A human-readable string describing the
245
+ approval request.
246
+ """
247
+ str_val = "ApprovalRequest: {} [{}] status={}".format(
248
+ self._identifier, self._description, self._status
249
+ )
250
+ return str_val
@@ -0,0 +1,187 @@
1
+ """
2
+ Defines the AsyncAgent abstract base class for agents that run
3
+ their lifecycle methods as async coroutines on an asyncio event loop
4
+ in the codecraftai-agent-kit framework.
5
+
6
+ AsyncAgent extends Agent and provides async versions of all lifecycle
7
+ methods. Subclasses override the async_* methods to implement their
8
+ async behavior. The synchronous lifecycle methods delegate to the
9
+ async versions using the event loop.
10
+ """
11
+
12
+ import abc
13
+ import asyncio
14
+
15
+ from typing import Optional
16
+
17
+ from ccai.agentkit.agent import Agent
18
+ from ccai.agentkit.agentconfiguration import AgentConfiguration
19
+ from ccai.agentkit.concurrencymodel import ConcurrencyModel
20
+ from ccai.agentkit.lifecyclestate import LifecycleState
21
+ from ccai.agentkit.transitionrecord import TransitionRecord
22
+
23
+
24
+ class AsyncAgent(Agent):
25
+ """
26
+ Abstract base class for agents that run lifecycle methods as
27
+ async coroutines on an asyncio event loop.
28
+
29
+ Subclasses must implement the async lifecycle methods:
30
+ async_initialize, async_start, async_pause, async_resume,
31
+ async_stop, and async_reset.
32
+
33
+ The synchronous lifecycle methods (initialize, start, etc.)
34
+ delegate to the async versions by running them on the event loop.
35
+
36
+ :param configuration: The AgentConfiguration for this agent.
37
+ """
38
+
39
+ def __init__(self, configuration: AgentConfiguration) -> None:
40
+ super().__init__(configuration)
41
+ self._concurrency_model: ConcurrencyModel = ConcurrencyModel.ASYNCIO
42
+ return
43
+
44
+ @property
45
+ def concurrency_model(self) -> ConcurrencyModel:
46
+ """
47
+ The concurrency model used by this agent.
48
+
49
+ :returns: ConcurrencyModel.ASYNCIO
50
+ """
51
+ return self._concurrency_model
52
+
53
+ # -----------------------------------------------------------------------
54
+ # Async lifecycle transition helper
55
+ # -----------------------------------------------------------------------
56
+
57
+ async def _async_perform_transition(self, target_state: LifecycleState,
58
+ transition_point: str,
59
+ metadata: Optional[dict] = None) -> TransitionRecord:
60
+ """
61
+ Performs a lifecycle state transition in an async context.
62
+
63
+ Delegates to the synchronous _perform_transition method from
64
+ the Agent base class.
65
+
66
+ :param target_state: The target LifecycleState.
67
+ :param transition_point: The hook transition point to invoke.
68
+ :param metadata: Optional metadata for the transition.
69
+
70
+ :returns: The TransitionRecord for the transition.
71
+ """
72
+ record = self._perform_transition(target_state, transition_point, metadata=metadata)
73
+ return record
74
+
75
+ # -----------------------------------------------------------------------
76
+ # Synchronous lifecycle methods (delegate to async versions)
77
+ # -----------------------------------------------------------------------
78
+
79
+ def initialize(self) -> None:
80
+ """
81
+ Initializes the agent by running the async_initialize coroutine.
82
+ """
83
+ self._run_async(self.async_initialize())
84
+ return
85
+
86
+ def start(self) -> None:
87
+ """
88
+ Starts the agent by running the async_start coroutine.
89
+ """
90
+ self._run_async(self.async_start())
91
+ return
92
+
93
+ def pause(self) -> None:
94
+ """
95
+ Pauses the agent by running the async_pause coroutine.
96
+ """
97
+ self._run_async(self.async_pause())
98
+ return
99
+
100
+ def resume(self) -> None:
101
+ """
102
+ Resumes the agent by running the async_resume coroutine.
103
+ """
104
+ self._run_async(self.async_resume())
105
+ return
106
+
107
+ def stop(self) -> None:
108
+ """
109
+ Stops the agent by running the async_stop coroutine.
110
+ """
111
+ self._run_async(self.async_stop())
112
+ return
113
+
114
+ def reset(self) -> None:
115
+ """
116
+ Resets the agent by running the async_reset coroutine.
117
+ """
118
+ self._run_async(self.async_reset())
119
+ return
120
+
121
+ # -----------------------------------------------------------------------
122
+ # Async lifecycle methods (to be overridden by subclasses)
123
+ # -----------------------------------------------------------------------
124
+
125
+ @abc.abstractmethod
126
+ async def async_initialize(self) -> None:
127
+ """
128
+ Async initialization of the agent. Subclasses must implement this method.
129
+ """
130
+
131
+ @abc.abstractmethod
132
+ async def async_start(self) -> None:
133
+ """
134
+ Async start of the agent. Subclasses must implement this method.
135
+ """
136
+
137
+ @abc.abstractmethod
138
+ async def async_pause(self) -> None:
139
+ """
140
+ Async pause of the agent. Subclasses must implement this method.
141
+ """
142
+
143
+ @abc.abstractmethod
144
+ async def async_resume(self) -> None:
145
+ """
146
+ Async resume of the agent. Subclasses must implement this method.
147
+ """
148
+
149
+ @abc.abstractmethod
150
+ async def async_stop(self) -> None:
151
+ """
152
+ Async stop of the agent. Subclasses must implement this method.
153
+ """
154
+
155
+ @abc.abstractmethod
156
+ async def async_reset(self) -> None:
157
+ """
158
+ Async reset of the agent. Subclasses must implement this method.
159
+ """
160
+
161
+ # -----------------------------------------------------------------------
162
+ # Internal helper
163
+ # -----------------------------------------------------------------------
164
+
165
+ def _run_async(self, coroutine: object) -> None:
166
+ """
167
+ Runs an async coroutine, handling both cases where an event loop
168
+ is already running and where one needs to be created.
169
+
170
+ :param coroutine: The coroutine to run.
171
+ """
172
+ try:
173
+ loop = asyncio.get_running_loop()
174
+ except RuntimeError:
175
+ loop = None
176
+
177
+ if loop is not None and loop.is_running():
178
+ # We are inside a running event loop; create a task
179
+ # The caller must await this or use the event loop to complete it
180
+ asyncio.ensure_future(coroutine)
181
+ # If we are in a sync context within an async loop, we cannot block.
182
+ # This path is for when the sync method is called from async code.
183
+ return
184
+ else:
185
+ asyncio.run(coroutine)
186
+
187
+ return