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,65 @@
1
+ """
2
+ Defines the LLMStreamChunk class for immutable streaming response chunks.
3
+
4
+ LLMStreamChunk encapsulates a partial content string and an optional
5
+ metadata dictionary from a streaming LLM response. The chunk is
6
+ immutable once constructed.
7
+ """
8
+
9
+
10
+ class LLMStreamChunk:
11
+ """
12
+ Immutable partial content from a streaming LLM response.
13
+
14
+ Provides read-only access to the content string and metadata
15
+ dictionary. The metadata property returns a copy to preserve
16
+ immutability.
17
+
18
+ :param content: The partial content string from the stream.
19
+ :param metadata: Optional metadata dictionary.
20
+ """
21
+
22
+ def __init__(self, content: str, metadata: dict = None) -> None:
23
+ self._content = content
24
+ self._metadata = dict(metadata) if metadata is not None else {}
25
+ return
26
+
27
+ @property
28
+ def content(self) -> str:
29
+ """
30
+ The partial content string from the stream.
31
+
32
+ :returns: The content as a string.
33
+ """
34
+ rtnval = self._content
35
+ return rtnval
36
+
37
+ @property
38
+ def metadata(self) -> dict:
39
+ """
40
+ A copy of the metadata dictionary.
41
+
42
+ :returns: A dictionary copy of the metadata.
43
+ """
44
+ rtnval = dict(self._metadata)
45
+ return rtnval
46
+
47
+ def __repr__(self) -> str:
48
+ """
49
+ Returns a detailed string representation including the class name
50
+ and a truncated content preview at 30 characters.
51
+
52
+ :returns: A repr string for debugging.
53
+ """
54
+ preview = self._content[:30] + "..." if len(self._content) > 30 else self._content
55
+ rtnval = "{}(content={!r})".format(self.__class__.__name__, preview)
56
+ return rtnval
57
+
58
+ def __str__(self) -> str:
59
+ """
60
+ Returns the partial content string.
61
+
62
+ :returns: The content string.
63
+ """
64
+ rtnval = self._content
65
+ return rtnval
@@ -0,0 +1,48 @@
1
+ """
2
+ Defines the LLMStreamHandler abstract base class for streaming LLM
3
+ response processing.
4
+
5
+ LLMStreamHandler establishes the callback interface that streaming
6
+ consumers must implement. The handler receives LLMStreamChunk objects
7
+ as they arrive from the provider, a final LLMResponse when the stream
8
+ completes, and an exception if an error occurs during streaming.
9
+ """
10
+
11
+ import abc
12
+
13
+
14
+ class LLMStreamHandler(abc.ABC):
15
+ """
16
+ Abstract callback interface for receiving streaming LLM response chunks.
17
+
18
+ Subclasses implement the on_chunk, on_complete, and on_error methods
19
+ to process streaming responses from an LLMProvider. The provider
20
+ invokes on_chunk for each partial content chunk, on_complete with
21
+ the final assembled LLMResponse when the stream finishes, and
22
+ on_error if an exception occurs during streaming.
23
+ """
24
+
25
+ @abc.abstractmethod
26
+ def on_chunk(self, chunk) -> None:
27
+ """
28
+ Called for each chunk received during streaming.
29
+
30
+ :param chunk: The LLMStreamChunk with partial content.
31
+ """
32
+
33
+ @abc.abstractmethod
34
+ def on_complete(self, response) -> None:
35
+ """
36
+ Called when the streaming response completes successfully.
37
+
38
+ :param response: The final assembled LLMResponse including
39
+ complete TokenUsage.
40
+ """
41
+
42
+ @abc.abstractmethod
43
+ def on_error(self, error: Exception) -> None:
44
+ """
45
+ Called when an error occurs during streaming.
46
+
47
+ :param error: The exception that occurred.
48
+ """
@@ -0,0 +1,154 @@
1
+ """
2
+ Defines the LLMToolBridge class for converting between Tool system types
3
+ and LLM function calling format.
4
+
5
+ LLMToolBridge is a stateless utility class that converts ToolDescriptor
6
+ objects into OpenAI-compatible function definition dictionaries, extracts
7
+ tool call requests from LLMMessage metadata, and converts ToolResult
8
+ objects into LLMMessage instances with role "tool".
9
+ """
10
+
11
+ import json
12
+
13
+ from ccai.agentkit.errors import SemanticError
14
+ from ccai.agentkit.llmmessage import LLMMessage
15
+ from ccai.agentkit.tooldescriptor import ToolDescriptor
16
+ from ccai.agentkit.toolresult import ToolResult
17
+
18
+
19
+ class LLMToolBridge:
20
+ """
21
+ Converts between Tool system types and LLM function calling format.
22
+ Stateless utility class.
23
+ """
24
+
25
+ TOOL_SCHEMA_TYPE_TO_JSON_SCHEMA = {
26
+ "string": "string",
27
+ "integer": "integer",
28
+ "float": "number",
29
+ "boolean": "boolean",
30
+ "list": "array",
31
+ "dictionary": "object",
32
+ }
33
+
34
+ def descriptors_to_functions(self, descriptors: list) -> list:
35
+ """
36
+ Converts a list of ToolDescriptor objects into LLM-compatible
37
+ function definition dictionaries (OpenAI function calling format).
38
+
39
+ :param descriptors: A list of ToolDescriptor objects.
40
+
41
+ :returns: A list of function definition dictionaries.
42
+ """
43
+ rtnval = []
44
+
45
+ for descriptor in descriptors:
46
+ func_def = self._descriptor_to_function(descriptor)
47
+ rtnval.append(func_def)
48
+
49
+ return rtnval
50
+
51
+ def _descriptor_to_function(self, descriptor: ToolDescriptor) -> dict:
52
+ """
53
+ Converts a single ToolDescriptor to an OpenAI function definition.
54
+
55
+ :param descriptor: The ToolDescriptor to convert.
56
+
57
+ :returns: A function definition dictionary.
58
+ """
59
+ properties = {}
60
+ required = []
61
+
62
+ if descriptor.input_schema is not None:
63
+ for param in descriptor.input_schema.parameters:
64
+ pname = param["name"]
65
+ ptype = param["type"]
66
+ json_type = self.TOOL_SCHEMA_TYPE_TO_JSON_SCHEMA.get(ptype, "string")
67
+ properties[pname] = {"type": json_type}
68
+
69
+ has_description = param.get("description") is not None
70
+ if has_description is True:
71
+ description_value = param["description"]
72
+ if len(description_value) > 0:
73
+ properties[pname]["description"] = description_value
74
+
75
+ is_required = param.get("required", True)
76
+ if is_required is True:
77
+ required.append(pname)
78
+
79
+ rtnval = {
80
+ "type": "function",
81
+ "function": {
82
+ "name": descriptor.name,
83
+ "description": descriptor.description,
84
+ "parameters": {
85
+ "type": "object",
86
+ "properties": properties,
87
+ "required": required
88
+ }
89
+ }
90
+ }
91
+
92
+ return rtnval
93
+
94
+ def message_to_tool_calls(self, message: LLMMessage) -> list:
95
+ """
96
+ Extracts tool call requests from an LLMMessage.
97
+
98
+ :param message: An LLMMessage with tool call metadata.
99
+
100
+ :returns: A list of dicts with 'tool_name' and 'arguments' keys.
101
+
102
+ :raises: SemanticError if message does not contain tool calls.
103
+ """
104
+ metadata = message.metadata
105
+ tool_calls = metadata.get("tool_calls")
106
+
107
+ has_tool_calls = tool_calls is not None
108
+ if has_tool_calls is False:
109
+ errmsg = "LLMMessage does not contain tool call information."
110
+ raise SemanticError(errmsg)
111
+
112
+ is_empty = len(tool_calls) == 0
113
+ if is_empty is True:
114
+ errmsg = "LLMMessage does not contain tool call information."
115
+ raise SemanticError(errmsg)
116
+
117
+ rtnval = []
118
+
119
+ for tc in tool_calls:
120
+ function_info = tc["function"]
121
+ tool_name = function_info["name"]
122
+ arguments = function_info.get("arguments", {})
123
+
124
+ entry = {
125
+ "tool_name": tool_name,
126
+ "arguments": arguments
127
+ }
128
+ rtnval.append(entry)
129
+
130
+ return rtnval
131
+
132
+ def tool_result_to_message(self, tool_name: str,
133
+ result: ToolResult) -> LLMMessage:
134
+ """
135
+ Converts a ToolResult into an LLMMessage with role "tool".
136
+
137
+ :param tool_name: The name of the tool that was executed.
138
+ :param result: The ToolResult from tool execution.
139
+
140
+ :returns: An LLMMessage with role "tool".
141
+ """
142
+ has_output = result.output is not None
143
+ if has_output is True:
144
+ content = json.dumps(result.as_dict())
145
+ else:
146
+ content = ""
147
+
148
+ rtnval = LLMMessage(
149
+ role="tool",
150
+ content=content,
151
+ metadata={"tool_name": tool_name}
152
+ )
153
+
154
+ return rtnval
@@ -0,0 +1,316 @@
1
+ """
2
+ Defines the LogExporter abstract base class and concrete exporter
3
+ implementations for exporting StructuredLogEntry objects to external
4
+ systems.
5
+
6
+ Provides two concrete exporters:
7
+ - ConsoleLogExporter: writes formatted log entries to standard output
8
+ - FileLogExporter: writes formatted log entries to a specified file
9
+ path, resolved relative to the AppContext directory provided by
10
+ codecraftai-this-app
11
+
12
+ All exporters accept a LogFormatter at construction time for
13
+ formatting entries before export. Export failures raise
14
+ ObservabilityError with the exporter class name and underlying
15
+ error detail.
16
+ """
17
+
18
+ import abc
19
+ import os
20
+ import sys
21
+
22
+ from ccai.agentkit.logformatter import LogFormatter
23
+ from ccai.agentkit.observabilityerror import ObservabilityError
24
+ from ccai.agentkit.structuredlogentry import StructuredLogEntry
25
+
26
+
27
+ class LogExporter(abc.ABC):
28
+ """
29
+ Abstract base class for exporting StructuredLogEntry objects to
30
+ external systems.
31
+
32
+ Subclasses must implement the export, flush, and shutdown methods
33
+ to handle specific export destinations. Each exporter accepts a
34
+ LogFormatter for formatting entries before export and an optional
35
+ list of credential reference names declaring which credentials
36
+ the exporter requires.
37
+
38
+ :param formatter: The LogFormatter used to format entries before
39
+ export.
40
+ :param credential_references: Optional list of credential
41
+ reference name strings declaring which credentials the
42
+ exporter requires.
43
+ """
44
+
45
+ def __init__(self, formatter: LogFormatter, credential_references: list = None) -> None:
46
+
47
+ self._formatter = formatter
48
+
49
+ if credential_references is not None:
50
+ self._credential_references = list(credential_references)
51
+ else:
52
+ self._credential_references = []
53
+
54
+ return
55
+
56
+ @property
57
+ def formatter(self) -> LogFormatter:
58
+ """
59
+ The LogFormatter used to format entries before export.
60
+
61
+ :returns: The LogFormatter instance.
62
+ """
63
+ return self._formatter
64
+
65
+ @property
66
+ def credential_references(self) -> list:
67
+ """
68
+ The list of credential reference name strings declaring
69
+ which credentials the exporter requires.
70
+
71
+ :returns: A list of credential reference name strings.
72
+ """
73
+ return list(self._credential_references)
74
+
75
+ @abc.abstractmethod
76
+ def export(self, entry: StructuredLogEntry) -> None:
77
+ """
78
+ Exports a StructuredLogEntry to the configured destination.
79
+
80
+ :param entry: The structured log entry to export.
81
+
82
+ :raises: ObservabilityError
83
+ """
84
+
85
+ @abc.abstractmethod
86
+ def flush(self) -> None:
87
+ """
88
+ Ensures all buffered entries are delivered to the
89
+ configured destination.
90
+
91
+ :raises: ObservabilityError
92
+ """
93
+
94
+ @abc.abstractmethod
95
+ def shutdown(self) -> None:
96
+ """
97
+ Releases resources held by the exporter.
98
+
99
+ :raises: ObservabilityError
100
+ """
101
+
102
+ def __repr__(self) -> str:
103
+ """
104
+ Returns a detailed string representation including the
105
+ class name and the LogFormatter format name.
106
+
107
+ :returns: A repr string for debugging.
108
+ """
109
+ repr_str = "{}(format_name={!r})".format(
110
+ self.__class__.__name__,
111
+ self._formatter.format_name
112
+ )
113
+ return repr_str
114
+
115
+ def __str__(self) -> str:
116
+ """
117
+ Returns a human-readable summary including the exporter
118
+ class name and format name.
119
+
120
+ :returns: A human-readable string.
121
+ """
122
+ str_val = "{}: format_name={}".format(
123
+ self.__class__.__name__,
124
+ self._formatter.format_name
125
+ )
126
+ return str_val
127
+
128
+
129
+
130
+ class ConsoleLogExporter(LogExporter):
131
+ """
132
+ Writes formatted log entries to standard output.
133
+
134
+ Uses the provided LogFormatter to format each StructuredLogEntry
135
+ and writes the formatted string followed by a newline to
136
+ sys.stdout.
137
+
138
+ :param formatter: The LogFormatter used to format entries before
139
+ writing to standard output.
140
+ """
141
+
142
+ def __init__(self, formatter: LogFormatter) -> None:
143
+
144
+ super().__init__(formatter=formatter)
145
+
146
+ return
147
+
148
+ def export(self, entry: StructuredLogEntry) -> None:
149
+ """
150
+ Writes a formatted log entry to standard output.
151
+
152
+ Formats the entry using the configured LogFormatter and
153
+ writes the result followed by a newline to sys.stdout.
154
+
155
+ :param entry: The structured log entry to export.
156
+
157
+ :raises: ObservabilityError
158
+ """
159
+ try:
160
+ formatted = self._formatter.format(entry)
161
+ sys.stdout.write(formatted + "\n")
162
+ except Exception as exc:
163
+ raise ObservabilityError(
164
+ component_name=self.__class__.__name__,
165
+ operation_name="export",
166
+ message="Failed to export log entry to console: {}".format(str(exc)),
167
+ cause=exc
168
+ ) from exc
169
+
170
+ return
171
+
172
+ def flush(self) -> None:
173
+ """
174
+ Flushes standard output to ensure all buffered entries
175
+ are delivered.
176
+
177
+ :raises: ObservabilityError
178
+ """
179
+ try:
180
+ sys.stdout.flush()
181
+ except Exception as exc:
182
+ raise ObservabilityError(
183
+ component_name=self.__class__.__name__,
184
+ operation_name="flush",
185
+ message="Failed to flush console output: {}".format(str(exc)),
186
+ cause=exc
187
+ ) from exc
188
+
189
+ return
190
+
191
+ def shutdown(self) -> None:
192
+ """
193
+ Releases resources held by the console exporter.
194
+
195
+ The ConsoleLogExporter does not hold resources that
196
+ require explicit release, so this method performs no
197
+ action.
198
+ """
199
+ return
200
+
201
+
202
+ class FileLogExporter(LogExporter):
203
+ """
204
+ Writes formatted log entries to a specified file path, resolved
205
+ relative to the AppContext directory provided by codecraftai-this-app.
206
+
207
+ Uses the provided LogFormatter to format each StructuredLogEntry
208
+ and appends the formatted string followed by a newline to the
209
+ target file. If an app_context is provided, the file_path is
210
+ resolved relative to the app_context directory. Otherwise, the
211
+ file_path is used as-is.
212
+
213
+ :param formatter: The LogFormatter used to format entries before
214
+ writing to the file.
215
+ :param file_path: The file path string where log entries are
216
+ written.
217
+ :param app_context: Optional AppContext instance providing the
218
+ directory for resolving relative file paths.
219
+ """
220
+
221
+ def __init__(self, formatter: LogFormatter, file_path: str, app_context=None) -> None:
222
+
223
+ super().__init__(formatter=formatter)
224
+
225
+ self._file_path = file_path
226
+ self._app_context = app_context
227
+ self._resolved_path = self._resolve_path()
228
+
229
+ return
230
+
231
+ def _resolve_path(self) -> str:
232
+ """
233
+ Resolves the file path relative to the AppContext directory
234
+ if an app_context is provided, otherwise returns the
235
+ file_path as-is.
236
+
237
+ :returns: The resolved file path string.
238
+ """
239
+ if self._app_context is not None:
240
+ resolved = os.path.join(self._app_context.directory, self._file_path)
241
+ else:
242
+ resolved = self._file_path
243
+
244
+ return resolved
245
+
246
+ def export(self, entry: StructuredLogEntry) -> None:
247
+ """
248
+ Writes a formatted log entry to the configured file path.
249
+
250
+ Formats the entry using the configured LogFormatter and
251
+ appends the result followed by a newline to the target file.
252
+
253
+ :param entry: The structured log entry to export.
254
+
255
+ :raises: ObservabilityError
256
+ """
257
+ try:
258
+ formatted = self._formatter.format(entry)
259
+ with open(self._resolved_path, "a") as file_handle:
260
+ file_handle.write(formatted + "\n")
261
+ except Exception as exc:
262
+ raise ObservabilityError(
263
+ component_name=self.__class__.__name__,
264
+ operation_name="export",
265
+ message="Failed to export log entry to file {!r}: {}".format(
266
+ self._resolved_path, str(exc)
267
+ ),
268
+ cause=exc
269
+ ) from exc
270
+
271
+ return
272
+
273
+ def flush(self) -> None:
274
+ """
275
+ Flushes the file to ensure all buffered entries are
276
+ delivered. Since each export call opens and closes the
277
+ file, this method performs no additional action.
278
+ """
279
+ return
280
+
281
+ def shutdown(self) -> None:
282
+ """
283
+ Releases resources held by the file exporter.
284
+
285
+ The FileLogExporter opens and closes the file on each
286
+ export call, so this method performs no additional action.
287
+ """
288
+ return
289
+
290
+ def __repr__(self) -> str:
291
+ """
292
+ Returns a detailed string representation including the
293
+ class name, format name, and file path.
294
+
295
+ :returns: A repr string for debugging.
296
+ """
297
+ repr_str = "{}(format_name={!r}, file_path={!r})".format(
298
+ self.__class__.__name__,
299
+ self._formatter.format_name,
300
+ self._resolved_path
301
+ )
302
+ return repr_str
303
+
304
+ def __str__(self) -> str:
305
+ """
306
+ Returns a human-readable summary including the exporter
307
+ class name, format name, and file path.
308
+
309
+ :returns: A human-readable string.
310
+ """
311
+ str_val = "{}: format_name={}, file_path={}".format(
312
+ self.__class__.__name__,
313
+ self._formatter.format_name,
314
+ self._resolved_path
315
+ )
316
+ return str_val