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,197 @@
1
+ """
2
+ Defines the ToolSchema class for declarative schema definition of tool
3
+ input or output parameters.
4
+
5
+ ToolSchema supports type constraints, required/optional marking, default
6
+ values, validation, and serialization to and from dictionary and JSON
7
+ representations.
8
+ """
9
+
10
+ import json
11
+
12
+
13
+ class ToolSchema:
14
+ """
15
+ Declarative schema definition for tool input or output parameters.
16
+ Supports type constraints, required/optional marking, defaults, and validation.
17
+
18
+ Each parameter in the parameters list is a dictionary with keys:
19
+ - name (str, required): Parameter name
20
+ - type (str, required): One of SUPPORTED_TYPES
21
+ - required (bool, optional): Defaults to True
22
+ - default (any, optional): Default value for optional parameters
23
+ - description (str, optional): Human-readable description
24
+
25
+ :param parameters: A list of parameter definition dictionaries.
26
+ """
27
+
28
+ SUPPORTED_TYPES = {"string", "integer", "float", "boolean", "list", "dictionary"}
29
+
30
+ TYPE_MAP = {
31
+ "string": str,
32
+ "integer": int,
33
+ "float": float,
34
+ "boolean": bool,
35
+ "list": list,
36
+ "dictionary": dict,
37
+ }
38
+
39
+ def __init__(self, parameters: list = None) -> None:
40
+ if parameters is not None:
41
+ self._parameters = list(parameters)
42
+ else:
43
+ self._parameters = []
44
+
45
+ return
46
+
47
+ @property
48
+ def parameters(self) -> list:
49
+ """
50
+ A defensive copy of the parameter definition list.
51
+
52
+ :returns: A list of parameter definition dictionaries.
53
+ """
54
+ rtnval = list(self._parameters)
55
+ return rtnval
56
+
57
+ @property
58
+ def parameter_count(self) -> int:
59
+ """
60
+ The number of parameters defined in this schema.
61
+
62
+ :returns: The count of parameters.
63
+ """
64
+ rtnval = len(self._parameters)
65
+ return rtnval
66
+
67
+ def validate(self, values: dict) -> list:
68
+ """
69
+ Validates a dictionary of values against this schema.
70
+
71
+ Checks for missing required parameters, applies default values
72
+ for optional parameters that are absent, and verifies type
73
+ constraints for all provided values.
74
+
75
+ :param values: The dictionary of values to validate.
76
+
77
+ :returns: A list of validation error strings. Empty list if all values are valid.
78
+ """
79
+ errors = []
80
+
81
+ for param_def in self._parameters:
82
+ param_name = param_def["name"]
83
+ param_type = param_def["type"]
84
+ is_required = param_def.get("required", True)
85
+
86
+ has_value = param_name in values
87
+
88
+ if has_value is False:
89
+ if is_required is True:
90
+ errmsg = "Missing required parameter: '{}'".format(param_name)
91
+ errors.append(errmsg)
92
+ else:
93
+ has_default = "default" in param_def
94
+ if has_default is True:
95
+ default_value = param_def["default"]
96
+ values[param_name] = default_value
97
+ else:
98
+ provided_value = values[param_name]
99
+ expected_python_type = self.TYPE_MAP[param_type]
100
+ is_correct_type = isinstance(provided_value, expected_python_type)
101
+
102
+ if is_correct_type is False:
103
+ actual_type_name = type(provided_value).__name__
104
+ errmsg = "Parameter '{}': expected type '{}', got '{}'".format(
105
+ param_name, param_type, actual_type_name
106
+ )
107
+ errors.append(errmsg)
108
+
109
+ rtnval = errors
110
+ return rtnval
111
+
112
+ def as_dict(self) -> dict:
113
+ """
114
+ Returns a dictionary representation of the schema definition.
115
+
116
+ :returns: A dictionary with a 'parameters' key containing the list
117
+ of parameter definitions.
118
+ """
119
+ params_copy = []
120
+
121
+ for param_def in self._parameters:
122
+ param_copy = dict(param_def)
123
+ params_copy.append(param_copy)
124
+
125
+ rtnval = {
126
+ "parameters": params_copy
127
+ }
128
+ return rtnval
129
+
130
+ def to_json(self) -> str:
131
+ """
132
+ Returns a JSON string representation of the schema definition.
133
+
134
+ :returns: A JSON string containing the schema parameters.
135
+ """
136
+ data = self.as_dict()
137
+ rtnval = json.dumps(data)
138
+ return rtnval
139
+
140
+ @classmethod
141
+ def from_dict(cls, schema_data: dict) -> "ToolSchema":
142
+ """
143
+ Constructs a ToolSchema from a dictionary representation.
144
+
145
+ :param schema_data: A dictionary with a 'parameters' key containing
146
+ a list of parameter definition dictionaries.
147
+
148
+ :returns: A ToolSchema instance constructed from the dictionary data.
149
+ """
150
+ parameters = schema_data.get("parameters", [])
151
+ rtnval = cls(parameters=parameters)
152
+ return rtnval
153
+
154
+ @classmethod
155
+ def from_json(cls, json_str: str) -> "ToolSchema":
156
+ """
157
+ Deserializes a JSON string into a ToolSchema instance.
158
+
159
+ :param json_str: A JSON string containing schema data.
160
+
161
+ :returns: A ToolSchema instance reconstructed from the JSON data.
162
+ """
163
+ data = json.loads(json_str)
164
+ rtnval = cls.from_dict(schema_data=data)
165
+ return rtnval
166
+
167
+ def __repr__(self) -> str:
168
+ """
169
+ Returns a detailed string representation including class name
170
+ and the count of defined parameters.
171
+
172
+ :returns: A repr string for debugging.
173
+ """
174
+ rtnval = "ToolSchema(parameter_count={})".format(self.parameter_count)
175
+ return rtnval
176
+
177
+ def __str__(self) -> str:
178
+ """
179
+ Returns a human-readable summary listing the parameter names
180
+ and their types.
181
+
182
+ :returns: A human-readable string.
183
+ """
184
+ if len(self._parameters) == 0:
185
+ rtnval = "ToolSchema: (no parameters)"
186
+ return rtnval
187
+
188
+ parts = []
189
+ for param_def in self._parameters:
190
+ param_name = param_def["name"]
191
+ param_type = param_def["type"]
192
+ part = "{}: {}".format(param_name, param_type)
193
+ parts.append(part)
194
+
195
+ params_summary = ", ".join(parts)
196
+ rtnval = "ToolSchema: {}".format(params_summary)
197
+ return rtnval
@@ -0,0 +1,294 @@
1
+ """
2
+ Defines the TraceContext class representing an immutable distributed
3
+ tracing context for a single operation, compatible with the W3C
4
+ Trace Context specification.
5
+
6
+ TraceContext contains a trace identifier, a span identifier, an
7
+ optional parent span identifier, and trace flags. It supports
8
+ creation of child span contexts, serialization to and from JSON
9
+ and dictionary representations, and conversion to and from the
10
+ W3C traceparent header format.
11
+ """
12
+
13
+ import json
14
+ import os
15
+
16
+ from typing import Optional
17
+
18
+ from ccai.agentkit.errors import SemanticError
19
+
20
+
21
+ class TraceContext:
22
+ """
23
+ An immutable object representing the distributed tracing context
24
+ for a single operation, compatible with the W3C Trace Context
25
+ specification.
26
+
27
+ Contains a trace identifier as a 32-character lowercase hexadecimal
28
+ string, a span identifier as a 16-character lowercase hexadecimal
29
+ string, an optional parent span identifier, and trace flags as
30
+ an integer.
31
+
32
+ :param trace_id: Optional trace identifier string. Auto-generates
33
+ a 32-character hex string if not provided.
34
+ :param span_id: Optional span identifier string. Auto-generates
35
+ a 16-character hex string if not provided.
36
+ :param parent_span_id: Optional parent span identifier string.
37
+ :param trace_flags: Trace flags integer, defaults to 0.
38
+ """
39
+
40
+ def __init__(self, trace_id: str = None, span_id: str = None,
41
+ parent_span_id: str = None, trace_flags: int = 0) -> None:
42
+
43
+ if trace_id is not None:
44
+ self._trace_id = trace_id
45
+ else:
46
+ self._trace_id = os.urandom(16).hex()
47
+
48
+ if span_id is not None:
49
+ self._span_id = span_id
50
+ else:
51
+ self._span_id = os.urandom(8).hex()
52
+
53
+ self._parent_span_id = parent_span_id
54
+ self._trace_flags = trace_flags
55
+
56
+ return
57
+
58
+ @property
59
+ def trace_id(self) -> str:
60
+ """
61
+ The trace identifier as a 32-character lowercase hexadecimal
62
+ string.
63
+
64
+ :returns: The trace identifier string.
65
+ """
66
+ return self._trace_id
67
+
68
+ @property
69
+ def span_id(self) -> str:
70
+ """
71
+ The span identifier as a 16-character lowercase hexadecimal
72
+ string.
73
+
74
+ :returns: The span identifier string.
75
+ """
76
+ return self._span_id
77
+
78
+ @property
79
+ def parent_span_id(self) -> Optional[str]:
80
+ """
81
+ The optional parent span identifier as a 16-character lowercase
82
+ hexadecimal string.
83
+
84
+ :returns: The parent span identifier string, or None.
85
+ """
86
+ return self._parent_span_id
87
+
88
+ @property
89
+ def trace_flags(self) -> int:
90
+ """
91
+ The trace flags integer.
92
+
93
+ :returns: The trace flags value.
94
+ """
95
+ return self._trace_flags
96
+
97
+ def create_child_span_context(self) -> "TraceContext":
98
+ """
99
+ Creates a new TraceContext with the same trace identifier,
100
+ a new auto-generated span identifier, and the current span
101
+ identifier set as the parent span identifier.
102
+
103
+ :returns: A new TraceContext instance representing a child
104
+ span within the same trace.
105
+ """
106
+ child = TraceContext(
107
+ trace_id=self._trace_id,
108
+ parent_span_id=self._span_id,
109
+ trace_flags=self._trace_flags
110
+ )
111
+ return child
112
+
113
+ def to_traceparent(self) -> str:
114
+ """
115
+ Returns a W3C traceparent header string in the format
116
+ "00-{trace_id}-{span_id}-{trace_flags:02x}".
117
+
118
+ :returns: A W3C traceparent header string.
119
+ """
120
+ traceparent = "00-{}-{}-{:02x}".format(
121
+ self._trace_id, self._span_id, self._trace_flags
122
+ )
123
+ return traceparent
124
+
125
+ @classmethod
126
+ def from_traceparent(cls, traceparent: str) -> "TraceContext":
127
+ """
128
+ Parses a W3C traceparent header string and returns a
129
+ TraceContext instance.
130
+
131
+ The traceparent string must be in the format
132
+ "00-{trace_id}-{span_id}-{trace_flags}" where trace_id
133
+ is a 32-character hex string, span_id is a 16-character
134
+ hex string, and trace_flags is a 2-character hex string.
135
+
136
+ :param traceparent: A W3C traceparent header string.
137
+
138
+ :returns: A TraceContext instance parsed from the traceparent
139
+ string.
140
+
141
+ :raises SemanticError: If the traceparent string is malformed.
142
+ """
143
+ parts = traceparent.split("-")
144
+
145
+ if len(parts) != 4:
146
+ raise SemanticError(
147
+ "Malformed traceparent string: expected 4 parts separated by '-', got {}: {!r}".format(
148
+ len(parts), traceparent
149
+ )
150
+ )
151
+
152
+ version, trace_id, span_id, flags_str = parts
153
+
154
+ if len(trace_id) != 32:
155
+ raise SemanticError(
156
+ "Malformed traceparent string: trace_id must be 32 hex characters, got {}: {!r}".format(
157
+ len(trace_id), traceparent
158
+ )
159
+ )
160
+
161
+ try:
162
+ int(trace_id, 16)
163
+ except ValueError:
164
+ raise SemanticError(
165
+ "Malformed traceparent string: trace_id contains non-hex characters: {!r}".format(
166
+ traceparent
167
+ )
168
+ )
169
+
170
+ if len(span_id) != 16:
171
+ raise SemanticError(
172
+ "Malformed traceparent string: span_id must be 16 hex characters, got {}: {!r}".format(
173
+ len(span_id), traceparent
174
+ )
175
+ )
176
+
177
+ try:
178
+ int(span_id, 16)
179
+ except ValueError:
180
+ raise SemanticError(
181
+ "Malformed traceparent string: span_id contains non-hex characters: {!r}".format(
182
+ traceparent
183
+ )
184
+ )
185
+
186
+ if len(flags_str) != 2:
187
+ raise SemanticError(
188
+ "Malformed traceparent string: trace_flags must be 2 hex characters, got {}: {!r}".format(
189
+ len(flags_str), traceparent
190
+ )
191
+ )
192
+
193
+ try:
194
+ trace_flags = int(flags_str, 16)
195
+ except ValueError:
196
+ raise SemanticError(
197
+ "Malformed traceparent string: trace_flags contains non-hex characters: {!r}".format(
198
+ traceparent
199
+ )
200
+ )
201
+
202
+ context = cls(
203
+ trace_id=trace_id,
204
+ span_id=span_id,
205
+ trace_flags=trace_flags
206
+ )
207
+ return context
208
+
209
+ def as_dict(self) -> dict:
210
+ """
211
+ Returns a dictionary representation of the context fields.
212
+
213
+ :returns: A dictionary containing trace_id, span_id,
214
+ parent_span_id, and trace_flags.
215
+ """
216
+ result = {
217
+ "trace_id": self._trace_id,
218
+ "span_id": self._span_id,
219
+ "parent_span_id": self._parent_span_id,
220
+ "trace_flags": self._trace_flags
221
+ }
222
+ return result
223
+
224
+ def to_json(self) -> str:
225
+ """
226
+ Returns a JSON string representation of the context fields.
227
+
228
+ :returns: A JSON string containing all context fields.
229
+ """
230
+ data = self.as_dict()
231
+ json_str = json.dumps(data)
232
+ return json_str
233
+
234
+ @classmethod
235
+ def from_dict(cls, data: dict) -> "TraceContext":
236
+ """
237
+ Constructs a TraceContext from a dictionary.
238
+
239
+ :param data: A dictionary containing trace_id, span_id,
240
+ and optionally parent_span_id and trace_flags.
241
+
242
+ :returns: A TraceContext instance reconstructed from
243
+ the dictionary.
244
+ """
245
+ trace_id = data["trace_id"]
246
+ span_id = data["span_id"]
247
+ parent_span_id = data.get("parent_span_id", None)
248
+ trace_flags = data.get("trace_flags", 0)
249
+
250
+ context = cls(
251
+ trace_id=trace_id,
252
+ span_id=span_id,
253
+ parent_span_id=parent_span_id,
254
+ trace_flags=trace_flags
255
+ )
256
+ return context
257
+
258
+ @classmethod
259
+ def from_json(cls, json_str: str) -> "TraceContext":
260
+ """
261
+ Deserializes a JSON string into a TraceContext instance.
262
+
263
+ :param json_str: A JSON string containing context fields.
264
+
265
+ :returns: A TraceContext instance reconstructed from
266
+ the JSON data.
267
+ """
268
+ data = json.loads(json_str)
269
+ context = cls.from_dict(data)
270
+ return context
271
+
272
+ def __repr__(self) -> str:
273
+ """
274
+ Returns a detailed string representation including class name,
275
+ trace identifier, and span identifier.
276
+
277
+ :returns: A repr string for debugging.
278
+ """
279
+ repr_str = "TraceContext(trace_id={!r}, span_id={!r})".format(
280
+ self._trace_id, self._span_id
281
+ )
282
+ return repr_str
283
+
284
+ def __str__(self) -> str:
285
+ """
286
+ Returns a human-readable summary including the trace identifier,
287
+ span identifier, and parent span identifier.
288
+
289
+ :returns: A human-readable string.
290
+ """
291
+ str_val = "TraceContext: trace_id={}, span_id={}, parent_span_id={}".format(
292
+ self._trace_id, self._span_id, self._parent_span_id
293
+ )
294
+ return str_val
@@ -0,0 +1,166 @@
1
+ """
2
+ Defines the TraceEvent class representing an immutable timestamped
3
+ annotation within a TraceSpan.
4
+
5
+ TraceEvent objects record significant moments during a span's
6
+ lifetime for debugging and analysis. Each event contains a name,
7
+ a timestamp, and an attributes dictionary of key-value pairs.
8
+ All fields are exposed as read-only properties to preserve
9
+ immutability after construction.
10
+ """
11
+
12
+ import json
13
+
14
+ from datetime import datetime
15
+
16
+
17
+ class TraceEvent:
18
+ """
19
+ An immutable object representing a timestamped annotation within
20
+ a TraceSpan.
21
+
22
+ Contains a name string, a timestamp, and an attributes dictionary
23
+ of key-value pairs. The timestamp defaults to the current UTC time
24
+ when not explicitly provided.
25
+
26
+ :param name: The name string identifying this event.
27
+ :param timestamp: Optional timestamp for the event. Defaults to
28
+ the current UTC time if not provided.
29
+ :param attributes: Optional dictionary of key-value attributes
30
+ associated with this event.
31
+ """
32
+
33
+ def __init__(self, name: str, timestamp: datetime = None,
34
+ attributes: dict = None) -> None:
35
+
36
+ self._name = name
37
+
38
+ if timestamp is not None:
39
+ self._timestamp = timestamp
40
+ else:
41
+ self._timestamp = datetime.utcnow()
42
+
43
+ if attributes is not None:
44
+ self._attributes = dict(attributes)
45
+ else:
46
+ self._attributes = {}
47
+
48
+ return
49
+
50
+ @property
51
+ def name(self) -> str:
52
+ """
53
+ The name string identifying this event.
54
+
55
+ :returns: The event name string.
56
+ """
57
+ return self._name
58
+
59
+ @property
60
+ def timestamp(self) -> datetime:
61
+ """
62
+ The timestamp when this event occurred.
63
+
64
+ :returns: The datetime timestamp.
65
+ """
66
+ return self._timestamp
67
+
68
+ @property
69
+ def attributes(self) -> dict:
70
+ """
71
+ A copy of the attributes dictionary of key-value pairs
72
+ associated with this event. Returns a copy to preserve
73
+ immutability.
74
+
75
+ :returns: A dictionary copy of the event attributes.
76
+ """
77
+ result = dict(self._attributes)
78
+ return result
79
+
80
+ def as_dict(self) -> dict:
81
+ """
82
+ Returns a dictionary representation of the event fields.
83
+
84
+ The timestamp is serialized as an ISO format string for
85
+ consistent representation.
86
+
87
+ :returns: A dictionary containing all event fields.
88
+ """
89
+ result = {
90
+ "name": self._name,
91
+ "timestamp": self._timestamp.isoformat(),
92
+ "attributes": dict(self._attributes)
93
+ }
94
+ return result
95
+
96
+ def to_json(self) -> str:
97
+ """
98
+ Returns a JSON string representation of the event fields.
99
+
100
+ :returns: A JSON string containing all event fields.
101
+ """
102
+ data = self.as_dict()
103
+ json_str = json.dumps(data)
104
+ return json_str
105
+
106
+ @classmethod
107
+ def from_dict(cls, data: dict) -> "TraceEvent":
108
+ """
109
+ Constructs a TraceEvent from a dictionary.
110
+
111
+ The timestamp field is expected to be an ISO format string
112
+ and is parsed back into a datetime object.
113
+
114
+ :param data: A dictionary containing event fields.
115
+
116
+ :returns: A TraceEvent instance reconstructed from
117
+ the dictionary.
118
+ """
119
+ name = data["name"]
120
+ timestamp = datetime.fromisoformat(data["timestamp"])
121
+ attributes = data.get("attributes", None)
122
+
123
+ event = cls(
124
+ name=name,
125
+ timestamp=timestamp,
126
+ attributes=attributes
127
+ )
128
+ return event
129
+
130
+ @classmethod
131
+ def from_json(cls, json_str: str) -> "TraceEvent":
132
+ """
133
+ Deserializes a JSON string into a TraceEvent instance.
134
+
135
+ :param json_str: A JSON string containing event fields.
136
+
137
+ :returns: A TraceEvent instance reconstructed from
138
+ the JSON data.
139
+ """
140
+ data = json.loads(json_str)
141
+ event = cls.from_dict(data)
142
+ return event
143
+
144
+ def __repr__(self) -> str:
145
+ """
146
+ Returns a detailed string representation including class name,
147
+ name, and timestamp.
148
+
149
+ :returns: A repr string for debugging.
150
+ """
151
+ repr_str = "TraceEvent(name={!r}, timestamp={!r})".format(
152
+ self._name, self._timestamp.isoformat()
153
+ )
154
+ return repr_str
155
+
156
+ def __str__(self) -> str:
157
+ """
158
+ Returns a human-readable summary including the name and
159
+ timestamp.
160
+
161
+ :returns: A human-readable string.
162
+ """
163
+ str_val = "TraceEvent: name={}, timestamp={}".format(
164
+ self._name, self._timestamp.isoformat()
165
+ )
166
+ return str_val