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.
- ccai/agentkit/__init__.py +304 -0
- ccai/agentkit/addressresolver.py +177 -0
- ccai/agentkit/agent.py +2945 -0
- ccai/agentkit/agentaddress.py +187 -0
- ccai/agentkit/agentconfiguration.py +581 -0
- ccai/agentkit/agentidentity.py +152 -0
- ccai/agentkit/agentregistry.py +221 -0
- ccai/agentkit/agentstatemachine.py +134 -0
- ccai/agentkit/alternateproviderstrategy.py +36 -0
- ccai/agentkit/approvalgate.py +238 -0
- ccai/agentkit/approvalrequest.py +250 -0
- ccai/agentkit/asyncagent.py +187 -0
- ccai/agentkit/breakpoint.py +150 -0
- ccai/agentkit/builtinagentmetrics.py +114 -0
- ccai/agentkit/builtins/__init__.py +11 -0
- ccai/agentkit/builtins/filereadtool.py +90 -0
- ccai/agentkit/builtins/filewritetool.py +93 -0
- ccai/agentkit/builtins/httprequesttool.py +169 -0
- ccai/agentkit/builtins/shellcommandtool.py +190 -0
- ccai/agentkit/cachedresultstrategy.py +43 -0
- ccai/agentkit/checkpointmanager.py +219 -0
- ccai/agentkit/circuitbreaker.py +230 -0
- ccai/agentkit/circuitbreakerconfiguration.py +158 -0
- ccai/agentkit/circuitbreakerevent.py +158 -0
- ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
- ccai/agentkit/circuitbreakerregistry.py +116 -0
- ccai/agentkit/circuitbreakerstate.py +44 -0
- ccai/agentkit/clearcacheaction.py +46 -0
- ccai/agentkit/concurrencybridge.py +143 -0
- ccai/agentkit/concurrencymodel.py +19 -0
- ccai/agentkit/conditionevaluator.py +594 -0
- ccai/agentkit/configurationchangeevent.py +179 -0
- ccai/agentkit/configurationerrors.py +152 -0
- ccai/agentkit/configurationlayer.py +160 -0
- ccai/agentkit/configurationlayersource.py +46 -0
- ccai/agentkit/configurationmanager.py +680 -0
- ccai/agentkit/configurationschema.py +224 -0
- ccai/agentkit/configurationschemafield.py +217 -0
- ccai/agentkit/configurationserializer.py +163 -0
- ccai/agentkit/configurationvalidationresult.py +118 -0
- ccai/agentkit/contextsummarizer.py +170 -0
- ccai/agentkit/contextwindow.py +264 -0
- ccai/agentkit/contextwindowstrategy.py +57 -0
- ccai/agentkit/correlationcontext.py +156 -0
- ccai/agentkit/costestimate.py +139 -0
- ccai/agentkit/costtracker.py +121 -0
- ccai/agentkit/deadletterentry.py +134 -0
- ccai/agentkit/deadletterquery.py +119 -0
- ccai/agentkit/deadletterqueue.py +123 -0
- ccai/agentkit/deadletterstore.py +86 -0
- ccai/agentkit/debuginspector.py +211 -0
- ccai/agentkit/debugsession.py +223 -0
- ccai/agentkit/defaultvaluestrategy.py +43 -0
- ccai/agentkit/degradationchangeevent.py +120 -0
- ccai/agentkit/degradationlevel.py +44 -0
- ccai/agentkit/degradationmanager.py +212 -0
- ccai/agentkit/degradationpolicy.py +130 -0
- ccai/agentkit/degradationstrategy.py +66 -0
- ccai/agentkit/embeddingprovider.py +106 -0
- ccai/agentkit/errors.py +95 -0
- ccai/agentkit/executionrecord.py +213 -0
- ccai/agentkit/executionrecorder.py +180 -0
- ccai/agentkit/executionrecording.py +230 -0
- ccai/agentkit/executionreplayer.py +187 -0
- ccai/agentkit/expirationpolicy.py +116 -0
- ccai/agentkit/fallbackchain.py +82 -0
- ccai/agentkit/featureflag.py +154 -0
- ccai/agentkit/featureflagevaluator.py +109 -0
- ccai/agentkit/featureflagregistry.py +258 -0
- ccai/agentkit/filedeadletterstore.py +112 -0
- ccai/agentkit/filememorystore.py +291 -0
- ccai/agentkit/healthcheck.py +46 -0
- ccai/agentkit/healthcheckregistry.py +51 -0
- ccai/agentkit/healthmonitor.py +258 -0
- ccai/agentkit/healthstatus.py +105 -0
- ccai/agentkit/hotreloadmonitor.py +214 -0
- ccai/agentkit/hotreloadpolicy.py +160 -0
- ccai/agentkit/inmemorydeadletterstore.py +61 -0
- ccai/agentkit/inmemorystore.py +173 -0
- ccai/agentkit/jsonmessageserializer.py +89 -0
- ccai/agentkit/jsonoutputparser.py +50 -0
- ccai/agentkit/lifecyclestate.py +22 -0
- ccai/agentkit/llmconversation.py +153 -0
- ccai/agentkit/llmerrors.py +193 -0
- ccai/agentkit/llmmessage.py +158 -0
- ccai/agentkit/llmprovider.py +158 -0
- ccai/agentkit/llmproviderregistry.py +200 -0
- ccai/agentkit/llmresponse.py +190 -0
- ccai/agentkit/llmstreamchunk.py +65 -0
- ccai/agentkit/llmstreamhandler.py +48 -0
- ccai/agentkit/llmtoolbridge.py +154 -0
- ccai/agentkit/logexporter.py +316 -0
- ccai/agentkit/logformatter.py +169 -0
- ccai/agentkit/memoryconfiguration.py +243 -0
- ccai/agentkit/memoryentry.py +254 -0
- ccai/agentkit/memoryerrors.py +135 -0
- ccai/agentkit/memoryindex.py +213 -0
- ccai/agentkit/memoryquery.py +248 -0
- ccai/agentkit/memoryqueryresult.py +86 -0
- ccai/agentkit/memoryscope.py +54 -0
- ccai/agentkit/memorystore.py +260 -0
- ccai/agentkit/memorystorehealthcheck.py +33 -0
- ccai/agentkit/memorystoreregistry.py +106 -0
- ccai/agentkit/message.py +310 -0
- ccai/agentkit/messageenvelope.py +144 -0
- ccai/agentkit/messagepattern.py +50 -0
- ccai/agentkit/messagerouter.py +290 -0
- ccai/agentkit/messageserializer.py +106 -0
- ccai/agentkit/messageserializerregistry.py +163 -0
- ccai/agentkit/messagingconfiguration.py +397 -0
- ccai/agentkit/messagingerrors.py +338 -0
- ccai/agentkit/metricdefinition.py +164 -0
- ccai/agentkit/metricmeasurement.py +178 -0
- ccai/agentkit/metricscollector.py +258 -0
- ccai/agentkit/metricsexporter.py +303 -0
- ccai/agentkit/metricsregistry.py +130 -0
- ccai/agentkit/metricssnapshot.py +155 -0
- ccai/agentkit/metrictype.py +51 -0
- ccai/agentkit/msgpackmessageserializer.py +97 -0
- ccai/agentkit/observabilityconfiguration.py +546 -0
- ccai/agentkit/observabilityerror.py +67 -0
- ccai/agentkit/observabilitypipeline.py +252 -0
- ccai/agentkit/outputparser.py +82 -0
- ccai/agentkit/outputschema.py +142 -0
- ccai/agentkit/parallelbranch.py +87 -0
- ccai/agentkit/platform/__init__.py +43 -0
- ccai/agentkit/platform/adapters/__init__.py +18 -0
- ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
- ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
- ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
- ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
- ccai/agentkit/platform/adapters/platformadapter.py +139 -0
- ccai/agentkit/platform/deployment/__init__.py +15 -0
- ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
- ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
- ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
- ccai/agentkit/platform/errors.py +224 -0
- ccai/agentkit/platform/platformconfiguration.py +412 -0
- ccai/agentkit/platform/platformdetector.py +125 -0
- ccai/agentkit/platform/platformruntime.py +331 -0
- ccai/agentkit/platform/platformserviceregistry.py +149 -0
- ccai/agentkit/platform/platformtype.py +60 -0
- ccai/agentkit/platform/services/__init__.py +19 -0
- ccai/agentkit/platform/services/computeservice.py +112 -0
- ccai/agentkit/platform/services/invocationresult.py +173 -0
- ccai/agentkit/platform/services/messagingservice.py +135 -0
- ccai/agentkit/platform/services/platformservice.py +111 -0
- ccai/agentkit/platform/services/queuemessage.py +193 -0
- ccai/agentkit/platform/services/storageobject.py +195 -0
- ccai/agentkit/platform/services/storageservice.py +159 -0
- ccai/agentkit/pluginconfiguration.py +241 -0
- ccai/agentkit/plugindependency.py +129 -0
- ccai/agentkit/plugindescriptor.py +225 -0
- ccai/agentkit/pluginlifecyclehook.py +41 -0
- ccai/agentkit/pluginmanager.py +360 -0
- ccai/agentkit/pluginstatus.py +47 -0
- ccai/agentkit/pooledagent.py +116 -0
- ccai/agentkit/prompttemplate.py +221 -0
- ccai/agentkit/prompttemplateregistry.py +145 -0
- ccai/agentkit/protobufmessageserializer.py +144 -0
- ccai/agentkit/pubsubbroker.py +311 -0
- ccai/agentkit/py.typed +0 -0
- ccai/agentkit/reconnecttransportaction.py +47 -0
- ccai/agentkit/regexoutputparser.py +68 -0
- ccai/agentkit/requestresponsehandler.py +274 -0
- ccai/agentkit/resetcircuitbreakeraction.py +48 -0
- ccai/agentkit/resilienceconfiguration.py +191 -0
- ccai/agentkit/resilienceerrors.py +103 -0
- ccai/agentkit/resiliencepipeline.py +201 -0
- ccai/agentkit/retryattempt.py +158 -0
- ccai/agentkit/retryexecutor.py +157 -0
- ccai/agentkit/retrypolicy.py +195 -0
- ccai/agentkit/retryresult.py +186 -0
- ccai/agentkit/selfhealingaction.py +42 -0
- ccai/agentkit/selfhealingpolicy.py +67 -0
- ccai/agentkit/selfhealingresult.py +130 -0
- ccai/agentkit/stepexecutionstatus.py +52 -0
- ccai/agentkit/stepresult.py +198 -0
- ccai/agentkit/steps/__init__.py +9 -0
- ccai/agentkit/steps/agentstep.py +247 -0
- ccai/agentkit/steps/approvalstep.py +276 -0
- ccai/agentkit/steps/llmstep.py +403 -0
- ccai/agentkit/steps/subworkflowstep.py +270 -0
- ccai/agentkit/steps/toolstep.py +265 -0
- ccai/agentkit/structuredlogentry.py +222 -0
- ccai/agentkit/structuredlogger.py +189 -0
- ccai/agentkit/subscription.py +141 -0
- ccai/agentkit/threadedagent.py +94 -0
- ccai/agentkit/tokenusage.py +136 -0
- ccai/agentkit/tool.py +203 -0
- ccai/agentkit/toolchain.py +268 -0
- ccai/agentkit/toolchainexecutor.py +134 -0
- ccai/agentkit/toolchainresult.py +166 -0
- ccai/agentkit/tooldescriptor.py +203 -0
- ccai/agentkit/toolerrors.py +160 -0
- ccai/agentkit/toolexecutor.py +168 -0
- ccai/agentkit/toolfactory.py +60 -0
- ccai/agentkit/toolregistry.py +184 -0
- ccai/agentkit/toolresult.py +142 -0
- ccai/agentkit/toolschema.py +197 -0
- ccai/agentkit/tracecontext.py +294 -0
- ccai/agentkit/traceevent.py +166 -0
- ccai/agentkit/traceexporter.py +305 -0
- ccai/agentkit/tracer.py +234 -0
- ccai/agentkit/tracespan.py +349 -0
- ccai/agentkit/transitionrecord.py +84 -0
- ccai/agentkit/transport.py +334 -0
- ccai/agentkit/transportconfiguration.py +436 -0
- ccai/agentkit/transporthealthcheck.py +36 -0
- ccai/agentkit/transportregistry.py +224 -0
- ccai/agentkit/transports/__init__.py +28 -0
- ccai/agentkit/transports/grpctransport.py +410 -0
- ccai/agentkit/transports/httptransport.py +423 -0
- ccai/agentkit/transports/messagequeuetransport.py +489 -0
- ccai/agentkit/transports/websockettransport.py +473 -0
- ccai/agentkit/workflowcheckpoint.py +208 -0
- ccai/agentkit/workflowconfiguration.py +295 -0
- ccai/agentkit/workflowcontext.py +249 -0
- ccai/agentkit/workflowdefinition.py +790 -0
- ccai/agentkit/workflowedge.py +128 -0
- ccai/agentkit/workflowerrors.py +295 -0
- ccai/agentkit/workflowexecutionstatus.py +48 -0
- ccai/agentkit/workflowexecutor.py +1121 -0
- ccai/agentkit/workflowregistry.py +185 -0
- ccai/agentkit/workflowresult.py +250 -0
- ccai/agentkit/workflowstep.py +195 -0
- codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
- codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
- codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the ConfigurationManager class that manages the complete
|
|
3
|
+
configuration lifecycle for an Agent in the codecraftai-agent-kit framework.
|
|
4
|
+
|
|
5
|
+
The ConfigurationManager coordinates hierarchical configuration loading,
|
|
6
|
+
schema validation, change notification, and hot-reload monitoring.
|
|
7
|
+
It maintains an ordered list of ConfigurationLayer objects merged in
|
|
8
|
+
ascending priority order where higher-priority layers override
|
|
9
|
+
lower-priority values.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
from datetime import timezone
|
|
19
|
+
|
|
20
|
+
from ccai.agentkit.configurationchangeevent import ConfigurationChangeEvent
|
|
21
|
+
from ccai.agentkit.configurationerrors import ConfigurationValidationError
|
|
22
|
+
from ccai.agentkit.configurationlayer import ConfigurationLayer
|
|
23
|
+
from ccai.agentkit.configurationlayersource import ConfigurationLayerSource
|
|
24
|
+
from ccai.agentkit.errors import ConfigurationError
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import yaml
|
|
28
|
+
YAML_AVAILABLE = True
|
|
29
|
+
except ImportError:
|
|
30
|
+
YAML_AVAILABLE = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
PRIORITY_DEFAULTS = 0
|
|
34
|
+
PRIORITY_FILE = 100
|
|
35
|
+
PRIORITY_ENVIRONMENT = 200
|
|
36
|
+
PRIORITY_RUNTIME = 300
|
|
37
|
+
PRIORITY_OVERRIDE = 400
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigurationManager:
|
|
41
|
+
"""
|
|
42
|
+
Manages the complete configuration lifecycle for an Agent.
|
|
43
|
+
|
|
44
|
+
Coordinates hierarchical configuration loading, schema validation,
|
|
45
|
+
change notification, and hot-reload monitoring. Maintains an ordered
|
|
46
|
+
list of ConfigurationLayer objects merged in ascending priority order.
|
|
47
|
+
|
|
48
|
+
:param agent_identifier: The identifier string for the agent.
|
|
49
|
+
:param schema: An optional ConfigurationSchema for validation.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, agent_identifier: str, schema=None) -> None:
|
|
53
|
+
self._agent_identifier = agent_identifier
|
|
54
|
+
self._schema = schema
|
|
55
|
+
self._layers = []
|
|
56
|
+
self._merged_configuration = {}
|
|
57
|
+
self._change_listeners = []
|
|
58
|
+
self._logger = logging.getLogger("ccai.agentkit.configuration")
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def agent_identifier(self) -> str:
|
|
63
|
+
"""
|
|
64
|
+
The identifier string for the agent.
|
|
65
|
+
|
|
66
|
+
:returns: The agent identifier string.
|
|
67
|
+
"""
|
|
68
|
+
return self._agent_identifier
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def schema(self):
|
|
72
|
+
"""
|
|
73
|
+
The optional ConfigurationSchema used for validation.
|
|
74
|
+
|
|
75
|
+
:returns: The ConfigurationSchema instance, or None.
|
|
76
|
+
"""
|
|
77
|
+
return self._schema
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def merged_configuration(self) -> dict:
|
|
81
|
+
"""
|
|
82
|
+
A defensive copy of the merged configuration dictionary.
|
|
83
|
+
|
|
84
|
+
:returns: A deep copy of the merged configuration dictionary.
|
|
85
|
+
"""
|
|
86
|
+
result = copy.deepcopy(self._merged_configuration)
|
|
87
|
+
return result
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def layers(self) -> list:
|
|
91
|
+
"""
|
|
92
|
+
A defensive copy of the list of ConfigurationLayer objects
|
|
93
|
+
in priority order.
|
|
94
|
+
|
|
95
|
+
:returns: A list of ConfigurationLayer objects.
|
|
96
|
+
"""
|
|
97
|
+
result = list(self._layers)
|
|
98
|
+
return result
|
|
99
|
+
|
|
100
|
+
def get(self, field_path: str, default=None):
|
|
101
|
+
"""
|
|
102
|
+
Returns the resolved configuration value at the given dot-separated
|
|
103
|
+
field path, or the default value when not found.
|
|
104
|
+
|
|
105
|
+
:param field_path: Dot-separated path string.
|
|
106
|
+
:param default: Value to return when the field path is not found.
|
|
107
|
+
|
|
108
|
+
:returns: The resolved configuration value or default.
|
|
109
|
+
"""
|
|
110
|
+
value = self._resolve_field_path(self._merged_configuration, field_path)
|
|
111
|
+
|
|
112
|
+
if value is None:
|
|
113
|
+
return default
|
|
114
|
+
|
|
115
|
+
return value
|
|
116
|
+
|
|
117
|
+
def set(self, field_path: str, value) -> None:
|
|
118
|
+
"""
|
|
119
|
+
Stores a value in the RUNTIME ConfigurationLayer at the given
|
|
120
|
+
field path. Creates a RUNTIME layer if one does not exist.
|
|
121
|
+
Re-merges configuration, detects changes, and notifies listeners.
|
|
122
|
+
|
|
123
|
+
:param field_path: Dot-separated path string.
|
|
124
|
+
:param value: The value to store.
|
|
125
|
+
"""
|
|
126
|
+
runtime_layer = self._find_runtime_layer()
|
|
127
|
+
|
|
128
|
+
if runtime_layer is None:
|
|
129
|
+
runtime_config = {}
|
|
130
|
+
self._set_nested_value(runtime_config, field_path, value)
|
|
131
|
+
|
|
132
|
+
runtime_layer = ConfigurationLayer(
|
|
133
|
+
name="runtime",
|
|
134
|
+
priority=PRIORITY_RUNTIME,
|
|
135
|
+
source=ConfigurationLayerSource.RUNTIME,
|
|
136
|
+
configuration=runtime_config
|
|
137
|
+
)
|
|
138
|
+
self._layers.append(runtime_layer)
|
|
139
|
+
else:
|
|
140
|
+
layer_config = runtime_layer.configuration
|
|
141
|
+
self._set_nested_value(layer_config, field_path, value)
|
|
142
|
+
|
|
143
|
+
layer_index = self._layers.index(runtime_layer)
|
|
144
|
+
updated_layer = ConfigurationLayer(
|
|
145
|
+
name=runtime_layer.name,
|
|
146
|
+
priority=runtime_layer.priority,
|
|
147
|
+
source=runtime_layer.source,
|
|
148
|
+
configuration=layer_config
|
|
149
|
+
)
|
|
150
|
+
self._layers[layer_index] = updated_layer
|
|
151
|
+
|
|
152
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
153
|
+
self._merge_layers()
|
|
154
|
+
self._validate_if_schema_present()
|
|
155
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.RUNTIME)
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
def load_defaults(self, defaults: dict) -> None:
|
|
159
|
+
"""
|
|
160
|
+
Loads default configuration values as the lowest-priority layer.
|
|
161
|
+
|
|
162
|
+
:param defaults: Dictionary of default configuration values.
|
|
163
|
+
"""
|
|
164
|
+
layer = ConfigurationLayer(
|
|
165
|
+
name="defaults",
|
|
166
|
+
priority=PRIORITY_DEFAULTS,
|
|
167
|
+
source=ConfigurationLayerSource.DEFAULTS,
|
|
168
|
+
configuration=defaults
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
172
|
+
self._layers.append(layer)
|
|
173
|
+
self._merge_layers()
|
|
174
|
+
self._validate_if_schema_present()
|
|
175
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.DEFAULTS)
|
|
176
|
+
return
|
|
177
|
+
|
|
178
|
+
def load_from_dict(self, data: dict, layer_name: str = None) -> None:
|
|
179
|
+
"""
|
|
180
|
+
Loads configuration from a dictionary as a RUNTIME layer.
|
|
181
|
+
|
|
182
|
+
:param data: Configuration dictionary.
|
|
183
|
+
:param layer_name: Optional layer name.
|
|
184
|
+
"""
|
|
185
|
+
if layer_name is None:
|
|
186
|
+
layer_name = "dict-runtime"
|
|
187
|
+
|
|
188
|
+
layer = ConfigurationLayer(
|
|
189
|
+
name=layer_name,
|
|
190
|
+
priority=PRIORITY_RUNTIME,
|
|
191
|
+
source=ConfigurationLayerSource.RUNTIME,
|
|
192
|
+
configuration=data
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
196
|
+
self._layers.append(layer)
|
|
197
|
+
self._merge_layers()
|
|
198
|
+
self._validate_if_schema_present()
|
|
199
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.RUNTIME)
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
def load_from_file(self, file_path: str) -> None:
|
|
203
|
+
"""
|
|
204
|
+
Loads configuration from a JSON or YAML file as a FILE layer.
|
|
205
|
+
Raises ConfigurationError for missing files or invalid syntax.
|
|
206
|
+
|
|
207
|
+
:param file_path: Path to the configuration file.
|
|
208
|
+
|
|
209
|
+
:raises ConfigurationError: If the file does not exist or contains
|
|
210
|
+
invalid syntax.
|
|
211
|
+
"""
|
|
212
|
+
if os.path.isfile(file_path) is False:
|
|
213
|
+
errmsg = "Configuration file not found: '{}'".format(file_path)
|
|
214
|
+
raise ConfigurationError(errmsg)
|
|
215
|
+
|
|
216
|
+
file_extension = os.path.splitext(file_path)[1].lower()
|
|
217
|
+
|
|
218
|
+
if file_extension == ".json":
|
|
219
|
+
data = self._load_json_file(file_path)
|
|
220
|
+
elif file_extension in (".yaml", ".yml"):
|
|
221
|
+
data = self._load_yaml_file(file_path)
|
|
222
|
+
else:
|
|
223
|
+
errmsg = "Unsupported configuration file format: '{}'. Supported formats: .json, .yaml, .yml".format(
|
|
224
|
+
file_extension
|
|
225
|
+
)
|
|
226
|
+
raise ConfigurationError(errmsg)
|
|
227
|
+
|
|
228
|
+
layer_name = os.path.basename(file_path)
|
|
229
|
+
layer = ConfigurationLayer(
|
|
230
|
+
name=layer_name,
|
|
231
|
+
priority=PRIORITY_FILE,
|
|
232
|
+
source=ConfigurationLayerSource.FILE,
|
|
233
|
+
configuration=data
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
237
|
+
self._layers.append(layer)
|
|
238
|
+
self._merge_layers()
|
|
239
|
+
self._validate_if_schema_present()
|
|
240
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.FILE)
|
|
241
|
+
return
|
|
242
|
+
|
|
243
|
+
def load_from_environment(self, prefix: str = None) -> None:
|
|
244
|
+
"""
|
|
245
|
+
Loads configuration from environment variables as an ENVIRONMENT layer.
|
|
246
|
+
Strips the prefix and converts underscores to dots for field paths.
|
|
247
|
+
|
|
248
|
+
:param prefix: Optional prefix to filter environment variables.
|
|
249
|
+
"""
|
|
250
|
+
env_config = {}
|
|
251
|
+
|
|
252
|
+
for env_key, env_value in os.environ.items():
|
|
253
|
+
if prefix is not None:
|
|
254
|
+
if env_key.startswith(prefix) is False:
|
|
255
|
+
continue
|
|
256
|
+
|
|
257
|
+
stripped_key = env_key[len(prefix):]
|
|
258
|
+
else:
|
|
259
|
+
stripped_key = env_key
|
|
260
|
+
|
|
261
|
+
field_path = stripped_key.replace("_", ".").lower()
|
|
262
|
+
|
|
263
|
+
if len(field_path) > 0:
|
|
264
|
+
self._set_nested_value(env_config, field_path, env_value)
|
|
265
|
+
|
|
266
|
+
layer_name = "environment"
|
|
267
|
+
if prefix is not None:
|
|
268
|
+
layer_name = "environment-{}".format(prefix)
|
|
269
|
+
|
|
270
|
+
layer = ConfigurationLayer(
|
|
271
|
+
name=layer_name,
|
|
272
|
+
priority=PRIORITY_ENVIRONMENT,
|
|
273
|
+
source=ConfigurationLayerSource.ENVIRONMENT,
|
|
274
|
+
configuration=env_config
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
278
|
+
self._layers.append(layer)
|
|
279
|
+
self._merge_layers()
|
|
280
|
+
self._validate_if_schema_present()
|
|
281
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.ENVIRONMENT)
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
def reload(self) -> None:
|
|
285
|
+
"""
|
|
286
|
+
Re-reads all file-based and environment-based layers and re-merges.
|
|
287
|
+
Detects changes and notifies listeners. Logs at INFO level.
|
|
288
|
+
"""
|
|
289
|
+
self._logger.info("Reloading configuration for agent '%s'", self._agent_identifier)
|
|
290
|
+
|
|
291
|
+
old_merged = copy.deepcopy(self._merged_configuration)
|
|
292
|
+
reloaded_layers = []
|
|
293
|
+
|
|
294
|
+
for layer in self._layers:
|
|
295
|
+
if layer.source is ConfigurationLayerSource.FILE:
|
|
296
|
+
reloaded_layer = self._reload_file_layer(layer)
|
|
297
|
+
reloaded_layers.append(reloaded_layer)
|
|
298
|
+
elif layer.source is ConfigurationLayerSource.ENVIRONMENT:
|
|
299
|
+
reloaded_layer = self._reload_environment_layer(layer)
|
|
300
|
+
reloaded_layers.append(reloaded_layer)
|
|
301
|
+
else:
|
|
302
|
+
reloaded_layers.append(layer)
|
|
303
|
+
|
|
304
|
+
self._layers = reloaded_layers
|
|
305
|
+
self._merge_layers()
|
|
306
|
+
self._detect_and_notify_changes(old_merged, self._merged_configuration, ConfigurationLayerSource.RUNTIME)
|
|
307
|
+
|
|
308
|
+
self._logger.info("Configuration reload complete for agent '%s'", self._agent_identifier)
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
def register_change_listener(self, listener) -> None:
|
|
312
|
+
"""
|
|
313
|
+
Registers a ConfigurationChangeListener callback.
|
|
314
|
+
|
|
315
|
+
:param listener: Callable that accepts a ConfigurationChangeEvent.
|
|
316
|
+
"""
|
|
317
|
+
self._change_listeners.append(listener)
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
def deregister_change_listener(self, listener) -> None:
|
|
321
|
+
"""
|
|
322
|
+
Deregisters a previously registered ConfigurationChangeListener.
|
|
323
|
+
|
|
324
|
+
:param listener: The listener to remove.
|
|
325
|
+
"""
|
|
326
|
+
if listener in self._change_listeners:
|
|
327
|
+
self._change_listeners.remove(listener)
|
|
328
|
+
|
|
329
|
+
return
|
|
330
|
+
|
|
331
|
+
# ---- Private Helper Methods ----
|
|
332
|
+
|
|
333
|
+
def _find_runtime_layer(self):
|
|
334
|
+
"""
|
|
335
|
+
Finds the first RUNTIME layer in the layers list.
|
|
336
|
+
|
|
337
|
+
:returns: The ConfigurationLayer with RUNTIME source, or None.
|
|
338
|
+
"""
|
|
339
|
+
for layer in self._layers:
|
|
340
|
+
if layer.source is ConfigurationLayerSource.RUNTIME:
|
|
341
|
+
if layer.name == "runtime":
|
|
342
|
+
return layer
|
|
343
|
+
|
|
344
|
+
return None
|
|
345
|
+
|
|
346
|
+
def _merge_layers(self) -> None:
|
|
347
|
+
"""
|
|
348
|
+
Merges all layers in ascending priority order. Higher-priority
|
|
349
|
+
layers override lower-priority values using deep dictionary merge.
|
|
350
|
+
"""
|
|
351
|
+
sorted_layers = sorted(self._layers, key=lambda layer: layer.priority)
|
|
352
|
+
merged = {}
|
|
353
|
+
|
|
354
|
+
for layer in sorted_layers:
|
|
355
|
+
self._deep_merge(merged, layer.configuration)
|
|
356
|
+
|
|
357
|
+
self._merged_configuration = merged
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
def _deep_merge(self, base: dict, override: dict) -> None:
|
|
361
|
+
"""
|
|
362
|
+
Recursively merges the override dictionary into the base dictionary.
|
|
363
|
+
Nested dictionaries are merged recursively; other values are overwritten.
|
|
364
|
+
|
|
365
|
+
:param base: The base dictionary to merge into.
|
|
366
|
+
:param override: The override dictionary to merge from.
|
|
367
|
+
"""
|
|
368
|
+
for key, value in override.items():
|
|
369
|
+
if key in base and isinstance(base[key], dict) is True and isinstance(value, dict) is True:
|
|
370
|
+
self._deep_merge(base[key], value)
|
|
371
|
+
else:
|
|
372
|
+
base[key] = value
|
|
373
|
+
|
|
374
|
+
return
|
|
375
|
+
|
|
376
|
+
def _resolve_field_path(self, configuration: dict, field_path: str):
|
|
377
|
+
"""
|
|
378
|
+
Traverses a configuration dictionary using a dot-separated field path.
|
|
379
|
+
|
|
380
|
+
:param configuration: The configuration dictionary to traverse.
|
|
381
|
+
:param field_path: The dot-separated path string.
|
|
382
|
+
|
|
383
|
+
:returns: The resolved value, or None if not found.
|
|
384
|
+
"""
|
|
385
|
+
parts = field_path.split(".")
|
|
386
|
+
current = configuration
|
|
387
|
+
|
|
388
|
+
for part in parts:
|
|
389
|
+
if isinstance(current, dict) is False:
|
|
390
|
+
return None
|
|
391
|
+
|
|
392
|
+
if part not in current:
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
current = current[part]
|
|
396
|
+
|
|
397
|
+
return current
|
|
398
|
+
|
|
399
|
+
def _set_nested_value(self, configuration: dict, field_path: str, value) -> None:
|
|
400
|
+
"""
|
|
401
|
+
Sets a value in a nested dictionary using a dot-separated field path.
|
|
402
|
+
Creates intermediate dictionaries as needed.
|
|
403
|
+
|
|
404
|
+
:param configuration: The configuration dictionary to modify.
|
|
405
|
+
:param field_path: The dot-separated path string.
|
|
406
|
+
:param value: The value to set.
|
|
407
|
+
"""
|
|
408
|
+
parts = field_path.split(".")
|
|
409
|
+
current = configuration
|
|
410
|
+
|
|
411
|
+
for part in parts[:-1]:
|
|
412
|
+
if part not in current:
|
|
413
|
+
current[part] = {}
|
|
414
|
+
elif isinstance(current[part], dict) is False:
|
|
415
|
+
current[part] = {}
|
|
416
|
+
|
|
417
|
+
current = current[part]
|
|
418
|
+
|
|
419
|
+
last_part = parts[-1]
|
|
420
|
+
current[last_part] = value
|
|
421
|
+
return
|
|
422
|
+
|
|
423
|
+
def _validate_if_schema_present(self) -> None:
|
|
424
|
+
"""
|
|
425
|
+
Validates the merged configuration against the schema if a schema
|
|
426
|
+
is provided. Raises ConfigurationValidationError if validation fails.
|
|
427
|
+
Logs validation failures at WARNING level.
|
|
428
|
+
|
|
429
|
+
:raises ConfigurationValidationError: If validation fails.
|
|
430
|
+
"""
|
|
431
|
+
if self._schema is None:
|
|
432
|
+
return
|
|
433
|
+
|
|
434
|
+
validation_result = self._schema.validate(self._merged_configuration)
|
|
435
|
+
|
|
436
|
+
if validation_result.is_valid is False:
|
|
437
|
+
self._logger.warning(
|
|
438
|
+
"Configuration validation failed for agent '%s' against schema '%s' with %d error(s)",
|
|
439
|
+
self._agent_identifier,
|
|
440
|
+
self._schema.name,
|
|
441
|
+
len(validation_result.errors)
|
|
442
|
+
)
|
|
443
|
+
raise ConfigurationValidationError(
|
|
444
|
+
schema_name=self._schema.name,
|
|
445
|
+
errors=validation_result.errors,
|
|
446
|
+
warnings=validation_result.warnings
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
return
|
|
450
|
+
|
|
451
|
+
def _detect_and_notify_changes(self, old_config: dict, new_config: dict,
|
|
452
|
+
source: ConfigurationLayerSource) -> None:
|
|
453
|
+
"""
|
|
454
|
+
Compares old and new merged configurations, creates
|
|
455
|
+
ConfigurationChangeEvent for each changed field, and notifies
|
|
456
|
+
all registered listeners.
|
|
457
|
+
|
|
458
|
+
:param old_config: The previous merged configuration.
|
|
459
|
+
:param new_config: The new merged configuration.
|
|
460
|
+
:param source: The ConfigurationLayerSource that triggered the change.
|
|
461
|
+
"""
|
|
462
|
+
changes = []
|
|
463
|
+
self._collect_changes(old_config, new_config, "", changes)
|
|
464
|
+
|
|
465
|
+
timestamp = datetime.now(tz=timezone.utc)
|
|
466
|
+
|
|
467
|
+
for field_path, previous_value, new_value in changes:
|
|
468
|
+
event = ConfigurationChangeEvent(
|
|
469
|
+
field_path=field_path,
|
|
470
|
+
previous_value=previous_value,
|
|
471
|
+
new_value=new_value,
|
|
472
|
+
source=source,
|
|
473
|
+
timestamp=timestamp
|
|
474
|
+
)
|
|
475
|
+
self._notify_listeners(event)
|
|
476
|
+
|
|
477
|
+
return
|
|
478
|
+
|
|
479
|
+
def _collect_changes(self, old_config: dict, new_config: dict,
|
|
480
|
+
prefix: str, changes: list) -> None:
|
|
481
|
+
"""
|
|
482
|
+
Recursively collects changed fields between old and new configurations.
|
|
483
|
+
|
|
484
|
+
:param old_config: The previous configuration dictionary.
|
|
485
|
+
:param new_config: The new configuration dictionary.
|
|
486
|
+
:param prefix: The current dot-separated path prefix.
|
|
487
|
+
:param changes: The list to append (field_path, old_value, new_value) tuples to.
|
|
488
|
+
"""
|
|
489
|
+
all_keys = set()
|
|
490
|
+
|
|
491
|
+
if isinstance(old_config, dict) is True:
|
|
492
|
+
all_keys.update(old_config.keys())
|
|
493
|
+
|
|
494
|
+
if isinstance(new_config, dict) is True:
|
|
495
|
+
all_keys.update(new_config.keys())
|
|
496
|
+
|
|
497
|
+
for key in sorted(all_keys):
|
|
498
|
+
if len(prefix) > 0:
|
|
499
|
+
field_path = "{}.{}".format(prefix, key)
|
|
500
|
+
else:
|
|
501
|
+
field_path = key
|
|
502
|
+
|
|
503
|
+
old_value = old_config.get(key) if isinstance(old_config, dict) is True else None
|
|
504
|
+
new_value = new_config.get(key) if isinstance(new_config, dict) is True else None
|
|
505
|
+
|
|
506
|
+
if isinstance(old_value, dict) is True and isinstance(new_value, dict) is True:
|
|
507
|
+
self._collect_changes(old_value, new_value, field_path, changes)
|
|
508
|
+
elif old_value != new_value:
|
|
509
|
+
changes.append((field_path, old_value, new_value))
|
|
510
|
+
|
|
511
|
+
return
|
|
512
|
+
|
|
513
|
+
def _notify_listeners(self, event: ConfigurationChangeEvent) -> None:
|
|
514
|
+
"""
|
|
515
|
+
Invokes all registered change listeners with the given event.
|
|
516
|
+
Catches exceptions from listeners, logs at WARNING level, and
|
|
517
|
+
continues invoking remaining listeners.
|
|
518
|
+
|
|
519
|
+
:param event: The ConfigurationChangeEvent to pass to listeners.
|
|
520
|
+
"""
|
|
521
|
+
for listener in self._change_listeners:
|
|
522
|
+
try:
|
|
523
|
+
listener(event)
|
|
524
|
+
except Exception as listener_exc:
|
|
525
|
+
self._logger.warning(
|
|
526
|
+
"Change listener exception for agent '%s' on field '%s': %s",
|
|
527
|
+
self._agent_identifier,
|
|
528
|
+
event.field_path,
|
|
529
|
+
str(listener_exc)
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
return
|
|
533
|
+
|
|
534
|
+
def _load_json_file(self, file_path: str) -> dict:
|
|
535
|
+
"""
|
|
536
|
+
Loads and parses a JSON configuration file.
|
|
537
|
+
|
|
538
|
+
:param file_path: Path to the JSON file.
|
|
539
|
+
|
|
540
|
+
:returns: The parsed configuration dictionary.
|
|
541
|
+
|
|
542
|
+
:raises ConfigurationError: If the file contains invalid JSON.
|
|
543
|
+
"""
|
|
544
|
+
try:
|
|
545
|
+
with open(file_path, "r", encoding="utf-8") as file_handle:
|
|
546
|
+
data = json.load(file_handle)
|
|
547
|
+
except json.JSONDecodeError as json_err:
|
|
548
|
+
errmsg = "Invalid JSON syntax in configuration file '{}': {}".format(
|
|
549
|
+
file_path, str(json_err)
|
|
550
|
+
)
|
|
551
|
+
raise ConfigurationError(errmsg, cause=json_err)
|
|
552
|
+
|
|
553
|
+
return data
|
|
554
|
+
|
|
555
|
+
def _load_yaml_file(self, file_path: str) -> dict:
|
|
556
|
+
"""
|
|
557
|
+
Loads and parses a YAML configuration file.
|
|
558
|
+
|
|
559
|
+
:param file_path: Path to the YAML file.
|
|
560
|
+
|
|
561
|
+
:returns: The parsed configuration dictionary.
|
|
562
|
+
|
|
563
|
+
:raises ConfigurationError: If YAML is not available or the file
|
|
564
|
+
contains invalid YAML.
|
|
565
|
+
"""
|
|
566
|
+
if YAML_AVAILABLE is False:
|
|
567
|
+
errmsg = "YAML support is not available. Install PyYAML to load YAML configuration files."
|
|
568
|
+
raise ConfigurationError(errmsg)
|
|
569
|
+
|
|
570
|
+
try:
|
|
571
|
+
with open(file_path, "r", encoding="utf-8") as file_handle:
|
|
572
|
+
data = yaml.safe_load(file_handle)
|
|
573
|
+
except yaml.YAMLError as yaml_err:
|
|
574
|
+
errmsg = "Invalid YAML syntax in configuration file '{}': {}".format(
|
|
575
|
+
file_path, str(yaml_err)
|
|
576
|
+
)
|
|
577
|
+
raise ConfigurationError(errmsg, cause=yaml_err)
|
|
578
|
+
|
|
579
|
+
if data is None:
|
|
580
|
+
data = {}
|
|
581
|
+
|
|
582
|
+
return data
|
|
583
|
+
|
|
584
|
+
def _reload_file_layer(self, layer: ConfigurationLayer) -> ConfigurationLayer:
|
|
585
|
+
"""
|
|
586
|
+
Re-reads a file-based configuration layer from disk.
|
|
587
|
+
|
|
588
|
+
:param layer: The existing FILE layer to reload.
|
|
589
|
+
|
|
590
|
+
:returns: A new ConfigurationLayer with the re-read configuration.
|
|
591
|
+
"""
|
|
592
|
+
file_path = layer.name
|
|
593
|
+
file_extension = os.path.splitext(file_path)[1].lower()
|
|
594
|
+
|
|
595
|
+
try:
|
|
596
|
+
if file_extension == ".json":
|
|
597
|
+
data = self._load_json_file(file_path)
|
|
598
|
+
elif file_extension in (".yaml", ".yml"):
|
|
599
|
+
data = self._load_yaml_file(file_path)
|
|
600
|
+
else:
|
|
601
|
+
data = layer.configuration
|
|
602
|
+
except ConfigurationError:
|
|
603
|
+
self._logger.warning(
|
|
604
|
+
"Failed to reload file layer '%s' for agent '%s', retaining previous configuration",
|
|
605
|
+
layer.name, self._agent_identifier
|
|
606
|
+
)
|
|
607
|
+
data = layer.configuration
|
|
608
|
+
|
|
609
|
+
reloaded_layer = ConfigurationLayer(
|
|
610
|
+
name=layer.name,
|
|
611
|
+
priority=layer.priority,
|
|
612
|
+
source=layer.source,
|
|
613
|
+
configuration=data
|
|
614
|
+
)
|
|
615
|
+
return reloaded_layer
|
|
616
|
+
|
|
617
|
+
def _reload_environment_layer(self, layer: ConfigurationLayer) -> ConfigurationLayer:
|
|
618
|
+
"""
|
|
619
|
+
Re-reads an environment-based configuration layer from os.environ.
|
|
620
|
+
|
|
621
|
+
:param layer: The existing ENVIRONMENT layer to reload.
|
|
622
|
+
|
|
623
|
+
:returns: A new ConfigurationLayer with the re-read configuration.
|
|
624
|
+
"""
|
|
625
|
+
layer_name = layer.name
|
|
626
|
+
prefix = None
|
|
627
|
+
|
|
628
|
+
if layer_name.startswith("environment-"):
|
|
629
|
+
prefix = layer_name[len("environment-"):]
|
|
630
|
+
|
|
631
|
+
env_config = {}
|
|
632
|
+
|
|
633
|
+
for env_key, env_value in os.environ.items():
|
|
634
|
+
if prefix is not None:
|
|
635
|
+
if env_key.startswith(prefix) is False:
|
|
636
|
+
continue
|
|
637
|
+
|
|
638
|
+
stripped_key = env_key[len(prefix):]
|
|
639
|
+
else:
|
|
640
|
+
stripped_key = env_key
|
|
641
|
+
|
|
642
|
+
field_path = stripped_key.replace("_", ".").lower()
|
|
643
|
+
|
|
644
|
+
if len(field_path) > 0:
|
|
645
|
+
self._set_nested_value(env_config, field_path, env_value)
|
|
646
|
+
|
|
647
|
+
reloaded_layer = ConfigurationLayer(
|
|
648
|
+
name=layer.name,
|
|
649
|
+
priority=layer.priority,
|
|
650
|
+
source=layer.source,
|
|
651
|
+
configuration=env_config
|
|
652
|
+
)
|
|
653
|
+
return reloaded_layer
|
|
654
|
+
|
|
655
|
+
def __repr__(self) -> str:
|
|
656
|
+
"""
|
|
657
|
+
Returns a detailed string representation including class name,
|
|
658
|
+
agent identifier, and layer count.
|
|
659
|
+
|
|
660
|
+
:returns: A repr string for debugging.
|
|
661
|
+
"""
|
|
662
|
+
layer_count = len(self._layers)
|
|
663
|
+
repr_str = "ConfigurationManager(agent_identifier={!r}, layer_count={})".format(
|
|
664
|
+
self._agent_identifier, layer_count
|
|
665
|
+
)
|
|
666
|
+
return repr_str
|
|
667
|
+
|
|
668
|
+
def __str__(self) -> str:
|
|
669
|
+
"""
|
|
670
|
+
Returns a human-readable summary including the agent identifier,
|
|
671
|
+
layer count, and whether a schema is configured.
|
|
672
|
+
|
|
673
|
+
:returns: A human-readable string.
|
|
674
|
+
"""
|
|
675
|
+
layer_count = len(self._layers)
|
|
676
|
+
has_schema = self._schema is not None
|
|
677
|
+
str_val = "ConfigurationManager for agent '{}' ({} layers, schema={})".format(
|
|
678
|
+
self._agent_identifier, layer_count, has_schema
|
|
679
|
+
)
|
|
680
|
+
return str_val
|