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,311 @@
1
+ """
2
+ Defines the PubSubBroker class for managing topic-based publish/subscribe
3
+ messaging with wildcard support.
4
+
5
+ PubSubBroker maintains a list of Subscription objects and routes
6
+ published messages to all subscribers whose topic pattern matches
7
+ the publish topic. Wildcard topic matching follows MQTT/AMQP
8
+ conventions: '*' matches exactly one segment, '#' matches zero or
9
+ more segments, and '.' is the segment separator.
10
+
11
+ Subscriber handlers are invoked in registration order. If a handler
12
+ raises an exception, the exception is logged at WARNING level and
13
+ delivery continues to remaining subscribers.
14
+
15
+ .. module:: ccai.agentkit.pubsubbroker
16
+ :platform: Darwin, Linux, Unix, Windows
17
+ :synopsis: Topic-based pub/sub messaging with wildcard support.
18
+
19
+ Requirements: 14.1-14.12, 26.15, 26.16
20
+ """
21
+
22
+ import logging
23
+
24
+ from typing import Callable
25
+ from typing import List
26
+ from typing import Optional
27
+
28
+ from ccai.agentkit.message import Message
29
+ from ccai.agentkit.subscription import Subscription
30
+
31
+
32
+ SINGLE_LEVEL_WILDCARD = "*"
33
+ MULTI_LEVEL_WILDCARD = "#"
34
+ TOPIC_SEPARATOR = "."
35
+
36
+
37
+ class PubSubBroker:
38
+ """
39
+ Manages topic-based publish/subscribe messaging with wildcard support.
40
+
41
+ Maintains an ordered list of Subscription objects. When a message
42
+ is published to a topic, the broker invokes the handler of each
43
+ subscription whose topic pattern matches the publish topic, in
44
+ registration order.
45
+
46
+ Wildcard topic matching rules:
47
+ - '.' is the segment separator
48
+ - '*' matches exactly one segment
49
+ - '#' matches zero or more segments
50
+
51
+ If a subscriber handler raises an exception during invocation,
52
+ the exception is logged at WARNING level and delivery continues
53
+ to the remaining subscribers.
54
+ """
55
+
56
+ def __init__(self) -> None:
57
+ self._subscriptions: List[Subscription] = []
58
+ self._logger = logging.getLogger("ccai.agentkit.messaging.pubsub")
59
+ return
60
+
61
+ def subscribe(self, topic: str, subscriber_agent_id: str,
62
+ handler: Callable, message_filter: Optional[Callable] = None) -> Subscription:
63
+ """
64
+ Creates a subscription for a topic.
65
+
66
+ Constructs a Subscription object and appends it to the
67
+ internal subscription list. Logs the subscription creation
68
+ at INFO level.
69
+
70
+ :param topic: The topic string (supports wildcard patterns).
71
+ :param subscriber_agent_id: The subscriber agent identifier.
72
+ :param handler: The MessageHandler callback.
73
+ :param message_filter: Optional filter callable for additional
74
+ message filtering.
75
+
76
+ :returns: A Subscription object.
77
+ """
78
+ subscription = Subscription(
79
+ subscriber_agent_id=subscriber_agent_id,
80
+ topic=topic,
81
+ handler=handler,
82
+ message_filter=message_filter,
83
+ )
84
+
85
+ self._subscriptions.append(subscription)
86
+
87
+ self._logger.info(
88
+ "Subscription created: topic='%s', subscriber='%s'",
89
+ topic, subscriber_agent_id
90
+ )
91
+
92
+ return subscription
93
+
94
+ def unsubscribe(self, subscription: Subscription) -> None:
95
+ """
96
+ Removes a subscription.
97
+
98
+ Removes the subscription from the internal list by matching
99
+ the subscription identifier. If the subscription is not found,
100
+ the operation is a no-op. Logs the removal at INFO level.
101
+
102
+ :param subscription: The Subscription to remove.
103
+ """
104
+ updated_subscriptions = []
105
+
106
+ for existing in self._subscriptions:
107
+ is_target = existing.identifier == subscription.identifier
108
+
109
+ if is_target is not True:
110
+ updated_subscriptions.append(existing)
111
+
112
+ self._subscriptions = updated_subscriptions
113
+
114
+ self._logger.info(
115
+ "Subscription removed: topic='%s', subscriber='%s'",
116
+ subscription.topic, subscription.subscriber_agent_id
117
+ )
118
+
119
+ return
120
+
121
+ def publish(self, topic: str, message: Message) -> None:
122
+ """
123
+ Publishes a message to all subscribers whose topic pattern matches.
124
+
125
+ Iterates through all subscriptions in registration order and
126
+ invokes the handler of each subscription whose topic pattern
127
+ matches the publish topic. If a handler raises an exception,
128
+ the exception is logged at WARNING level and delivery continues
129
+ to the remaining subscribers.
130
+
131
+ :param topic: The topic string.
132
+ :param message: The Message to publish.
133
+ """
134
+ matched_count = 0
135
+
136
+ for subscription in self._subscriptions:
137
+ is_match = self.topic_matches(subscription.topic, topic)
138
+
139
+ if is_match is True:
140
+ if subscription.message_filter is not None:
141
+ try:
142
+ filter_result = subscription.message_filter(message)
143
+ except Exception:
144
+ filter_result = False
145
+
146
+ if filter_result is not True:
147
+ continue
148
+
149
+ matched_count = matched_count + 1
150
+ handler = subscription.handler
151
+
152
+ try:
153
+ handler(message)
154
+ except Exception as exc:
155
+ self._logger.warning(
156
+ "Handler exception: topic='%s', subscriber='%s', "
157
+ "message='%s': %s",
158
+ topic, subscription.subscriber_agent_id,
159
+ message.identifier, exc
160
+ )
161
+
162
+ self._logger.info(
163
+ "Message published: topic='%s', message='%s', subscriber_count=%d",
164
+ topic, message.identifier, matched_count
165
+ )
166
+
167
+ return
168
+
169
+ def topic_matches(self, subscription_topic: str, publish_topic: str) -> bool:
170
+ """
171
+ Checks if a subscription topic pattern matches a publish topic.
172
+
173
+ Supports wildcard matching following MQTT/AMQP conventions:
174
+ - '.' is the segment separator
175
+ - '*' matches exactly one segment
176
+ - '#' matches zero or more segments
177
+
178
+ :param subscription_topic: The subscription topic pattern.
179
+ :param publish_topic: The actual publish topic.
180
+
181
+ :returns: True if the pattern matches, False otherwise.
182
+ """
183
+ sub_segments = subscription_topic.split(TOPIC_SEPARATOR)
184
+ pub_segments = publish_topic.split(TOPIC_SEPARATOR)
185
+
186
+ return self._match_segments(sub_segments, 0, pub_segments, 0)
187
+
188
+ def _match_segments(self, sub_segments: list, sub_index: int,
189
+ pub_segments: list, pub_index: int) -> bool:
190
+ """
191
+ Recursively matches subscription topic segments against
192
+ publish topic segments with wildcard support.
193
+
194
+ :param sub_segments: The subscription topic segments.
195
+ :param sub_index: The current index in subscription segments.
196
+ :param pub_segments: The publish topic segments.
197
+ :param pub_index: The current index in publish segments.
198
+
199
+ :returns: True if the segments match, False otherwise.
200
+ """
201
+ sub_len = len(sub_segments)
202
+ pub_len = len(pub_segments)
203
+
204
+ while sub_index < sub_len:
205
+ current_sub = sub_segments[sub_index]
206
+
207
+ if current_sub == MULTI_LEVEL_WILDCARD:
208
+ # '#' must be the last segment in the subscription pattern
209
+ # It matches zero or more remaining segments
210
+ return True
211
+
212
+ if pub_index >= pub_len:
213
+ # No more publish segments to match against
214
+ return False
215
+
216
+ if current_sub == SINGLE_LEVEL_WILDCARD:
217
+ # '*' matches exactly one segment
218
+ sub_index = sub_index + 1
219
+ pub_index = pub_index + 1
220
+ continue
221
+
222
+ # Exact segment match required
223
+ current_pub = pub_segments[pub_index]
224
+ if current_sub != current_pub:
225
+ return False
226
+
227
+ sub_index = sub_index + 1
228
+ pub_index = pub_index + 1
229
+
230
+ # All subscription segments consumed; check if all publish segments consumed
231
+ is_complete = pub_index >= pub_len
232
+ return is_complete
233
+
234
+ @property
235
+ def active_topics(self) -> list:
236
+ """
237
+ Returns a list of unique topic strings from active subscriptions.
238
+
239
+ :returns: A list of unique topic strings.
240
+ """
241
+ topics = []
242
+
243
+ for subscription in self._subscriptions:
244
+ topic = subscription.topic
245
+ is_duplicate = topic in topics
246
+
247
+ if is_duplicate is not True:
248
+ topics.append(topic)
249
+
250
+ return topics
251
+
252
+ def get_subscriber_count(self, topic: str) -> int:
253
+ """
254
+ Returns the count of subscribers for an exact topic match.
255
+
256
+ :param topic: The topic string to count subscribers for.
257
+
258
+ :returns: The count of subscribers with the exact topic.
259
+ """
260
+ count = 0
261
+
262
+ for subscription in self._subscriptions:
263
+ if subscription.topic == topic:
264
+ count = count + 1
265
+
266
+ return count
267
+
268
+ def get_subscriber_ids(self, topic: str) -> list:
269
+ """
270
+ Returns a list of subscriber agent identifiers for an exact
271
+ topic match.
272
+
273
+ :param topic: The topic string to get subscriber IDs for.
274
+
275
+ :returns: A list of subscriber agent identifier strings.
276
+ """
277
+ subscriber_ids = []
278
+
279
+ for subscription in self._subscriptions:
280
+ if subscription.topic == topic:
281
+ subscriber_ids.append(subscription.subscriber_agent_id)
282
+
283
+ return subscriber_ids
284
+
285
+ def __repr__(self) -> str:
286
+ """
287
+ Returns a detailed string representation including the class
288
+ name and the count of active topics.
289
+
290
+ :returns: A repr string for debugging.
291
+ """
292
+ topic_count = len(self.active_topics)
293
+ repr_str = "{}(active_topics={})".format(
294
+ self.__class__.__name__, topic_count
295
+ )
296
+ return repr_str
297
+
298
+ def __str__(self) -> str:
299
+ """
300
+ Returns a human-readable summary including the count of
301
+ active topics and total subscription count.
302
+
303
+ :returns: A human-readable string describing the broker state.
304
+ """
305
+ topic_count = len(self.active_topics)
306
+ subscription_count = len(self._subscriptions)
307
+
308
+ str_val = "PubSubBroker: {} active topic(s), {} subscription(s)".format(
309
+ topic_count, subscription_count
310
+ )
311
+ return str_val
ccai/agentkit/py.typed ADDED
File without changes
@@ -0,0 +1,47 @@
1
+ """
2
+ Defines the ReconnectTransportAction for reconnecting a Transport instance.
3
+ """
4
+
5
+ from ccai.agentkit.healthstatus import HealthStatus
6
+ from ccai.agentkit.selfhealingaction import SelfHealingAction
7
+ from ccai.agentkit.selfhealingresult import SelfHealingResult
8
+
9
+
10
+ class ReconnectTransportAction(SelfHealingAction):
11
+ """
12
+ Attempts to disconnect and reconnect a Transport instance.
13
+
14
+ :param transport: The transport instance to reconnect.
15
+ """
16
+
17
+ def __init__(self, transport) -> None:
18
+ super().__init__(action_name="reconnect_transport")
19
+ self._transport = transport
20
+ return
21
+
22
+ def heal(self, check_name: str, status: HealthStatus) -> SelfHealingResult:
23
+ """
24
+ Disconnects and reconnects the transport.
25
+
26
+ :param check_name: Name of the health check that triggered healing.
27
+ :param status: The HealthStatus that triggered the action.
28
+
29
+ :returns: A SelfHealingResult indicating success or failure.
30
+ """
31
+ try:
32
+ self._transport.disconnect()
33
+ self._transport.connect()
34
+ result = SelfHealingResult(
35
+ check_name=check_name,
36
+ action_name=self._action_name,
37
+ success=True
38
+ )
39
+ return result
40
+ except Exception as exc:
41
+ result = SelfHealingResult(
42
+ check_name=check_name,
43
+ action_name=self._action_name,
44
+ success=False,
45
+ error_message=str(exc)
46
+ )
47
+ return result
@@ -0,0 +1,68 @@
1
+ """
2
+ Defines the RegexOutputParser class for extracting structured data
3
+ from LLM response text using regular expressions.
4
+
5
+ RegexOutputParser extends OutputParser to handle regex-based extraction
6
+ of named capture groups from LLM responses. It compiles the pattern
7
+ at construction time and raises LLMResponseParsingError when the
8
+ pattern does not match the response text.
9
+ """
10
+
11
+ import re
12
+
13
+ from ccai.agentkit.llmerrors import LLMResponseParsingError
14
+ from ccai.agentkit.outputparser import OutputParser
15
+ from ccai.agentkit.outputschema import OutputSchema
16
+
17
+
18
+ class RegexOutputParser(OutputParser):
19
+ """
20
+ Extracts structured data from LLM response text using a regular
21
+ expression pattern with named capture groups.
22
+
23
+ The pattern is compiled at construction time. The _parse_raw method
24
+ searches the raw text for a match and returns the named group
25
+ dictionary. Optionally validates the parsed result against an
26
+ OutputSchema if one was provided at construction time.
27
+
28
+ :param pattern: A regex pattern string with named capture groups.
29
+ :param schema: Optional OutputSchema for post-parse validation.
30
+ """
31
+
32
+ def __init__(self, pattern: str, schema: OutputSchema = None) -> None:
33
+ super().__init__(schema=schema)
34
+ self._pattern = pattern
35
+ self._compiled = re.compile(pattern)
36
+ return
37
+
38
+ @property
39
+ def pattern(self) -> str:
40
+ """
41
+ The regex pattern string.
42
+
43
+ :returns: The pattern string.
44
+ """
45
+ rtnval = self._pattern
46
+ return rtnval
47
+
48
+ def _parse_raw(self, raw_text: str) -> object:
49
+ """
50
+ Matches the pattern against the raw text and returns named groups.
51
+
52
+ :param raw_text: The raw LLM response text.
53
+
54
+ :returns: A dictionary of named capture group matches.
55
+ :raises: LLMResponseParsingError if pattern does not match.
56
+ """
57
+ match = self._compiled.search(raw_text)
58
+
59
+ if match is None:
60
+ errmsg = "Regex pattern {!r} did not match the response text.".format(self._pattern)
61
+ raise LLMResponseParsingError(
62
+ parser_name=self.__class__.__name__,
63
+ raw_text=raw_text,
64
+ message=errmsg
65
+ )
66
+
67
+ rtnval = match.groupdict()
68
+ return rtnval
@@ -0,0 +1,274 @@
1
+ """
2
+ Defines the RequestResponseHandler class for managing the lifecycle
3
+ of request/response message exchanges.
4
+
5
+ The RequestResponseHandler tracks pending requests by correlation
6
+ identifier, sends request messages through a Transport, and waits
7
+ for correlated response messages. It supports configurable timeouts,
8
+ cancellation of pending requests, and multiple concurrent pending
9
+ requests using threading primitives.
10
+
11
+ When a response message arrives with a matching correlation identifier,
12
+ the handler delivers the response to the waiting caller. If no response
13
+ arrives within the timeout duration, a MessageTimeoutError is raised.
14
+
15
+ .. module:: ccai.agentkit.requestresponsehandler
16
+ :platform: Darwin, Linux, Unix, Windows
17
+ :synopsis: Correlated request/response management with timeout support.
18
+
19
+ Requirements: 12.1-12.10, 26.17, 26.18
20
+ """
21
+
22
+ import logging
23
+ import threading
24
+ import uuid
25
+
26
+ from typing import Optional
27
+
28
+ from ccai.agentkit.message import Message
29
+ from ccai.agentkit.messagingerrors import MessageTimeoutError
30
+ from ccai.agentkit.transport import Transport
31
+
32
+
33
+ class RequestResponseHandler:
34
+ """
35
+ Manages the lifecycle of request/response message exchanges
36
+ including correlation tracking, timeout management, and
37
+ response delivery.
38
+
39
+ Each outgoing request is assigned a unique correlation identifier.
40
+ The request is sent through a Transport and the caller blocks
41
+ until a correlated response is received or the timeout expires.
42
+
43
+ Pending requests are tracked in a dictionary keyed by correlation
44
+ identifier. Each entry contains a threading.Event for signaling,
45
+ a slot for the response message, and the original request message
46
+ identifier.
47
+
48
+ :param default_timeout: The default timeout in seconds for
49
+ request/response exchanges. Defaults to 30.0.
50
+ """
51
+
52
+ def __init__(self, default_timeout: float = 30.0) -> None:
53
+ self._pending_requests: dict = {}
54
+ self._default_timeout = default_timeout
55
+ self._lock = threading.Lock()
56
+ self._logger = logging.getLogger("ccai.agentkit.messaging.requestresponse")
57
+ return
58
+
59
+ def send_request(self, message: Message, transport: Transport,
60
+ timeout: Optional[float] = None) -> Message:
61
+ """
62
+ Sends a request message and waits for a correlated response.
63
+
64
+ Generates a unique correlation identifier for the request,
65
+ constructs a new Message with the correlation identifier set,
66
+ sends the message through the provided Transport, and blocks
67
+ until a correlated response is received or the timeout expires.
68
+
69
+ :param message: The request Message with MessagePattern.REQUEST.
70
+ :param transport: The Transport to send through.
71
+ :param timeout: Optional timeout in seconds. If not provided,
72
+ the default_timeout is used.
73
+
74
+ :returns: The correlated response Message.
75
+
76
+ :raises MessageTimeoutError: If no response is received within
77
+ the timeout duration.
78
+
79
+ If the transport send raises, the request is no longer tracked
80
+ as pending and the send error propagates to the caller.
81
+ """
82
+ effective_timeout = timeout if timeout is not None else self._default_timeout
83
+
84
+ correlation_id = str(uuid.uuid4())
85
+
86
+ request_message = Message(
87
+ sender=message.sender,
88
+ recipient=message.recipient,
89
+ payload=message.payload,
90
+ pattern=message.pattern,
91
+ headers=message.headers,
92
+ correlation_id=correlation_id,
93
+ identifier=message.identifier,
94
+ timestamp=message.timestamp,
95
+ serialization_format=message.serialization_format,
96
+ )
97
+
98
+ ready_event = threading.Event()
99
+
100
+ pending_entry = {
101
+ "event": ready_event,
102
+ "response": None,
103
+ "request_message_id": request_message.identifier,
104
+ "correlation_id": correlation_id,
105
+ "timeout": effective_timeout,
106
+ "cancelled": False,
107
+ }
108
+
109
+ # The request is tracked before it is sent so a reply that arrives
110
+ # while send is still returning is not lost.
111
+ with self._lock:
112
+ self._pending_requests[correlation_id] = pending_entry
113
+
114
+ send_completed = False
115
+ try:
116
+ transport.send(request_message)
117
+ send_completed = True
118
+ finally:
119
+ if send_completed is not True:
120
+ # The request never left, so no reply can come; stop tracking
121
+ # it so pending_count stays accurate.
122
+ with self._lock:
123
+ self._pending_requests.pop(correlation_id, None)
124
+
125
+ self._logger.info(
126
+ "Request sent: message_id='%s', correlation_id='%s', "
127
+ "timeout=%.1f",
128
+ request_message.identifier, correlation_id, effective_timeout
129
+ )
130
+
131
+ response_received = ready_event.wait(timeout=effective_timeout)
132
+
133
+ with self._lock:
134
+ entry = self._pending_requests.pop(correlation_id, None)
135
+
136
+ if entry is not None and entry.get("cancelled") is True:
137
+ raise MessageTimeoutError(
138
+ request_message_id=request_message.identifier,
139
+ correlation_id=correlation_id,
140
+ timeout=effective_timeout,
141
+ )
142
+
143
+ if response_received is not True:
144
+ self._logger.warning(
145
+ "Request timed out: message_id='%s', correlation_id='%s', "
146
+ "timeout=%.1f",
147
+ request_message.identifier, correlation_id, effective_timeout
148
+ )
149
+ raise MessageTimeoutError(
150
+ request_message_id=request_message.identifier,
151
+ correlation_id=correlation_id,
152
+ timeout=effective_timeout,
153
+ )
154
+
155
+ response_message = entry["response"]
156
+
157
+ self._logger.info(
158
+ "Response received: request_message_id='%s', "
159
+ "correlation_id='%s', response_message_id='%s'",
160
+ request_message.identifier, correlation_id,
161
+ response_message.identifier
162
+ )
163
+
164
+ return response_message
165
+
166
+ def handle_response(self, message: Message) -> None:
167
+ """
168
+ Delivers a response message to the waiting caller by matching
169
+ the correlation identifier.
170
+
171
+ Looks up the pending request entry by the response message's
172
+ correlation_id. If a matching entry is found, stores the
173
+ response message and signals the waiting caller via the
174
+ threading.Event.
175
+
176
+ If no matching pending request is found, the response is
177
+ silently ignored and logged at WARNING level.
178
+
179
+ :param message: The response Message with a correlation_id
180
+ matching a pending request.
181
+ """
182
+ correlation_id = message.correlation_id
183
+
184
+ with self._lock:
185
+ entry = self._pending_requests.get(correlation_id)
186
+
187
+ if entry is None:
188
+ self._logger.warning(
189
+ "No pending request for correlation_id='%s', "
190
+ "message_id='%s'",
191
+ correlation_id, message.identifier
192
+ )
193
+ return
194
+
195
+ entry["response"] = message
196
+ entry["event"].set()
197
+
198
+ self._logger.info(
199
+ "Response matched: correlation_id='%s', "
200
+ "response_message_id='%s'",
201
+ correlation_id, message.identifier
202
+ )
203
+
204
+ return
205
+
206
+ def cancel(self, correlation_id: str) -> None:
207
+ """
208
+ Cancels a pending request.
209
+
210
+ Marks the pending request entry as cancelled and signals
211
+ the waiting caller via the threading.Event. The waiting
212
+ caller will then raise a MessageTimeoutError.
213
+
214
+ If no pending request is found for the given correlation
215
+ identifier, the operation is a no-op.
216
+
217
+ :param correlation_id: The correlation identifier of the
218
+ pending request to cancel.
219
+ """
220
+ with self._lock:
221
+ entry = self._pending_requests.get(correlation_id)
222
+
223
+ if entry is None:
224
+ self._logger.warning(
225
+ "Cancel requested for unknown correlation_id='%s'",
226
+ correlation_id
227
+ )
228
+ return
229
+
230
+ entry["cancelled"] = True
231
+ entry["event"].set()
232
+
233
+ self._logger.info(
234
+ "Request cancelled: correlation_id='%s', "
235
+ "request_message_id='%s'",
236
+ correlation_id, entry["request_message_id"]
237
+ )
238
+
239
+ return
240
+
241
+ @property
242
+ def pending_count(self) -> int:
243
+ """
244
+ The count of currently pending requests.
245
+
246
+ :returns: The number of pending requests as an integer.
247
+ """
248
+ with self._lock:
249
+ count = len(self._pending_requests)
250
+ return count
251
+
252
+ def __repr__(self) -> str:
253
+ """
254
+ Returns a detailed string representation including the class
255
+ name and the count of pending requests.
256
+
257
+ :returns: A repr string for debugging.
258
+ """
259
+ repr_str = "{}(pending_count={})".format(
260
+ self.__class__.__name__, self.pending_count
261
+ )
262
+ return repr_str
263
+
264
+ def __str__(self) -> str:
265
+ """
266
+ Returns a human-readable summary including the count of
267
+ pending requests and the default timeout.
268
+
269
+ :returns: A human-readable string describing the handler state.
270
+ """
271
+ str_val = "RequestResponseHandler: {} pending request(s), default_timeout={:.1f}s".format(
272
+ self.pending_count, self._default_timeout
273
+ )
274
+ return str_val