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,305 @@
1
+ """
2
+ Defines the TraceExporter abstract base class and concrete exporter
3
+ implementations for exporting completed TraceSpan objects to external
4
+ tracing backends.
5
+
6
+ Provides two concrete exporters:
7
+ - ConsoleTraceExporter: writes completed TraceSpan objects as
8
+ formatted text to standard output
9
+ - FileTraceExporter: writes completed TraceSpan objects as JSON
10
+ lines to a specified file path, resolved relative to the
11
+ AppContext directory provided by codecraftai-this-app
12
+
13
+ All exporters accept an optional list of credential reference names
14
+ at construction time. Export failures raise ObservabilityError with
15
+ the exporter class name and underlying error detail.
16
+ """
17
+
18
+ import abc
19
+ import os
20
+ import sys
21
+
22
+ from ccai.agentkit.observabilityerror import ObservabilityError
23
+
24
+
25
+ class TraceExporter(abc.ABC):
26
+ """
27
+ Abstract base class for exporting completed TraceSpan objects
28
+ to external tracing backends.
29
+
30
+ Subclasses must implement the export, flush, and shutdown methods
31
+ to handle specific export destinations. Each exporter accepts an
32
+ optional list of credential reference names declaring which
33
+ credentials the exporter requires.
34
+
35
+ :param credential_references: Optional list of credential
36
+ reference name strings declaring which credentials the
37
+ exporter requires.
38
+ """
39
+
40
+ def __init__(self, credential_references: list = None) -> None:
41
+
42
+ if credential_references is not None:
43
+ self._credential_references = list(credential_references)
44
+ else:
45
+ self._credential_references = []
46
+
47
+ return
48
+
49
+ @property
50
+ def credential_references(self) -> list:
51
+ """
52
+ The list of credential reference name strings declaring
53
+ which credentials the exporter requires.
54
+
55
+ :returns: A list of credential reference name strings.
56
+ """
57
+ return list(self._credential_references)
58
+
59
+ @abc.abstractmethod
60
+ def export(self, spans: list) -> None:
61
+ """
62
+ Exports a list of completed TraceSpan objects to the
63
+ configured destination.
64
+
65
+ :param spans: A list of completed TraceSpan objects to export.
66
+
67
+ :raises: ObservabilityError
68
+ """
69
+
70
+ @abc.abstractmethod
71
+ def flush(self) -> None:
72
+ """
73
+ Ensures all buffered spans are delivered to the
74
+ configured destination.
75
+
76
+ :raises: ObservabilityError
77
+ """
78
+
79
+ @abc.abstractmethod
80
+ def shutdown(self) -> None:
81
+ """
82
+ Releases resources held by the exporter.
83
+
84
+ :raises: ObservabilityError
85
+ """
86
+
87
+ def __repr__(self) -> str:
88
+ """
89
+ Returns a detailed string representation including the
90
+ class name.
91
+
92
+ :returns: A repr string for debugging.
93
+ """
94
+ repr_str = "{}()".format(self.__class__.__name__)
95
+ return repr_str
96
+
97
+ def __str__(self) -> str:
98
+ """
99
+ Returns a human-readable summary including the exporter
100
+ class name.
101
+
102
+ :returns: A human-readable string.
103
+ """
104
+ str_val = "{}".format(self.__class__.__name__)
105
+ return str_val
106
+
107
+
108
+ class ConsoleTraceExporter(TraceExporter):
109
+ """
110
+ Writes completed TraceSpan objects as formatted text to standard
111
+ output.
112
+
113
+ Each span is formatted as a human-readable text line containing
114
+ the span name, trace identifier, span identifier, status, and
115
+ duration. The formatted text is written to sys.stdout followed
116
+ by a newline.
117
+ """
118
+
119
+ def __init__(self) -> None:
120
+
121
+ super().__init__()
122
+
123
+ return
124
+
125
+ def export(self, spans: list) -> None:
126
+ """
127
+ Writes a list of completed TraceSpan objects as formatted
128
+ text to standard output.
129
+
130
+ Each span is formatted as a human-readable text line
131
+ containing the span name, trace identifier, span identifier,
132
+ status, and duration.
133
+
134
+ :param spans: A list of completed TraceSpan objects to export.
135
+
136
+ :raises: ObservabilityError
137
+ """
138
+ try:
139
+ for span in spans:
140
+ trace_id = span.trace_context.trace_id
141
+ span_id = span.trace_context.span_id
142
+ parent_span_id = span.trace_context.parent_span_id
143
+ duration = span.duration
144
+
145
+ formatted = (
146
+ "TraceSpan: name={}, trace_id={}, span_id={}, "
147
+ "parent_span_id={}, status={}, duration={}"
148
+ ).format(
149
+ span.name, trace_id, span_id,
150
+ parent_span_id, span.status, duration
151
+ )
152
+ sys.stdout.write(formatted + "\n")
153
+ except Exception as exc:
154
+ raise ObservabilityError(
155
+ component_name=self.__class__.__name__,
156
+ operation_name="export",
157
+ message="Failed to export trace spans to console: {}".format(str(exc)),
158
+ cause=exc
159
+ ) from exc
160
+
161
+ return
162
+
163
+ def flush(self) -> None:
164
+ """
165
+ Flushes standard output to ensure all buffered spans
166
+ are delivered.
167
+
168
+ :raises: ObservabilityError
169
+ """
170
+ try:
171
+ sys.stdout.flush()
172
+ except Exception as exc:
173
+ raise ObservabilityError(
174
+ component_name=self.__class__.__name__,
175
+ operation_name="flush",
176
+ message="Failed to flush console output: {}".format(str(exc)),
177
+ cause=exc
178
+ ) from exc
179
+
180
+ return
181
+
182
+ def shutdown(self) -> None:
183
+ """
184
+ Releases resources held by the console exporter.
185
+
186
+ The ConsoleTraceExporter does not hold resources that
187
+ require explicit release, so this method performs no
188
+ action.
189
+ """
190
+ return
191
+
192
+
193
+ class FileTraceExporter(TraceExporter):
194
+ """
195
+ Writes completed TraceSpan objects as JSON lines to a specified
196
+ file path, resolved relative to the AppContext directory provided
197
+ by codecraftai-this-app.
198
+
199
+ Each span is serialized as a single-line JSON object and appended
200
+ to the target file. If an app_context is provided, the file_path
201
+ is resolved relative to the app_context directory. Otherwise, the
202
+ file_path is used as-is.
203
+
204
+ :param file_path: The file path string where span JSON lines
205
+ are written.
206
+ :param app_context: Optional AppContext instance providing the
207
+ directory for resolving relative file paths.
208
+ """
209
+
210
+ def __init__(self, file_path: str, app_context=None) -> None:
211
+
212
+ super().__init__()
213
+
214
+ self._file_path = file_path
215
+ self._app_context = app_context
216
+ self._resolved_path = self._resolve_path()
217
+
218
+ return
219
+
220
+ def _resolve_path(self) -> str:
221
+ """
222
+ Resolves the file path relative to the AppContext directory
223
+ if an app_context is provided, otherwise returns the
224
+ file_path as-is.
225
+
226
+ :returns: The resolved file path string.
227
+ """
228
+ if self._app_context is not None:
229
+ resolved = os.path.join(self._app_context.directory, self._file_path)
230
+ else:
231
+ resolved = self._file_path
232
+
233
+ return resolved
234
+
235
+ def export(self, spans: list) -> None:
236
+ """
237
+ Writes a list of completed TraceSpan objects as JSON lines
238
+ to the configured file path.
239
+
240
+ Each span is serialized using its to_json method and
241
+ appended as a single line to the target file.
242
+
243
+ :param spans: A list of completed TraceSpan objects to export.
244
+
245
+ :raises: ObservabilityError
246
+ """
247
+ try:
248
+ with open(self._resolved_path, "a") as file_handle:
249
+ for span in spans:
250
+ json_line = span.to_json()
251
+ file_handle.write(json_line + "\n")
252
+ except Exception as exc:
253
+ raise ObservabilityError(
254
+ component_name=self.__class__.__name__,
255
+ operation_name="export",
256
+ message="Failed to export trace spans to file {!r}: {}".format(
257
+ self._resolved_path, str(exc)
258
+ ),
259
+ cause=exc
260
+ ) from exc
261
+
262
+ return
263
+
264
+ def flush(self) -> None:
265
+ """
266
+ Flushes the file to ensure all buffered spans are
267
+ delivered. Since each export call opens and closes the
268
+ file, this method performs no additional action.
269
+ """
270
+ return
271
+
272
+ def shutdown(self) -> None:
273
+ """
274
+ Releases resources held by the file exporter.
275
+
276
+ The FileTraceExporter opens and closes the file on each
277
+ export call, so this method performs no additional action.
278
+ """
279
+ return
280
+
281
+ def __repr__(self) -> str:
282
+ """
283
+ Returns a detailed string representation including the
284
+ class name and file path.
285
+
286
+ :returns: A repr string for debugging.
287
+ """
288
+ repr_str = "{}(file_path={!r})".format(
289
+ self.__class__.__name__,
290
+ self._resolved_path
291
+ )
292
+ return repr_str
293
+
294
+ def __str__(self) -> str:
295
+ """
296
+ Returns a human-readable summary including the exporter
297
+ class name and file path.
298
+
299
+ :returns: A human-readable string.
300
+ """
301
+ str_val = "{}: file_path={}".format(
302
+ self.__class__.__name__,
303
+ self._resolved_path
304
+ )
305
+ return str_val
@@ -0,0 +1,234 @@
1
+ """
2
+ Defines the Tracer class that creates and manages TraceSpan objects
3
+ for an Agent.
4
+
5
+ The Tracer maintains an active span stack, supports nested span
6
+ creation for hierarchical tracing, and delivers completed spans
7
+ to registered TraceExporter instances. It implements probabilistic
8
+ sampling at the root span level, where non-sampled spans propagate
9
+ context but are not exported.
10
+ """
11
+
12
+ import contextlib
13
+ import random
14
+
15
+ from typing import Optional
16
+
17
+ from ccai.agentkit.tracecontext import TraceContext
18
+ from ccai.agentkit.traceexporter import TraceExporter
19
+ from ccai.agentkit.tracespan import TraceSpan
20
+
21
+
22
+ class Tracer:
23
+ """
24
+ A component that creates and manages TraceSpan objects for an
25
+ Agent.
26
+
27
+ The Tracer maintains a stack of active spans. When start_span
28
+ is called with no active span, a root span is created using
29
+ the root trace context if provided, or a new TraceContext
30
+ otherwise. When start_span is called with an active span, a
31
+ child span is created using the active span's
32
+ create_child_span_context method.
33
+
34
+ Probabilistic sampling is applied at the root span level. When
35
+ a root span is not sampled, the span and all its children
36
+ propagate context but are not delivered to exporters.
37
+
38
+ :param agent_id: The agent identifier string.
39
+ :param trace_context: Optional root TraceContext for establishing
40
+ the root trace context.
41
+ :param sampling_rate: The sampling rate as a float between 0.0
42
+ and 1.0 inclusive, defaulting to 1.0 (sample all spans).
43
+ """
44
+
45
+ def __init__(self, agent_id: str, trace_context: TraceContext = None,
46
+ sampling_rate: float = 1.0) -> None:
47
+
48
+ self._agent_id = agent_id
49
+ self._root_trace_context = trace_context
50
+ self._sampling_rate = sampling_rate
51
+ self._active_span_stack = []
52
+ self._exporters = []
53
+ self._sampled_traces = {}
54
+
55
+ return
56
+
57
+ @property
58
+ def active_span(self) -> Optional[TraceSpan]:
59
+ """
60
+ The current active TraceSpan at the top of the span stack,
61
+ or None when no span is active.
62
+
63
+ :returns: The active TraceSpan instance, or None.
64
+ """
65
+ if len(self._active_span_stack) > 0:
66
+ return self._active_span_stack[-1]
67
+
68
+ return None
69
+
70
+ @property
71
+ def sampling_rate(self) -> float:
72
+ """
73
+ The configured sampling rate as a float between 0.0 and 1.0
74
+ inclusive.
75
+
76
+ :returns: The sampling rate float.
77
+ """
78
+ return self._sampling_rate
79
+
80
+ def start_span(self, name: str, attributes: dict = None) -> TraceSpan:
81
+ """
82
+ Creates a new TraceSpan and pushes it onto the active span
83
+ stack.
84
+
85
+ When no active span exists, a root span is created. If a
86
+ root trace context was provided at construction, it is used
87
+ for the root span. Otherwise, a new TraceContext is generated.
88
+ A probabilistic sampling decision is made for root spans
89
+ using the configured sampling rate.
90
+
91
+ When an active span exists, a child span is created using
92
+ the active span's trace context create_child_span_context
93
+ method. Child spans inherit the sampling decision of their
94
+ root span.
95
+
96
+ :param name: The name string identifying the new span.
97
+ :param attributes: Optional dictionary of key-value attributes
98
+ for the new span.
99
+
100
+ :returns: The newly created TraceSpan instance.
101
+ """
102
+ if len(self._active_span_stack) == 0:
103
+ # Root span creation
104
+ if self._root_trace_context is not None:
105
+ trace_context = self._root_trace_context
106
+ self._root_trace_context = None
107
+ else:
108
+ trace_context = TraceContext()
109
+
110
+ # Make sampling decision for this trace
111
+ trace_id = trace_context.trace_id
112
+ is_sampled = random.random() < self._sampling_rate
113
+ self._sampled_traces[trace_id] = is_sampled
114
+ else:
115
+ # Child span creation
116
+ parent_span = self._active_span_stack[-1]
117
+ trace_context = parent_span.trace_context.create_child_span_context()
118
+
119
+ span = TraceSpan(
120
+ name=name,
121
+ trace_context=trace_context,
122
+ attributes=attributes
123
+ )
124
+ self._active_span_stack.append(span)
125
+
126
+ return span
127
+
128
+ def end_span(self) -> None:
129
+ """
130
+ Pops the current active span from the stack, ends it, and
131
+ delivers it to all registered exporters if the trace is
132
+ sampled.
133
+
134
+ If the span's trace is sampled, the completed span is
135
+ delivered to each registered TraceExporter via the export
136
+ method. If the trace is not sampled, the span is ended but
137
+ not exported.
138
+
139
+ When the last span for a trace is ended (stack becomes empty
140
+ or next span has a different trace_id), the sampling decision
141
+ for that trace is cleaned up.
142
+ """
143
+ if len(self._active_span_stack) == 0:
144
+ return
145
+
146
+ span = self._active_span_stack.pop()
147
+ span.end()
148
+
149
+ trace_id = span.trace_context.trace_id
150
+ is_sampled = self._sampled_traces.get(trace_id, True)
151
+
152
+ if is_sampled:
153
+ for exporter in self._exporters:
154
+ exporter.export([span])
155
+
156
+ # Clean up sampling decision when no more spans for this trace
157
+ if len(self._active_span_stack) == 0:
158
+ self._sampled_traces.pop(trace_id, None)
159
+ else:
160
+ remaining_trace_id = self._active_span_stack[-1].trace_context.trace_id
161
+ if remaining_trace_id != trace_id:
162
+ self._sampled_traces.pop(trace_id, None)
163
+
164
+ return
165
+
166
+ @contextlib.contextmanager
167
+ def span(self, name: str, attributes: dict = None):
168
+ """
169
+ A context manager that starts a span on entry and ends
170
+ the span on exit.
171
+
172
+ If an exception occurs within the context, the span's
173
+ status is set to "error" with the exception message as
174
+ the description before the span is ended. The exception
175
+ is then re-raised.
176
+
177
+ :param name: The name string identifying the span.
178
+ :param attributes: Optional dictionary of key-value attributes
179
+ for the span.
180
+
181
+ :yields: The newly created TraceSpan instance.
182
+ """
183
+ span = self.start_span(name=name, attributes=attributes)
184
+
185
+ try:
186
+ yield span
187
+ except Exception as exc:
188
+ span.set_status("error", description=str(exc))
189
+ raise
190
+ finally:
191
+ self.end_span()
192
+
193
+ def register_exporter(self, exporter: TraceExporter) -> None:
194
+ """
195
+ Registers a TraceExporter instance to receive completed
196
+ spans.
197
+
198
+ :param exporter: The TraceExporter instance to register.
199
+ """
200
+ self._exporters.append(exporter)
201
+
202
+ return
203
+
204
+ def __repr__(self) -> str:
205
+ """
206
+ Returns a detailed string representation including the
207
+ class name, agent identifier, and whether an active span
208
+ exists.
209
+
210
+ :returns: A repr string for debugging.
211
+ """
212
+ has_active = self.active_span is not None
213
+ repr_str = "Tracer(agent_id={!r}, has_active_span={})".format(
214
+ self._agent_id, has_active
215
+ )
216
+ return repr_str
217
+
218
+ def __str__(self) -> str:
219
+ """
220
+ Returns a human-readable summary including the agent
221
+ identifier and active span name.
222
+
223
+ :returns: A human-readable string.
224
+ """
225
+ active = self.active_span
226
+ if active is not None:
227
+ active_name = active.name
228
+ else:
229
+ active_name = None
230
+
231
+ str_val = "Tracer: agent_id={}, active_span={}".format(
232
+ self._agent_id, active_name
233
+ )
234
+ return str_val