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,956 @@
1
+ """
2
+ Defines the LocalPlatformAdapter and its local service implementations
3
+ for running agents in a local environment. Provides LocalComputeService
4
+ (subprocess execution), LocalStorageService (file system storage), and
5
+ LocalMessagingService (in-memory queuing).
6
+
7
+ .. module:: ccai.agentkit.platform.adapters.localplatformadapter
8
+ :platform: Darwin, Linux, Unix, Windows
9
+ :synopsis: Local platform adapter with subprocess, filesystem, and in-memory services.
10
+ """
11
+
12
+ import collections
13
+ import json
14
+ import logging
15
+ import os
16
+ import subprocess
17
+ import threading
18
+ import time
19
+ import uuid
20
+
21
+ from datetime import datetime
22
+
23
+ from ccai.agentkit.platform.adapters.platformadapter import PlatformAdapter
24
+ from ccai.agentkit.platform.errors import ComputeError
25
+ from ccai.agentkit.platform.errors import MessagingError
26
+ from ccai.agentkit.platform.errors import StorageError
27
+ from ccai.agentkit.platform.platformconfiguration import PlatformConfiguration
28
+ from ccai.agentkit.platform.platformtype import PlatformType
29
+ from ccai.agentkit.platform.services.computeservice import ComputeService
30
+ from ccai.agentkit.platform.services.invocationresult import InvocationResult
31
+ from ccai.agentkit.platform.services.messagingservice import MessagingService
32
+ from ccai.agentkit.platform.services.queuemessage import QueueMessage
33
+ from ccai.agentkit.platform.services.storageobject import StorageObject
34
+ from ccai.agentkit.platform.services.storageservice import StorageService
35
+
36
+
37
+ logger = logging.getLogger("ccai.agentkit.platform.adapters")
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # LocalComputeService
42
+ # ---------------------------------------------------------------------------
43
+
44
+ class LocalComputeService(ComputeService):
45
+ """
46
+ Compute service implementation that executes functions as local
47
+ subprocesses. Supports configurable timeout with a default of 30
48
+ seconds. Returns InvocationResult with status "timeout" when the
49
+ subprocess exceeds the configured timeout.
50
+
51
+ :param platform_type: The PlatformType (expected to be LOCAL).
52
+ :param configuration: An optional PlatformConfiguration.
53
+ :param default_timeout: Default timeout in seconds for subprocess execution.
54
+ """
55
+
56
+ def __init__(self, platform_type: PlatformType,
57
+ configuration: PlatformConfiguration = None,
58
+ default_timeout: float = 30.0) -> None:
59
+ super().__init__(
60
+ service_name="local-compute",
61
+ platform_type=platform_type,
62
+ configuration=configuration
63
+ )
64
+ self._default_timeout = default_timeout
65
+ self._async_results = {}
66
+ return
67
+
68
+ def invoke(self, function_name: str, payload: dict,
69
+ timeout: float = None) -> InvocationResult:
70
+ """
71
+ Invokes a function as a local subprocess.
72
+
73
+ The function_name is treated as a shell command. The payload is
74
+ serialized to JSON and passed as stdin to the subprocess.
75
+
76
+ :param function_name: The command to execute.
77
+ :param payload: Dictionary payload serialized as JSON stdin.
78
+ :param timeout: Optional timeout in seconds, defaults to default_timeout.
79
+
80
+ :returns: An InvocationResult with the execution outcome.
81
+ :raises: ComputeError
82
+ """
83
+ effective_timeout = timeout if timeout is not None else self._default_timeout
84
+ request_id = str(uuid.uuid4())
85
+ payload_json = json.dumps(payload)
86
+ start_time = time.monotonic()
87
+
88
+ try:
89
+ completed = subprocess.run(
90
+ function_name,
91
+ input=payload_json,
92
+ capture_output=True,
93
+ text=True,
94
+ timeout=effective_timeout,
95
+ shell=True
96
+ )
97
+ duration = time.monotonic() - start_time
98
+
99
+ if completed.returncode == 0:
100
+ response = completed.stdout
101
+ rtnval = InvocationResult(
102
+ status="success",
103
+ response=response,
104
+ duration=duration,
105
+ request_id=request_id
106
+ )
107
+ else:
108
+ err_detail = completed.stderr if completed.stderr else "exit code {}".format(completed.returncode)
109
+ rtnval = InvocationResult(
110
+ status="error",
111
+ response=completed.stdout,
112
+ error_message=err_detail,
113
+ duration=duration,
114
+ request_id=request_id
115
+ )
116
+
117
+ except subprocess.TimeoutExpired:
118
+ duration = time.monotonic() - start_time
119
+ err_msg = "Subprocess timed out after {:.1f} seconds.".format(effective_timeout)
120
+ rtnval = InvocationResult(
121
+ status="timeout",
122
+ error_message=err_msg,
123
+ duration=duration,
124
+ request_id=request_id
125
+ )
126
+
127
+ except Exception as exc:
128
+ err_msg_lines = [
129
+ "Local compute invocation failed.",
130
+ " Function: {!r}".format(function_name),
131
+ " Error: {}".format(str(exc))
132
+ ]
133
+ err_msg = os.linesep.join(err_msg_lines)
134
+ logger.warning("%s", err_msg)
135
+ raise ComputeError(
136
+ err_msg,
137
+ function_name=function_name,
138
+ cause=exc,
139
+ platform_type=PlatformType.LOCAL
140
+ )
141
+
142
+ return rtnval
143
+
144
+ def invoke_async(self, function_name: str, payload: dict) -> str:
145
+ """
146
+ Invokes a function asynchronously by spawning a thread that
147
+ runs the subprocess. Returns a request identifier for tracking.
148
+
149
+ :param function_name: The command to execute.
150
+ :param payload: Dictionary payload serialized as JSON stdin.
151
+
152
+ :returns: A request identifier string.
153
+ :raises: ComputeError
154
+ """
155
+ request_id = str(uuid.uuid4())
156
+ self._async_results[request_id] = None
157
+
158
+ def _run():
159
+ result = self.invoke(function_name, payload)
160
+ self._async_results[request_id] = result
161
+ return
162
+
163
+ thread = threading.Thread(target=_run, daemon=True)
164
+ thread.start()
165
+
166
+ rtnval = request_id
167
+ return rtnval
168
+
169
+ def get_invocation_status(self, request_id: str) -> InvocationResult:
170
+ """
171
+ Returns the current status of an asynchronous invocation.
172
+
173
+ :param request_id: The request identifier from invoke_async.
174
+
175
+ :returns: An InvocationResult or a pending result.
176
+ :raises: ComputeError
177
+ """
178
+ if request_id not in self._async_results:
179
+ err_msg_lines = [
180
+ "Unknown async invocation request identifier.",
181
+ " Request ID: {!r}".format(request_id)
182
+ ]
183
+ err_msg = os.linesep.join(err_msg_lines)
184
+ logger.warning("%s", err_msg)
185
+ raise ComputeError(
186
+ err_msg,
187
+ function_name="unknown",
188
+ platform_type=PlatformType.LOCAL
189
+ )
190
+
191
+ result = self._async_results[request_id]
192
+ if result is None:
193
+ rtnval = InvocationResult(
194
+ status="pending",
195
+ request_id=request_id
196
+ )
197
+ else:
198
+ rtnval = result
199
+
200
+ return rtnval
201
+
202
+ def list_functions(self) -> list:
203
+ """
204
+ Returns an empty list since local compute does not maintain
205
+ a function registry.
206
+
207
+ :returns: An empty list.
208
+ """
209
+ rtnval = []
210
+ return rtnval
211
+
212
+ def is_available(self) -> bool:
213
+ """
214
+ Local compute is always available.
215
+
216
+ :returns: True.
217
+ """
218
+ rtnval = True
219
+ return rtnval
220
+
221
+ def health_check(self) -> bool:
222
+ """
223
+ Local compute health check verifies subprocess execution works.
224
+
225
+ :returns: True if a simple subprocess can be executed.
226
+ """
227
+ try:
228
+ completed = subprocess.run(
229
+ "echo ok",
230
+ capture_output=True,
231
+ text=True,
232
+ timeout=5.0,
233
+ shell=True
234
+ )
235
+ rtnval = completed.returncode == 0
236
+ except Exception:
237
+ rtnval = False
238
+
239
+ return rtnval
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # LocalStorageService
244
+ # ---------------------------------------------------------------------------
245
+
246
+ class LocalStorageService(StorageService):
247
+ """
248
+ Storage service implementation that stores objects as files on the
249
+ local file system. Objects are stored under
250
+ {base_directory}/{container_name}/{object_key} with companion
251
+ .meta.json files for metadata.
252
+
253
+ :param platform_type: The PlatformType (expected to be LOCAL).
254
+ :param configuration: An optional PlatformConfiguration.
255
+ :param base_directory: The base directory for file storage.
256
+ """
257
+
258
+ def __init__(self, platform_type: PlatformType,
259
+ configuration: PlatformConfiguration = None,
260
+ base_directory: str = None) -> None:
261
+ super().__init__(
262
+ service_name="local-storage",
263
+ platform_type=platform_type,
264
+ configuration=configuration
265
+ )
266
+ self._base_directory = base_directory if base_directory is not None else os.path.join(os.getcwd(), ".local-storage")
267
+ return
268
+
269
+ def _container_path(self, container_name: str) -> str:
270
+ """
271
+ Returns the file system path for a container.
272
+
273
+ :param container_name: Name of the container.
274
+
275
+ :returns: The absolute path string.
276
+ """
277
+ rtnval = os.path.join(self._base_directory, container_name)
278
+ return rtnval
279
+
280
+ def _object_path(self, container_name: str, object_key: str) -> str:
281
+ """
282
+ Returns the file system path for an object within a container.
283
+
284
+ :param container_name: Name of the container.
285
+ :param object_key: Key identifying the object.
286
+
287
+ :returns: The absolute path string.
288
+ """
289
+ rtnval = os.path.join(self._base_directory, container_name, object_key)
290
+ return rtnval
291
+
292
+ def _meta_path(self, container_name: str, object_key: str) -> str:
293
+ """
294
+ Returns the file system path for the metadata companion file.
295
+
296
+ :param container_name: Name of the container.
297
+ :param object_key: Key identifying the object.
298
+
299
+ :returns: The absolute path string for the .meta.json file.
300
+ """
301
+ rtnval = os.path.join(self._base_directory, container_name, object_key + ".meta.json")
302
+ return rtnval
303
+
304
+ def put_object(self, container_name: str, object_key: str,
305
+ content: bytes, content_type: str = None,
306
+ metadata: dict = None) -> None:
307
+ """
308
+ Stores an object as a file in the specified container directory.
309
+
310
+ :param container_name: Name of the storage container.
311
+ :param object_key: Key identifying the object.
312
+ :param content: Object content as bytes.
313
+ :param content_type: Optional MIME content type string.
314
+ :param metadata: Optional metadata dictionary.
315
+
316
+ :raises: StorageError
317
+ """
318
+ obj_path = self._object_path(container_name, object_key)
319
+ meta_path = self._meta_path(container_name, object_key)
320
+
321
+ try:
322
+ obj_dir = os.path.dirname(obj_path)
323
+ if not os.path.exists(obj_dir):
324
+ os.makedirs(obj_dir, exist_ok=True)
325
+
326
+ with open(obj_path, "wb") as fh:
327
+ fh.write(content)
328
+
329
+ meta = {
330
+ "content_type": content_type if content_type is not None else "application/octet-stream",
331
+ "metadata": dict(metadata) if metadata is not None else {},
332
+ "size": len(content),
333
+ "last_modified": datetime.utcnow().isoformat()
334
+ }
335
+ with open(meta_path, "w") as fh:
336
+ json.dump(meta, fh)
337
+
338
+ except Exception as exc:
339
+ err_msg_lines = [
340
+ "Failed to store object in local storage.",
341
+ " Container: {!r}".format(container_name),
342
+ " Object key: {!r}".format(object_key),
343
+ " Error: {}".format(str(exc))
344
+ ]
345
+ err_msg = os.linesep.join(err_msg_lines)
346
+ logger.warning("%s", err_msg)
347
+ raise StorageError(
348
+ err_msg,
349
+ operation_name="put_object",
350
+ container_name=container_name,
351
+ object_key=object_key,
352
+ cause=exc,
353
+ platform_type=PlatformType.LOCAL
354
+ )
355
+
356
+ return
357
+
358
+ def get_object(self, container_name: str, object_key: str) -> StorageObject:
359
+ """
360
+ Retrieves an object from the specified container directory.
361
+
362
+ :param container_name: Name of the storage container.
363
+ :param object_key: Key identifying the object.
364
+
365
+ :returns: A StorageObject instance.
366
+ :raises: StorageError
367
+ """
368
+ obj_path = self._object_path(container_name, object_key)
369
+ meta_path = self._meta_path(container_name, object_key)
370
+
371
+ if not os.path.exists(obj_path):
372
+ err_msg_lines = [
373
+ "Object not found in local storage.",
374
+ " Container: {!r}".format(container_name),
375
+ " Object key: {!r}".format(object_key)
376
+ ]
377
+ err_msg = os.linesep.join(err_msg_lines)
378
+ logger.warning("%s", err_msg)
379
+ raise StorageError(
380
+ err_msg,
381
+ operation_name="get_object",
382
+ container_name=container_name,
383
+ object_key=object_key,
384
+ platform_type=PlatformType.LOCAL
385
+ )
386
+
387
+ try:
388
+ with open(obj_path, "rb") as fh:
389
+ content = fh.read()
390
+
391
+ meta = {}
392
+ if os.path.exists(meta_path):
393
+ with open(meta_path, "r") as fh:
394
+ meta = json.load(fh)
395
+
396
+ content_type = meta.get("content_type", "application/octet-stream")
397
+ metadata = meta.get("metadata", {})
398
+ size = meta.get("size", len(content))
399
+ last_modified_str = meta.get("last_modified")
400
+ last_modified = datetime.fromisoformat(last_modified_str) if last_modified_str is not None else None
401
+
402
+ rtnval = StorageObject(
403
+ key=object_key,
404
+ content=content,
405
+ content_type=content_type,
406
+ metadata=metadata,
407
+ size=size,
408
+ last_modified=last_modified
409
+ )
410
+
411
+ except StorageError:
412
+ raise
413
+
414
+ except Exception as exc:
415
+ err_msg_lines = [
416
+ "Failed to retrieve object from local storage.",
417
+ " Container: {!r}".format(container_name),
418
+ " Object key: {!r}".format(object_key),
419
+ " Error: {}".format(str(exc))
420
+ ]
421
+ err_msg = os.linesep.join(err_msg_lines)
422
+ logger.warning("%s", err_msg)
423
+ raise StorageError(
424
+ err_msg,
425
+ operation_name="get_object",
426
+ container_name=container_name,
427
+ object_key=object_key,
428
+ cause=exc,
429
+ platform_type=PlatformType.LOCAL
430
+ )
431
+
432
+ return rtnval
433
+
434
+ def delete_object(self, container_name: str, object_key: str) -> None:
435
+ """
436
+ Removes an object file and its metadata companion from the
437
+ specified container directory.
438
+
439
+ :param container_name: Name of the storage container.
440
+ :param object_key: Key identifying the object.
441
+
442
+ :raises: StorageError
443
+ """
444
+ obj_path = self._object_path(container_name, object_key)
445
+ meta_path = self._meta_path(container_name, object_key)
446
+
447
+ try:
448
+ if os.path.exists(obj_path):
449
+ os.remove(obj_path)
450
+ if os.path.exists(meta_path):
451
+ os.remove(meta_path)
452
+ except Exception as exc:
453
+ err_msg_lines = [
454
+ "Failed to delete object from local storage.",
455
+ " Container: {!r}".format(container_name),
456
+ " Object key: {!r}".format(object_key),
457
+ " Error: {}".format(str(exc))
458
+ ]
459
+ err_msg = os.linesep.join(err_msg_lines)
460
+ logger.warning("%s", err_msg)
461
+ raise StorageError(
462
+ err_msg,
463
+ operation_name="delete_object",
464
+ container_name=container_name,
465
+ object_key=object_key,
466
+ cause=exc,
467
+ platform_type=PlatformType.LOCAL
468
+ )
469
+
470
+ return
471
+
472
+ def list_objects(self, container_name: str, prefix: str = None) -> list:
473
+ """
474
+ Returns a list of object key strings in the specified container,
475
+ optionally filtered by prefix. Excludes .meta.json companion files.
476
+
477
+ :param container_name: Name of the storage container.
478
+ :param prefix: Optional prefix filter string.
479
+
480
+ :returns: List of object key strings.
481
+ :raises: StorageError
482
+ """
483
+ container_path = self._container_path(container_name)
484
+
485
+ if not os.path.exists(container_path):
486
+ rtnval = []
487
+ return rtnval
488
+
489
+ try:
490
+ keys = []
491
+ for root, dirs, files in os.walk(container_path):
492
+ for file_name in files:
493
+ if file_name.endswith(".meta.json"):
494
+ continue
495
+ full_path = os.path.join(root, file_name)
496
+ relative_key = os.path.relpath(full_path, container_path)
497
+ if prefix is not None and not relative_key.startswith(prefix):
498
+ continue
499
+ keys.append(relative_key)
500
+
501
+ rtnval = sorted(keys)
502
+
503
+ except Exception as exc:
504
+ err_msg_lines = [
505
+ "Failed to list objects in local storage.",
506
+ " Container: {!r}".format(container_name),
507
+ " Error: {}".format(str(exc))
508
+ ]
509
+ err_msg = os.linesep.join(err_msg_lines)
510
+ logger.warning("%s", err_msg)
511
+ raise StorageError(
512
+ err_msg,
513
+ operation_name="list_objects",
514
+ container_name=container_name,
515
+ cause=exc,
516
+ platform_type=PlatformType.LOCAL
517
+ )
518
+
519
+ return rtnval
520
+
521
+ def object_exists(self, container_name: str, object_key: str) -> bool:
522
+ """
523
+ Checks whether an object file exists in the specified container.
524
+
525
+ :param container_name: Name of the storage container.
526
+ :param object_key: Key identifying the object.
527
+
528
+ :returns: True if the object exists, False otherwise.
529
+ :raises: StorageError
530
+ """
531
+ obj_path = self._object_path(container_name, object_key)
532
+ rtnval = os.path.exists(obj_path)
533
+ return rtnval
534
+
535
+ def create_container(self, container_name: str) -> None:
536
+ """
537
+ Creates a container directory.
538
+
539
+ :param container_name: Name of the container to create.
540
+
541
+ :raises: StorageError
542
+ """
543
+ container_path = self._container_path(container_name)
544
+
545
+ try:
546
+ os.makedirs(container_path, exist_ok=True)
547
+ except Exception as exc:
548
+ err_msg_lines = [
549
+ "Failed to create container in local storage.",
550
+ " Container: {!r}".format(container_name),
551
+ " Error: {}".format(str(exc))
552
+ ]
553
+ err_msg = os.linesep.join(err_msg_lines)
554
+ logger.warning("%s", err_msg)
555
+ raise StorageError(
556
+ err_msg,
557
+ operation_name="create_container",
558
+ container_name=container_name,
559
+ cause=exc,
560
+ platform_type=PlatformType.LOCAL
561
+ )
562
+
563
+ return
564
+
565
+ def delete_container(self, container_name: str) -> None:
566
+ """
567
+ Removes a container directory and all its contents.
568
+
569
+ :param container_name: Name of the container to remove.
570
+
571
+ :raises: StorageError
572
+ """
573
+ container_path = self._container_path(container_name)
574
+
575
+ try:
576
+ if os.path.exists(container_path):
577
+ import shutil
578
+ shutil.rmtree(container_path)
579
+ except Exception as exc:
580
+ err_msg_lines = [
581
+ "Failed to delete container from local storage.",
582
+ " Container: {!r}".format(container_name),
583
+ " Error: {}".format(str(exc))
584
+ ]
585
+ err_msg = os.linesep.join(err_msg_lines)
586
+ logger.warning("%s", err_msg)
587
+ raise StorageError(
588
+ err_msg,
589
+ operation_name="delete_container",
590
+ container_name=container_name,
591
+ cause=exc,
592
+ platform_type=PlatformType.LOCAL
593
+ )
594
+
595
+ return
596
+
597
+ def list_containers(self) -> list:
598
+ """
599
+ Returns a list of container name strings (subdirectories under
600
+ the base directory).
601
+
602
+ :returns: List of container name strings.
603
+ :raises: StorageError
604
+ """
605
+ if not os.path.exists(self._base_directory):
606
+ rtnval = []
607
+ return rtnval
608
+
609
+ try:
610
+ containers = []
611
+ for entry in os.listdir(self._base_directory):
612
+ entry_path = os.path.join(self._base_directory, entry)
613
+ if os.path.isdir(entry_path):
614
+ containers.append(entry)
615
+
616
+ rtnval = sorted(containers)
617
+
618
+ except Exception as exc:
619
+ err_msg_lines = [
620
+ "Failed to list containers in local storage.",
621
+ " Base directory: {!r}".format(self._base_directory),
622
+ " Error: {}".format(str(exc))
623
+ ]
624
+ err_msg = os.linesep.join(err_msg_lines)
625
+ logger.warning("%s", err_msg)
626
+ raise StorageError(
627
+ err_msg,
628
+ operation_name="list_containers",
629
+ container_name="",
630
+ cause=exc,
631
+ platform_type=PlatformType.LOCAL
632
+ )
633
+
634
+ return rtnval
635
+
636
+ def is_available(self) -> bool:
637
+ """
638
+ Local storage is available when the base directory exists or
639
+ can be created.
640
+
641
+ :returns: True if available.
642
+ """
643
+ try:
644
+ os.makedirs(self._base_directory, exist_ok=True)
645
+ rtnval = True
646
+ except Exception:
647
+ rtnval = False
648
+
649
+ return rtnval
650
+
651
+ def health_check(self) -> bool:
652
+ """
653
+ Local storage health check verifies the base directory is
654
+ accessible.
655
+
656
+ :returns: True if the base directory is writable.
657
+ """
658
+ try:
659
+ os.makedirs(self._base_directory, exist_ok=True)
660
+ test_path = os.path.join(self._base_directory, ".health_check")
661
+ with open(test_path, "w") as fh:
662
+ fh.write("ok")
663
+ os.remove(test_path)
664
+ rtnval = True
665
+ except Exception:
666
+ rtnval = False
667
+
668
+ return rtnval
669
+
670
+
671
+ # ---------------------------------------------------------------------------
672
+ # LocalMessagingService
673
+ # ---------------------------------------------------------------------------
674
+
675
+ class LocalMessagingService(MessagingService):
676
+ """
677
+ Messaging service implementation that uses in-memory queues backed
678
+ by collections.deque with threading.Lock for concurrent access.
679
+
680
+ Messages are QueueMessage instances stored in per-queue deques.
681
+ Acknowledged messages are removed from the pending set.
682
+
683
+ :param platform_type: The PlatformType (expected to be LOCAL).
684
+ :param configuration: An optional PlatformConfiguration.
685
+ """
686
+
687
+ def __init__(self, platform_type: PlatformType,
688
+ configuration: PlatformConfiguration = None) -> None:
689
+ super().__init__(
690
+ service_name="local-messaging",
691
+ platform_type=platform_type,
692
+ configuration=configuration
693
+ )
694
+ self._queues = {}
695
+ self._pending = {}
696
+ self._lock = threading.Lock()
697
+ return
698
+
699
+ def send_message(self, queue_name: str, body: object,
700
+ attributes: dict = None) -> str:
701
+ """
702
+ Sends a message to the specified in-memory queue.
703
+
704
+ :param queue_name: Name of the target queue.
705
+ :param body: Message body as a Python object.
706
+ :param attributes: Optional message attributes dictionary.
707
+
708
+ :returns: A message identifier string.
709
+ :raises: MessagingError
710
+ """
711
+ with self._lock:
712
+ if queue_name not in self._queues:
713
+ err_msg_lines = [
714
+ "Queue does not exist.",
715
+ " Queue name: {!r}".format(queue_name)
716
+ ]
717
+ err_msg = os.linesep.join(err_msg_lines)
718
+ logger.warning("%s", err_msg)
719
+ raise MessagingError(
720
+ err_msg,
721
+ queue_name=queue_name,
722
+ platform_type=PlatformType.LOCAL
723
+ )
724
+
725
+ message_id = str(uuid.uuid4())
726
+ receipt_handle = str(uuid.uuid4())
727
+ message = QueueMessage(
728
+ identifier=message_id,
729
+ queue_name=queue_name,
730
+ body=body,
731
+ attributes=attributes,
732
+ receipt_handle=receipt_handle,
733
+ timestamp=datetime.utcnow()
734
+ )
735
+ self._queues[queue_name].append(message)
736
+
737
+ rtnval = message_id
738
+ return rtnval
739
+
740
+ def receive_messages(self, queue_name: str, max_count: int = 1,
741
+ wait_time: float = None) -> list:
742
+ """
743
+ Receives messages from the specified in-memory queue.
744
+
745
+ Messages are moved from the queue to a pending set until
746
+ acknowledged. If wait_time is specified and the queue is empty,
747
+ this method will poll briefly before returning.
748
+
749
+ :param queue_name: Name of the source queue.
750
+ :param max_count: Maximum number of messages to receive.
751
+ :param wait_time: Optional wait time in seconds.
752
+
753
+ :returns: A list of QueueMessage objects.
754
+ :raises: MessagingError
755
+ """
756
+ with self._lock:
757
+ if queue_name not in self._queues:
758
+ err_msg_lines = [
759
+ "Queue does not exist.",
760
+ " Queue name: {!r}".format(queue_name)
761
+ ]
762
+ err_msg = os.linesep.join(err_msg_lines)
763
+ logger.warning("%s", err_msg)
764
+ raise MessagingError(
765
+ err_msg,
766
+ queue_name=queue_name,
767
+ platform_type=PlatformType.LOCAL
768
+ )
769
+
770
+ messages = []
771
+ deadline = time.monotonic() + (wait_time if wait_time is not None else 0)
772
+
773
+ while True:
774
+ with self._lock:
775
+ queue = self._queues.get(queue_name)
776
+ if queue is None:
777
+ break
778
+
779
+ while len(messages) < max_count and len(queue) > 0:
780
+ msg = queue.popleft()
781
+ messages.append(msg)
782
+ if queue_name not in self._pending:
783
+ self._pending[queue_name] = {}
784
+ self._pending[queue_name][msg.receipt_handle] = msg
785
+
786
+ if len(messages) >= max_count:
787
+ break
788
+ if time.monotonic() >= deadline:
789
+ break
790
+ time.sleep(0.01)
791
+
792
+ rtnval = messages
793
+ return rtnval
794
+
795
+ def acknowledge_message(self, queue_name: str, receipt_handle: str) -> None:
796
+ """
797
+ Acknowledges a message for deletion from the pending set.
798
+
799
+ :param queue_name: Name of the queue.
800
+ :param receipt_handle: Receipt handle string for the message.
801
+
802
+ :raises: MessagingError
803
+ """
804
+ with self._lock:
805
+ pending_for_queue = self._pending.get(queue_name, {})
806
+ if receipt_handle in pending_for_queue:
807
+ del pending_for_queue[receipt_handle]
808
+
809
+ return
810
+
811
+ def create_queue(self, queue_name: str) -> None:
812
+ """
813
+ Creates an in-memory queue.
814
+
815
+ :param queue_name: Name of the queue to create.
816
+
817
+ :raises: MessagingError
818
+ """
819
+ with self._lock:
820
+ if queue_name not in self._queues:
821
+ self._queues[queue_name] = collections.deque()
822
+ self._pending[queue_name] = {}
823
+
824
+ return
825
+
826
+ def delete_queue(self, queue_name: str) -> None:
827
+ """
828
+ Removes an in-memory queue and its pending messages.
829
+
830
+ :param queue_name: Name of the queue to remove.
831
+
832
+ :raises: MessagingError
833
+ """
834
+ with self._lock:
835
+ if queue_name in self._queues:
836
+ del self._queues[queue_name]
837
+ if queue_name in self._pending:
838
+ del self._pending[queue_name]
839
+
840
+ return
841
+
842
+ def list_queues(self) -> list:
843
+ """
844
+ Returns a list of queue name strings.
845
+
846
+ :returns: List of queue name strings.
847
+ """
848
+ with self._lock:
849
+ rtnval = sorted(list(self._queues.keys()))
850
+
851
+ return rtnval
852
+
853
+ def is_available(self) -> bool:
854
+ """
855
+ Local messaging is always available.
856
+
857
+ :returns: True.
858
+ """
859
+ rtnval = True
860
+ return rtnval
861
+
862
+ def health_check(self) -> bool:
863
+ """
864
+ Local messaging health check always returns True.
865
+
866
+ :returns: True.
867
+ """
868
+ rtnval = True
869
+ return rtnval
870
+
871
+
872
+ # ---------------------------------------------------------------------------
873
+ # LocalPlatformAdapter
874
+ # ---------------------------------------------------------------------------
875
+
876
+ class LocalPlatformAdapter(PlatformAdapter):
877
+ """
878
+ PlatformAdapter implementation providing local environment service
879
+ implementations using subprocess execution, file system storage,
880
+ and in-memory message queuing.
881
+
882
+ :param configuration: The PlatformConfiguration for the local platform.
883
+ """
884
+
885
+ def __init__(self, configuration: PlatformConfiguration) -> None:
886
+ super().__init__(configuration=configuration)
887
+ base_dir = self._resolve_base_directory()
888
+ self._compute_service = LocalComputeService(
889
+ platform_type=PlatformType.LOCAL,
890
+ configuration=configuration,
891
+ default_timeout=30.0
892
+ )
893
+ self._storage_service = LocalStorageService(
894
+ platform_type=PlatformType.LOCAL,
895
+ configuration=configuration,
896
+ base_directory=base_dir
897
+ )
898
+ self._messaging_service = LocalMessagingService(
899
+ platform_type=PlatformType.LOCAL,
900
+ configuration=configuration
901
+ )
902
+ return
903
+
904
+ @property
905
+ def platform_type(self) -> PlatformType:
906
+ """
907
+ Returns PlatformType.LOCAL.
908
+
909
+ :returns: PlatformType.LOCAL.
910
+ """
911
+ rtnval = PlatformType.LOCAL
912
+ return rtnval
913
+
914
+ def get_compute_service(self) -> ComputeService:
915
+ """
916
+ Returns the LocalComputeService instance.
917
+
918
+ :returns: The LocalComputeService.
919
+ """
920
+ rtnval = self._compute_service
921
+ return rtnval
922
+
923
+ def get_storage_service(self) -> StorageService:
924
+ """
925
+ Returns the LocalStorageService instance.
926
+
927
+ :returns: The LocalStorageService.
928
+ """
929
+ rtnval = self._storage_service
930
+ return rtnval
931
+
932
+ def get_messaging_service(self) -> MessagingService:
933
+ """
934
+ Returns the LocalMessagingService instance.
935
+
936
+ :returns: The LocalMessagingService.
937
+ """
938
+ rtnval = self._messaging_service
939
+ return rtnval
940
+
941
+ def _resolve_base_directory(self) -> str:
942
+ """
943
+ Resolves the base directory for local storage from configuration
944
+ options, falling back to a .local-storage directory under the
945
+ current working directory.
946
+
947
+ :returns: The resolved base directory path string.
948
+ """
949
+ if self._configuration is not None:
950
+ options = self._configuration.options
951
+ if "storage_base_directory" in options:
952
+ rtnval = options["storage_base_directory"]
953
+ return rtnval
954
+
955
+ rtnval = os.path.join(os.getcwd(), ".local-storage")
956
+ return rtnval