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,291 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Built-in MemoryStore implementation that persists MemoryEntry objects
|
|
3
|
+
to JSON files on the local file system.
|
|
4
|
+
|
|
5
|
+
Each entry is stored as a separate JSON file using the entry identifier
|
|
6
|
+
as the file name. On construction, existing JSON files in the configured
|
|
7
|
+
directory are loaded into an in-memory index for efficient retrieval
|
|
8
|
+
and search.
|
|
9
|
+
|
|
10
|
+
Suitable for single-agent local deployments where persistence across
|
|
11
|
+
process restarts is required without an external database.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
from typing import Optional
|
|
17
|
+
|
|
18
|
+
from ccai.agentkit.embeddingprovider import EmbeddingProvider
|
|
19
|
+
from ccai.agentkit.errors import SemanticError
|
|
20
|
+
from ccai.agentkit.expirationpolicy import ExpirationPolicy
|
|
21
|
+
from ccai.agentkit.memoryentry import MemoryEntry
|
|
22
|
+
from ccai.agentkit.memoryerrors import MemoryStoreError
|
|
23
|
+
from ccai.agentkit.memoryindex import MemoryIndex
|
|
24
|
+
from ccai.agentkit.memoryquery import MemoryQuery
|
|
25
|
+
from ccai.agentkit.memoryqueryresult import MemoryQueryResult
|
|
26
|
+
from ccai.agentkit.memorystore import MemoryStore
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("ccai.agentkit.memory")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FileMemoryStore(MemoryStore):
|
|
33
|
+
"""
|
|
34
|
+
Built-in MemoryStore implementation that persists MemoryEntry objects
|
|
35
|
+
to JSON files on the local file system. Each entry is stored as a
|
|
36
|
+
separate JSON file using the entry identifier as the file name.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, store_name: str, directory_path: str,
|
|
40
|
+
embedding_provider: EmbeddingProvider = None,
|
|
41
|
+
expiration_policy: ExpirationPolicy = None) -> None:
|
|
42
|
+
"""
|
|
43
|
+
Constructs a FileMemoryStore.
|
|
44
|
+
|
|
45
|
+
:param store_name: The name of this memory store.
|
|
46
|
+
:param directory_path: The directory path for storing JSON files.
|
|
47
|
+
:param embedding_provider: Optional EmbeddingProvider for generating embeddings.
|
|
48
|
+
:param expiration_policy: Optional ExpirationPolicy for entry lifecycle.
|
|
49
|
+
|
|
50
|
+
:raises: SemanticError if store_name is empty.
|
|
51
|
+
:raises: MemoryStoreError if existing entry files cannot be loaded.
|
|
52
|
+
"""
|
|
53
|
+
super().__init__(
|
|
54
|
+
store_name=store_name,
|
|
55
|
+
embedding_provider=embedding_provider,
|
|
56
|
+
expiration_policy=expiration_policy,
|
|
57
|
+
)
|
|
58
|
+
self._directory_path = directory_path
|
|
59
|
+
self._index = MemoryIndex()
|
|
60
|
+
|
|
61
|
+
if not os.path.exists(self._directory_path):
|
|
62
|
+
os.makedirs(self._directory_path, exist_ok=True)
|
|
63
|
+
|
|
64
|
+
self._load_existing_entries()
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def directory_path(self) -> str:
|
|
69
|
+
"""
|
|
70
|
+
The directory path where JSON files are stored.
|
|
71
|
+
|
|
72
|
+
:returns: The directory path string.
|
|
73
|
+
"""
|
|
74
|
+
return self._directory_path
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def count(self) -> int:
|
|
78
|
+
"""
|
|
79
|
+
Returns the count of stored MemoryEntry objects.
|
|
80
|
+
|
|
81
|
+
:returns: The entry count as an integer.
|
|
82
|
+
"""
|
|
83
|
+
rtnval = self._index.count
|
|
84
|
+
return rtnval
|
|
85
|
+
|
|
86
|
+
def _load_existing_entries(self) -> None:
|
|
87
|
+
"""
|
|
88
|
+
Loads all existing MemoryEntry JSON files from the configured
|
|
89
|
+
directory into the in-memory index.
|
|
90
|
+
|
|
91
|
+
:raises: MemoryStoreError if a file cannot be read or parsed.
|
|
92
|
+
"""
|
|
93
|
+
if not os.path.isdir(self._directory_path):
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
for filename in os.listdir(self._directory_path):
|
|
97
|
+
if not filename.endswith(".json"):
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
filepath = os.path.join(self._directory_path, filename)
|
|
101
|
+
try:
|
|
102
|
+
with open(filepath, "r", encoding="utf-8") as fh:
|
|
103
|
+
json_str = fh.read()
|
|
104
|
+
entry = MemoryEntry.from_json(json_str=json_str)
|
|
105
|
+
self._index.add(entry=entry)
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
raise MemoryStoreError(
|
|
108
|
+
store_name=self._store_name,
|
|
109
|
+
operation="load",
|
|
110
|
+
cause=exc,
|
|
111
|
+
) from exc
|
|
112
|
+
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
def _entry_filepath(self, identifier: str) -> str:
|
|
116
|
+
"""
|
|
117
|
+
Returns the file path for a given entry identifier.
|
|
118
|
+
|
|
119
|
+
:param identifier: The entry identifier.
|
|
120
|
+
|
|
121
|
+
:returns: The full file path string.
|
|
122
|
+
"""
|
|
123
|
+
filename = "{}.json".format(identifier)
|
|
124
|
+
rtnval = os.path.join(self._directory_path, filename)
|
|
125
|
+
return rtnval
|
|
126
|
+
|
|
127
|
+
def _write_entry_file(self, entry: MemoryEntry) -> None:
|
|
128
|
+
"""
|
|
129
|
+
Writes a MemoryEntry to a JSON file.
|
|
130
|
+
|
|
131
|
+
:param entry: The MemoryEntry to write.
|
|
132
|
+
|
|
133
|
+
:raises: MemoryStoreError on I/O failure.
|
|
134
|
+
"""
|
|
135
|
+
filepath = self._entry_filepath(identifier=entry.identifier)
|
|
136
|
+
try:
|
|
137
|
+
json_str = entry.to_json()
|
|
138
|
+
with open(filepath, "w", encoding="utf-8") as fh:
|
|
139
|
+
fh.write(json_str)
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
raise MemoryStoreError(
|
|
142
|
+
store_name=self._store_name,
|
|
143
|
+
operation="store",
|
|
144
|
+
cause=exc,
|
|
145
|
+
) from exc
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
def _delete_entry_file(self, identifier: str) -> None:
|
|
149
|
+
"""
|
|
150
|
+
Deletes the JSON file for a given entry identifier.
|
|
151
|
+
|
|
152
|
+
:param identifier: The entry identifier.
|
|
153
|
+
|
|
154
|
+
:raises: MemoryStoreError on I/O failure.
|
|
155
|
+
"""
|
|
156
|
+
filepath = self._entry_filepath(identifier=identifier)
|
|
157
|
+
try:
|
|
158
|
+
if os.path.exists(filepath):
|
|
159
|
+
os.remove(filepath)
|
|
160
|
+
except Exception as exc:
|
|
161
|
+
raise MemoryStoreError(
|
|
162
|
+
store_name=self._store_name,
|
|
163
|
+
operation="delete",
|
|
164
|
+
cause=exc,
|
|
165
|
+
) from exc
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
def store(self, entry: MemoryEntry) -> MemoryEntry:
|
|
169
|
+
"""
|
|
170
|
+
Stores a MemoryEntry as a JSON file and indexes it.
|
|
171
|
+
|
|
172
|
+
:param entry: The MemoryEntry to store.
|
|
173
|
+
|
|
174
|
+
:returns: The stored MemoryEntry (potentially with generated embedding and expiration).
|
|
175
|
+
:raises: SemanticError if a MemoryEntry with the same identifier already exists.
|
|
176
|
+
:raises: MemoryStoreError on I/O failure.
|
|
177
|
+
"""
|
|
178
|
+
if self._index.contains(identifier=entry.identifier):
|
|
179
|
+
errmsg = "A MemoryEntry with identifier {!r} already exists in store {!r}.".format(
|
|
180
|
+
entry.identifier, self._store_name
|
|
181
|
+
)
|
|
182
|
+
raise SemanticError(errmsg)
|
|
183
|
+
|
|
184
|
+
entry = self._apply_expiration_policy(entry=entry)
|
|
185
|
+
entry = self._generate_embedding_if_needed(entry=entry)
|
|
186
|
+
self._write_entry_file(entry=entry)
|
|
187
|
+
self._index.add(entry=entry)
|
|
188
|
+
|
|
189
|
+
logger.info(
|
|
190
|
+
"FileMemoryStore %r stored entry %r with scope %s.",
|
|
191
|
+
self._store_name, entry.identifier, entry.scope.value
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
rtnval = entry
|
|
195
|
+
return rtnval
|
|
196
|
+
|
|
197
|
+
def retrieve(self, identifier: str) -> Optional[MemoryEntry]:
|
|
198
|
+
"""
|
|
199
|
+
Retrieves a MemoryEntry by identifier from the in-memory index.
|
|
200
|
+
|
|
201
|
+
:param identifier: The entry identifier.
|
|
202
|
+
|
|
203
|
+
:returns: The MemoryEntry, or None if not found.
|
|
204
|
+
"""
|
|
205
|
+
rtnval = self._index.get(identifier=identifier)
|
|
206
|
+
return rtnval
|
|
207
|
+
|
|
208
|
+
def search(self, query: MemoryQuery) -> MemoryQueryResult:
|
|
209
|
+
"""
|
|
210
|
+
Executes a MemoryQuery against the in-memory index. When the query
|
|
211
|
+
includes semantic text, generates a query embedding using the
|
|
212
|
+
configured EmbeddingProvider and delegates to the index for
|
|
213
|
+
cosine similarity ranking.
|
|
214
|
+
|
|
215
|
+
:param query: The MemoryQuery with filter criteria.
|
|
216
|
+
|
|
217
|
+
:returns: A MemoryQueryResult with matching entries.
|
|
218
|
+
:raises: MemoryStoreError if semantic search is requested without an EmbeddingProvider.
|
|
219
|
+
"""
|
|
220
|
+
query_embedding = None
|
|
221
|
+
if query.semantic_text is not None:
|
|
222
|
+
if self._embedding_provider is None:
|
|
223
|
+
errmsg = "Semantic search requires an EmbeddingProvider, but none is configured for store {!r}.".format(
|
|
224
|
+
self._store_name
|
|
225
|
+
)
|
|
226
|
+
raise MemoryStoreError(
|
|
227
|
+
store_name=self._store_name,
|
|
228
|
+
operation="search",
|
|
229
|
+
cause=ValueError(errmsg),
|
|
230
|
+
)
|
|
231
|
+
query_embedding = self._embedding_provider.embed(text=query.semantic_text)
|
|
232
|
+
|
|
233
|
+
rtnval = self._index.search(query=query, query_embedding=query_embedding)
|
|
234
|
+
|
|
235
|
+
logger.info(
|
|
236
|
+
"FileMemoryStore %r search returned %d entries.",
|
|
237
|
+
self._store_name, rtnval.total_count
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
return rtnval
|
|
241
|
+
|
|
242
|
+
def update(self, identifier: str, entry: MemoryEntry) -> MemoryEntry:
|
|
243
|
+
"""
|
|
244
|
+
Replaces a MemoryEntry by identifier. Deletes the old file,
|
|
245
|
+
removes from the index, generates an embedding if needed,
|
|
246
|
+
writes the new file, and adds to the index.
|
|
247
|
+
|
|
248
|
+
:param identifier: The identifier of the entry to replace.
|
|
249
|
+
:param entry: The new MemoryEntry.
|
|
250
|
+
|
|
251
|
+
:returns: The updated MemoryEntry.
|
|
252
|
+
:raises: MemoryStoreError on I/O failure.
|
|
253
|
+
"""
|
|
254
|
+
self._delete_entry_file(identifier=identifier)
|
|
255
|
+
self._index.remove(identifier=identifier)
|
|
256
|
+
entry = self._generate_embedding_if_needed(entry=entry)
|
|
257
|
+
self._write_entry_file(entry=entry)
|
|
258
|
+
self._index.add(entry=entry)
|
|
259
|
+
rtnval = entry
|
|
260
|
+
return rtnval
|
|
261
|
+
|
|
262
|
+
def delete(self, identifier: str) -> None:
|
|
263
|
+
"""
|
|
264
|
+
Removes a MemoryEntry by identifier. Deletes the JSON file
|
|
265
|
+
and removes the entry from the in-memory index.
|
|
266
|
+
|
|
267
|
+
:param identifier: The entry identifier to remove.
|
|
268
|
+
|
|
269
|
+
:raises: MemoryStoreError on I/O failure.
|
|
270
|
+
"""
|
|
271
|
+
self._delete_entry_file(identifier=identifier)
|
|
272
|
+
self._index.remove(identifier=identifier)
|
|
273
|
+
|
|
274
|
+
logger.info(
|
|
275
|
+
"FileMemoryStore %r deleted entry %r.",
|
|
276
|
+
self._store_name, identifier
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
return
|
|
280
|
+
|
|
281
|
+
def clear(self) -> None:
|
|
282
|
+
"""
|
|
283
|
+
Removes all entries from the store. Deletes all JSON files
|
|
284
|
+
and clears the in-memory index.
|
|
285
|
+
|
|
286
|
+
:raises: MemoryStoreError on I/O failure.
|
|
287
|
+
"""
|
|
288
|
+
for identifier in list(self._index._entries.keys()):
|
|
289
|
+
self._delete_entry_file(identifier=identifier)
|
|
290
|
+
self._index.clear()
|
|
291
|
+
return
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the HealthCheck abstract base class for health checks.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import abc
|
|
6
|
+
|
|
7
|
+
from ccai.agentkit.healthstatus import HealthStatus
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class HealthCheck(abc.ABC):
|
|
11
|
+
"""
|
|
12
|
+
Abstract base class representing a health check for a specific
|
|
13
|
+
agent component or external dependency.
|
|
14
|
+
|
|
15
|
+
:param name: The name of the health check.
|
|
16
|
+
:param check_interval: The interval between checks in seconds.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, name: str, check_interval: float = 30.0) -> None:
|
|
20
|
+
self._name = name
|
|
21
|
+
self._check_interval = check_interval
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def name(self) -> str:
|
|
26
|
+
return self._name
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def check_interval(self) -> float:
|
|
30
|
+
return self._check_interval
|
|
31
|
+
|
|
32
|
+
@abc.abstractmethod
|
|
33
|
+
def check(self) -> HealthStatus:
|
|
34
|
+
"""
|
|
35
|
+
Performs the health check against the monitored component or dependency.
|
|
36
|
+
|
|
37
|
+
:returns: The health status produced by the check.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __repr__(self) -> str:
|
|
41
|
+
return "{}(name={!r})".format(self.__class__.__name__, self._name)
|
|
42
|
+
|
|
43
|
+
def __str__(self) -> str:
|
|
44
|
+
return "{} name='{}', interval={}s".format(
|
|
45
|
+
self.__class__.__name__, self._name, self._check_interval
|
|
46
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the HealthCheckRegistry for tracking HealthCheck instances.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import List
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from ccai.agentkit.errors import SemanticError
|
|
9
|
+
from ccai.agentkit.healthcheck import HealthCheck
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HealthCheckRegistry:
|
|
13
|
+
"""
|
|
14
|
+
Registry tracking all HealthCheck instances for an Agent.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
self._health_checks = {}
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
def register(self, health_check: HealthCheck) -> None:
|
|
22
|
+
name = health_check.name
|
|
23
|
+
if name in self._health_checks:
|
|
24
|
+
errmsg = "HealthCheck with name '{}' is already registered.".format(name)
|
|
25
|
+
raise SemanticError(errmsg)
|
|
26
|
+
self._health_checks[name] = health_check
|
|
27
|
+
return
|
|
28
|
+
|
|
29
|
+
def deregister(self, name: str) -> None:
|
|
30
|
+
self._health_checks.pop(name, None)
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
def lookup(self, name: str) -> Optional[HealthCheck]:
|
|
34
|
+
return self._health_checks.get(name)
|
|
35
|
+
|
|
36
|
+
def list_all(self) -> List[HealthCheck]:
|
|
37
|
+
return list(self._health_checks.values())
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def count(self) -> int:
|
|
41
|
+
return len(self._health_checks)
|
|
42
|
+
|
|
43
|
+
def has_health_check(self, name: str) -> bool:
|
|
44
|
+
return name in self._health_checks
|
|
45
|
+
|
|
46
|
+
def __repr__(self) -> str:
|
|
47
|
+
return "HealthCheckRegistry(count={})".format(self.count)
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str:
|
|
50
|
+
names = list(self._health_checks.keys())
|
|
51
|
+
return "HealthCheckRegistry: [{}]".format(", ".join(names))
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the HealthMonitor class for periodic health check execution
|
|
3
|
+
and self-healing in the Error Handling & Resilience feature.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from ccai.agentkit.healthcheckregistry import HealthCheckRegistry
|
|
10
|
+
from ccai.agentkit.healthstatus import HealthStatus
|
|
11
|
+
from ccai.agentkit.selfhealingresult import SelfHealingResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HealthMonitor:
|
|
15
|
+
"""
|
|
16
|
+
Periodically executes registered HealthCheck instances and aggregates
|
|
17
|
+
results into an overall agent health status. Triggers self-healing
|
|
18
|
+
actions when unhealthy components are detected.
|
|
19
|
+
|
|
20
|
+
:param health_check_registry: The HealthCheckRegistry to monitor.
|
|
21
|
+
:param check_interval: Default interval between checks in seconds.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, health_check_registry: HealthCheckRegistry,
|
|
25
|
+
check_interval: float = 30.0) -> None:
|
|
26
|
+
self._health_check_registry = health_check_registry
|
|
27
|
+
self._check_interval = check_interval
|
|
28
|
+
self._is_active = False
|
|
29
|
+
self._latest_results = {}
|
|
30
|
+
self._healing_policies = {}
|
|
31
|
+
self._healing_attempt_counts = {}
|
|
32
|
+
self._healing_cooldown_timestamps = {}
|
|
33
|
+
self._logger = logging.getLogger("ccai.agentkit.resilience")
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def is_active(self) -> bool:
|
|
38
|
+
"""
|
|
39
|
+
Whether the monitor is actively running.
|
|
40
|
+
|
|
41
|
+
:returns: Boolean indicating active state.
|
|
42
|
+
"""
|
|
43
|
+
return self._is_active
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def latest_results(self) -> dict:
|
|
47
|
+
"""
|
|
48
|
+
Returns the most recent HealthStatus for each registered check.
|
|
49
|
+
|
|
50
|
+
:returns: Dictionary of check name to HealthStatus.
|
|
51
|
+
"""
|
|
52
|
+
return dict(self._latest_results)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def overall_status(self) -> str:
|
|
56
|
+
"""
|
|
57
|
+
Returns the overall agent health status.
|
|
58
|
+
|
|
59
|
+
Returns "healthy" when all checks are healthy, "degraded" when
|
|
60
|
+
any is degraded but none unhealthy, "unhealthy" when any check
|
|
61
|
+
is unhealthy. Returns "healthy" when no results exist.
|
|
62
|
+
|
|
63
|
+
:returns: Overall status string.
|
|
64
|
+
"""
|
|
65
|
+
if not self._latest_results:
|
|
66
|
+
return "healthy"
|
|
67
|
+
|
|
68
|
+
has_unhealthy = False
|
|
69
|
+
has_degraded = False
|
|
70
|
+
|
|
71
|
+
for status in self._latest_results.values():
|
|
72
|
+
if status.status == "unhealthy":
|
|
73
|
+
has_unhealthy = True
|
|
74
|
+
elif status.status == "degraded":
|
|
75
|
+
has_degraded = True
|
|
76
|
+
|
|
77
|
+
if has_unhealthy:
|
|
78
|
+
return "unhealthy"
|
|
79
|
+
if has_degraded:
|
|
80
|
+
return "degraded"
|
|
81
|
+
return "healthy"
|
|
82
|
+
|
|
83
|
+
def register_healing_policy(self, policy) -> None:
|
|
84
|
+
"""
|
|
85
|
+
Registers a SelfHealingPolicy for a specific health check.
|
|
86
|
+
|
|
87
|
+
:param policy: The SelfHealingPolicy to register.
|
|
88
|
+
"""
|
|
89
|
+
self._healing_policies[policy.check_name] = policy
|
|
90
|
+
return
|
|
91
|
+
|
|
92
|
+
def start(self) -> None:
|
|
93
|
+
"""
|
|
94
|
+
Marks the monitor as active. Actual periodic scheduling is
|
|
95
|
+
handled externally (e.g., by the Agent lifecycle).
|
|
96
|
+
"""
|
|
97
|
+
self._is_active = True
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
def stop(self) -> None:
|
|
101
|
+
"""
|
|
102
|
+
Marks the monitor as inactive.
|
|
103
|
+
"""
|
|
104
|
+
self._is_active = False
|
|
105
|
+
return
|
|
106
|
+
|
|
107
|
+
def check_now(self) -> dict:
|
|
108
|
+
"""
|
|
109
|
+
Immediately executes all registered health checks, triggers
|
|
110
|
+
self-healing for unhealthy checks, and returns the results.
|
|
111
|
+
|
|
112
|
+
:returns: Dictionary of check name to HealthStatus.
|
|
113
|
+
"""
|
|
114
|
+
results = {}
|
|
115
|
+
checks = self._health_check_registry.list_all()
|
|
116
|
+
|
|
117
|
+
for health_check in checks:
|
|
118
|
+
check_name = health_check.name
|
|
119
|
+
status = self._execute_check(health_check)
|
|
120
|
+
results[check_name] = status
|
|
121
|
+
self._latest_results[check_name] = status
|
|
122
|
+
|
|
123
|
+
if status.status == "unhealthy":
|
|
124
|
+
self._logger.warning(
|
|
125
|
+
"Health check '%s' is unhealthy: %s",
|
|
126
|
+
check_name, status.detail
|
|
127
|
+
)
|
|
128
|
+
self._attempt_healing(check_name, status)
|
|
129
|
+
elif status.status == "degraded":
|
|
130
|
+
self._logger.warning(
|
|
131
|
+
"Health check '%s' is degraded: %s",
|
|
132
|
+
check_name, status.detail
|
|
133
|
+
)
|
|
134
|
+
else:
|
|
135
|
+
self._logger.debug(
|
|
136
|
+
"Health check '%s' is healthy", check_name
|
|
137
|
+
)
|
|
138
|
+
self._reset_healing_state(check_name)
|
|
139
|
+
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
def _execute_check(self, health_check) -> HealthStatus:
|
|
143
|
+
"""
|
|
144
|
+
Executes a single health check, catching exceptions as unhealthy.
|
|
145
|
+
|
|
146
|
+
:param health_check: The HealthCheck to execute.
|
|
147
|
+
|
|
148
|
+
:returns: A HealthStatus object.
|
|
149
|
+
"""
|
|
150
|
+
try:
|
|
151
|
+
status = health_check.check()
|
|
152
|
+
return status
|
|
153
|
+
except Exception as exc:
|
|
154
|
+
self._logger.warning(
|
|
155
|
+
"Health check '%s' raised exception: %s",
|
|
156
|
+
health_check.name, exc
|
|
157
|
+
)
|
|
158
|
+
status = HealthStatus(
|
|
159
|
+
check_name=health_check.name,
|
|
160
|
+
status="unhealthy",
|
|
161
|
+
detail="check raised exception: {}".format(str(exc))
|
|
162
|
+
)
|
|
163
|
+
return status
|
|
164
|
+
|
|
165
|
+
def _attempt_healing(self, check_name: str, status: HealthStatus) -> None:
|
|
166
|
+
"""
|
|
167
|
+
Attempts self-healing for an unhealthy check if a policy exists
|
|
168
|
+
and attempt/cooldown limits allow it.
|
|
169
|
+
|
|
170
|
+
:param check_name: The health check name.
|
|
171
|
+
:param status: The unhealthy HealthStatus.
|
|
172
|
+
"""
|
|
173
|
+
if check_name not in self._healing_policies:
|
|
174
|
+
return
|
|
175
|
+
|
|
176
|
+
policy = self._healing_policies[check_name]
|
|
177
|
+
|
|
178
|
+
# Check cooldown
|
|
179
|
+
cooldown_ts = self._healing_cooldown_timestamps.get(check_name)
|
|
180
|
+
if cooldown_ts is not None:
|
|
181
|
+
elapsed = time.monotonic() - cooldown_ts
|
|
182
|
+
if elapsed < policy.cooldown_interval:
|
|
183
|
+
self._logger.debug(
|
|
184
|
+
"Healing for '%s' in cooldown (%.1fs remaining)",
|
|
185
|
+
check_name, policy.cooldown_interval - elapsed
|
|
186
|
+
)
|
|
187
|
+
return
|
|
188
|
+
|
|
189
|
+
# Check attempt count
|
|
190
|
+
attempt_count = self._healing_attempt_counts.get(check_name, 0)
|
|
191
|
+
if attempt_count >= policy.max_attempts:
|
|
192
|
+
self._logger.debug(
|
|
193
|
+
"Healing for '%s' reached max attempts (%d), entering cooldown",
|
|
194
|
+
check_name, policy.max_attempts
|
|
195
|
+
)
|
|
196
|
+
self._healing_cooldown_timestamps[check_name] = time.monotonic()
|
|
197
|
+
self._healing_attempt_counts[check_name] = 0
|
|
198
|
+
return
|
|
199
|
+
|
|
200
|
+
# Execute healing
|
|
201
|
+
self._healing_attempt_counts[check_name] = attempt_count + 1
|
|
202
|
+
healing_result = self._execute_healing(check_name, status, policy)
|
|
203
|
+
|
|
204
|
+
self._logger.info(
|
|
205
|
+
"Self-healing for '%s' with action '%s': success=%s",
|
|
206
|
+
check_name, policy.action.action_name, healing_result.success
|
|
207
|
+
)
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
def _execute_healing(self, check_name: str, status: HealthStatus,
|
|
211
|
+
policy) -> SelfHealingResult:
|
|
212
|
+
"""
|
|
213
|
+
Executes the healing action, catching exceptions as failures.
|
|
214
|
+
|
|
215
|
+
:param check_name: The health check name.
|
|
216
|
+
:param status: The unhealthy HealthStatus.
|
|
217
|
+
:param policy: The SelfHealingPolicy.
|
|
218
|
+
|
|
219
|
+
:returns: A SelfHealingResult.
|
|
220
|
+
"""
|
|
221
|
+
try:
|
|
222
|
+
result = policy.action.heal(check_name, status)
|
|
223
|
+
return result
|
|
224
|
+
except Exception as exc:
|
|
225
|
+
self._logger.warning(
|
|
226
|
+
"Self-healing action '%s' for '%s' raised exception: %s",
|
|
227
|
+
policy.action.action_name, check_name, exc
|
|
228
|
+
)
|
|
229
|
+
result = SelfHealingResult(
|
|
230
|
+
check_name=check_name,
|
|
231
|
+
action_name=policy.action.action_name,
|
|
232
|
+
success=False,
|
|
233
|
+
error_message=str(exc)
|
|
234
|
+
)
|
|
235
|
+
return result
|
|
236
|
+
|
|
237
|
+
def _reset_healing_state(self, check_name: str) -> None:
|
|
238
|
+
"""
|
|
239
|
+
Resets healing attempt count and cooldown for a check that
|
|
240
|
+
has returned to healthy.
|
|
241
|
+
|
|
242
|
+
:param check_name: The health check name.
|
|
243
|
+
"""
|
|
244
|
+
if check_name in self._healing_attempt_counts:
|
|
245
|
+
del self._healing_attempt_counts[check_name]
|
|
246
|
+
if check_name in self._healing_cooldown_timestamps:
|
|
247
|
+
del self._healing_cooldown_timestamps[check_name]
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
def __repr__(self) -> str:
|
|
251
|
+
return "HealthMonitor(active={}, checks={})".format(
|
|
252
|
+
self._is_active, self._health_check_registry.count
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def __str__(self) -> str:
|
|
256
|
+
return "HealthMonitor active={}, checks={}, overall={}".format(
|
|
257
|
+
self._is_active, self._health_check_registry.count, self.overall_status
|
|
258
|
+
)
|