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,190 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Built-in tool for executing shell commands.
|
|
3
|
+
|
|
4
|
+
Provides the ShellCommandTool class which executes a shell command
|
|
5
|
+
using subprocess and returns the exit code, stdout, and stderr.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import shlex
|
|
10
|
+
import subprocess
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.tool import Tool
|
|
13
|
+
from ccai.agentkit.toolerrors import ToolExecutionError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ShellCommandTool(Tool):
|
|
17
|
+
"""
|
|
18
|
+
Executes a shell command and returns the output.
|
|
19
|
+
|
|
20
|
+
Accepts a required command parameter, and optional working_directory,
|
|
21
|
+
timeout_seconds, environment, and safe_mode parameters. Returns the
|
|
22
|
+
exit code, stdout, and stderr. Raises ToolExecutionError for timeout,
|
|
23
|
+
missing working directory, and shell metacharacter rejection in safe mode.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
TOOL_NAME = "shell_command"
|
|
27
|
+
TOOL_DESCRIPTION = "Executes a shell command and returns the output."
|
|
28
|
+
TOOL_VERSION = "1.0.0"
|
|
29
|
+
|
|
30
|
+
INPUT_SCHEMA = {
|
|
31
|
+
"parameters": [
|
|
32
|
+
{
|
|
33
|
+
"name": "command",
|
|
34
|
+
"type": "string",
|
|
35
|
+
"required": True,
|
|
36
|
+
"description": "Shell command to execute.",
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"name": "working_directory",
|
|
40
|
+
"type": "string",
|
|
41
|
+
"required": False,
|
|
42
|
+
"description": "Working directory for command execution.",
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"name": "timeout_seconds",
|
|
46
|
+
"type": "float",
|
|
47
|
+
"required": False,
|
|
48
|
+
"default": 60.0,
|
|
49
|
+
"description": "Command timeout in seconds.",
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"name": "environment",
|
|
53
|
+
"type": "dictionary",
|
|
54
|
+
"required": False,
|
|
55
|
+
"description": "Additional environment variables.",
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"name": "safe_mode",
|
|
59
|
+
"type": "boolean",
|
|
60
|
+
"required": False,
|
|
61
|
+
"default": True,
|
|
62
|
+
"description": "Reject commands with shell metacharacters.",
|
|
63
|
+
},
|
|
64
|
+
]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
OUTPUT_SCHEMA = {
|
|
68
|
+
"parameters": [
|
|
69
|
+
{
|
|
70
|
+
"name": "exit_code",
|
|
71
|
+
"type": "integer",
|
|
72
|
+
"required": True,
|
|
73
|
+
"description": "Process exit code.",
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"name": "stdout",
|
|
77
|
+
"type": "string",
|
|
78
|
+
"required": True,
|
|
79
|
+
"description": "Standard output.",
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"name": "stderr",
|
|
83
|
+
"type": "string",
|
|
84
|
+
"required": True,
|
|
85
|
+
"description": "Standard error.",
|
|
86
|
+
},
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
SHELL_METACHARACTERS = set(";|&$`\\!#~")
|
|
91
|
+
|
|
92
|
+
def execute(self, inputs: dict, credentials: dict = None) -> dict:
|
|
93
|
+
"""
|
|
94
|
+
Executes the shell command specified by the inputs.
|
|
95
|
+
|
|
96
|
+
:param inputs: Dictionary containing 'command' and optional
|
|
97
|
+
'working_directory', 'timeout_seconds', 'environment', 'safe_mode'.
|
|
98
|
+
:param credentials: Optional dictionary of resolved credentials (unused).
|
|
99
|
+
|
|
100
|
+
:returns: A dictionary with 'exit_code', 'stdout', and 'stderr' keys.
|
|
101
|
+
|
|
102
|
+
:raises: ToolExecutionError
|
|
103
|
+
"""
|
|
104
|
+
command = inputs["command"]
|
|
105
|
+
working_directory = inputs.get("working_directory", None)
|
|
106
|
+
timeout_seconds = inputs.get("timeout_seconds", 60.0)
|
|
107
|
+
environment = inputs.get("environment", None)
|
|
108
|
+
safe_mode = inputs.get("safe_mode", True)
|
|
109
|
+
|
|
110
|
+
if safe_mode is True:
|
|
111
|
+
self._check_metacharacters(command=command)
|
|
112
|
+
|
|
113
|
+
if working_directory is not None:
|
|
114
|
+
if os.path.isdir(working_directory) is not True:
|
|
115
|
+
err_msg_lines = [
|
|
116
|
+
"Working directory does not exist: '{}'.".format(working_directory),
|
|
117
|
+
]
|
|
118
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
119
|
+
raise ToolExecutionError(
|
|
120
|
+
tool_name=self.TOOL_NAME,
|
|
121
|
+
cause=FileNotFoundError(err_msg),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
merged_env = None
|
|
125
|
+
if environment is not None:
|
|
126
|
+
merged_env = dict(os.environ)
|
|
127
|
+
merged_env.update(environment)
|
|
128
|
+
|
|
129
|
+
command_parts = shlex.split(command)
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
completed = subprocess.run(
|
|
133
|
+
command_parts,
|
|
134
|
+
cwd=working_directory,
|
|
135
|
+
env=merged_env,
|
|
136
|
+
timeout=timeout_seconds,
|
|
137
|
+
capture_output=True,
|
|
138
|
+
)
|
|
139
|
+
except subprocess.TimeoutExpired as timeout_err:
|
|
140
|
+
err_msg_lines = [
|
|
141
|
+
"Shell command timed out.",
|
|
142
|
+
"COMMAND: {}".format(command),
|
|
143
|
+
"TIMEOUT: {} seconds".format(timeout_seconds),
|
|
144
|
+
]
|
|
145
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
146
|
+
raise ToolExecutionError(
|
|
147
|
+
tool_name=self.TOOL_NAME,
|
|
148
|
+
cause=TimeoutError(err_msg),
|
|
149
|
+
) from timeout_err
|
|
150
|
+
|
|
151
|
+
exit_code = completed.returncode
|
|
152
|
+
stdout = completed.stdout.decode("utf-8")
|
|
153
|
+
stderr = completed.stderr.decode("utf-8")
|
|
154
|
+
|
|
155
|
+
rtnval = {
|
|
156
|
+
"exit_code": exit_code,
|
|
157
|
+
"stdout": stdout,
|
|
158
|
+
"stderr": stderr,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return rtnval
|
|
162
|
+
|
|
163
|
+
def _check_metacharacters(self, command: str) -> None:
|
|
164
|
+
"""
|
|
165
|
+
Checks the command string for shell metacharacters and raises
|
|
166
|
+
ToolExecutionError if any are found.
|
|
167
|
+
|
|
168
|
+
:param command: The command string to check.
|
|
169
|
+
|
|
170
|
+
:raises: ToolExecutionError
|
|
171
|
+
"""
|
|
172
|
+
found_chars = []
|
|
173
|
+
|
|
174
|
+
for char in command:
|
|
175
|
+
if char in self.SHELL_METACHARACTERS:
|
|
176
|
+
found_chars.append(char)
|
|
177
|
+
|
|
178
|
+
if len(found_chars) > 0:
|
|
179
|
+
err_msg_lines = [
|
|
180
|
+
"Command contains shell metacharacters and safe_mode is enabled.",
|
|
181
|
+
"COMMAND: {}".format(command),
|
|
182
|
+
"METACHARACTERS FOUND: {}".format(", ".join(found_chars)),
|
|
183
|
+
]
|
|
184
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
185
|
+
raise ToolExecutionError(
|
|
186
|
+
tool_name=self.TOOL_NAME,
|
|
187
|
+
cause=ValueError(err_msg),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
return
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the CachedResultStrategy for returning cached successful results
|
|
3
|
+
when a dependency is unavailable.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from ccai.agentkit.degradationstrategy import DegradationStrategy
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CachedResultStrategy(DegradationStrategy):
|
|
12
|
+
"""
|
|
13
|
+
Returns the most recently cached successful result for the dependency
|
|
14
|
+
when the dependency is unavailable.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
super().__init__("cached_result")
|
|
19
|
+
self._cache = {}
|
|
20
|
+
return
|
|
21
|
+
|
|
22
|
+
def cache_result(self, dependency_name: str, result) -> None:
|
|
23
|
+
"""
|
|
24
|
+
Caches a successful result for a dependency.
|
|
25
|
+
|
|
26
|
+
:param dependency_name: The dependency name.
|
|
27
|
+
:param result: The result to cache.
|
|
28
|
+
"""
|
|
29
|
+
self._cache[dependency_name] = result
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
def degrade(self, dependency_name: str, exception: Exception,
|
|
33
|
+
context: Optional[dict] = None):
|
|
34
|
+
"""
|
|
35
|
+
Returns the most recently cached result for the dependency.
|
|
36
|
+
|
|
37
|
+
:param dependency_name: Name of the unavailable dependency.
|
|
38
|
+
:param exception: The exception that triggered degradation.
|
|
39
|
+
:param context: Optional context dictionary.
|
|
40
|
+
|
|
41
|
+
:returns: The cached result or None if no cache exists.
|
|
42
|
+
"""
|
|
43
|
+
return self._cache.get(dependency_name)
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the CheckpointManager class responsible for persisting
|
|
3
|
+
and restoring WorkflowExecution state at configurable checkpoint
|
|
4
|
+
boundaries using a MemoryStore backend.
|
|
5
|
+
|
|
6
|
+
The CheckpointManager serializes WorkflowCheckpoint objects to
|
|
7
|
+
JSON and stores them as MemoryEntry objects in the MemoryStore.
|
|
8
|
+
It provides save, load, list, and delete operations for
|
|
9
|
+
checkpoint management.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
from ccai.agentkit.memoryentry import MemoryEntry
|
|
15
|
+
from ccai.agentkit.memoryquery import MemoryQuery
|
|
16
|
+
from ccai.agentkit.memoryscope import MemoryScope
|
|
17
|
+
from ccai.agentkit.workflowcheckpoint import WorkflowCheckpoint
|
|
18
|
+
from ccai.agentkit.workflowcontext import WorkflowContext
|
|
19
|
+
from ccai.agentkit.workflowerrors import WorkflowCheckpointError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CheckpointManager:
|
|
23
|
+
"""
|
|
24
|
+
Persists and restores WorkflowExecution state at configurable
|
|
25
|
+
checkpoint boundaries using a MemoryStore backend.
|
|
26
|
+
|
|
27
|
+
The CheckpointManager uses a MemoryStore to persist
|
|
28
|
+
WorkflowCheckpoint objects as MemoryEntry instances. Each
|
|
29
|
+
checkpoint is serialized to JSON and stored with the
|
|
30
|
+
execution identifier as the entry identifier. Checkpoints
|
|
31
|
+
are tagged with the workflow name for efficient lookup.
|
|
32
|
+
|
|
33
|
+
:param memory_store: The MemoryStore instance used for
|
|
34
|
+
persisting checkpoint data.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, memory_store) -> None:
|
|
38
|
+
self._memory_store = memory_store
|
|
39
|
+
self._logger = logging.getLogger("ccai.agentkit.workflow.checkpoint")
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
def save_checkpoint(self, execution_id: str, context: WorkflowContext,
|
|
43
|
+
completed_step_ids: set, current_step_id: str) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Persists a WorkflowCheckpoint to the MemoryStore.
|
|
46
|
+
|
|
47
|
+
Creates a WorkflowCheckpoint from the provided execution
|
|
48
|
+
state, serializes it to JSON, and stores it as a
|
|
49
|
+
MemoryEntry in the MemoryStore. The execution identifier
|
|
50
|
+
is used as the MemoryEntry identifier for direct
|
|
51
|
+
retrieval.
|
|
52
|
+
|
|
53
|
+
:param execution_id: The unique identifier of the
|
|
54
|
+
workflow execution.
|
|
55
|
+
:param context: The current WorkflowContext containing
|
|
56
|
+
inputs, step outputs, and metadata.
|
|
57
|
+
:param completed_step_ids: The set of step identifiers
|
|
58
|
+
that have completed execution.
|
|
59
|
+
:param current_step_id: The identifier of the step
|
|
60
|
+
that is currently executing or about to execute.
|
|
61
|
+
|
|
62
|
+
:raises: WorkflowCheckpointError when the save
|
|
63
|
+
operation fails.
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
context_state = context.as_dict()
|
|
67
|
+
workflow_name = context.get_metadata("workflow_name", "unknown")
|
|
68
|
+
|
|
69
|
+
checkpoint = WorkflowCheckpoint(
|
|
70
|
+
workflow_name=workflow_name,
|
|
71
|
+
execution_id=execution_id,
|
|
72
|
+
completed_step_ids=completed_step_ids,
|
|
73
|
+
context_state=context_state,
|
|
74
|
+
current_step_id=current_step_id
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
checkpoint_json = checkpoint.to_json()
|
|
78
|
+
|
|
79
|
+
entry = MemoryEntry(
|
|
80
|
+
content=checkpoint_json,
|
|
81
|
+
scope=MemoryScope.AGENT,
|
|
82
|
+
identifier=execution_id,
|
|
83
|
+
metadata={
|
|
84
|
+
"type": "workflow_checkpoint",
|
|
85
|
+
"workflow_name": workflow_name,
|
|
86
|
+
"execution_id": execution_id
|
|
87
|
+
},
|
|
88
|
+
tags=["workflow_checkpoint", workflow_name]
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if self._memory_store.contains(execution_id):
|
|
92
|
+
self._memory_store.update(execution_id, entry)
|
|
93
|
+
else:
|
|
94
|
+
self._memory_store.store(entry)
|
|
95
|
+
|
|
96
|
+
completed_count = len(completed_step_ids)
|
|
97
|
+
self._logger.info(
|
|
98
|
+
"Checkpoint saved for workflow '%s', execution '%s', "
|
|
99
|
+
"%d completed steps.",
|
|
100
|
+
workflow_name, execution_id, completed_count
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
except WorkflowCheckpointError:
|
|
104
|
+
raise
|
|
105
|
+
except Exception as ex:
|
|
106
|
+
raise WorkflowCheckpointError(
|
|
107
|
+
execution_id=execution_id,
|
|
108
|
+
operation="save",
|
|
109
|
+
cause=ex
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
def load_checkpoint(self, execution_id: str) -> WorkflowCheckpoint:
|
|
115
|
+
"""
|
|
116
|
+
Returns the most recent WorkflowCheckpoint for the
|
|
117
|
+
execution, or None when no checkpoint exists.
|
|
118
|
+
|
|
119
|
+
Retrieves the MemoryEntry by execution identifier and
|
|
120
|
+
deserializes the checkpoint JSON content back into a
|
|
121
|
+
WorkflowCheckpoint instance.
|
|
122
|
+
|
|
123
|
+
:param execution_id: The unique identifier of the
|
|
124
|
+
workflow execution.
|
|
125
|
+
|
|
126
|
+
:returns: A WorkflowCheckpoint instance or None when
|
|
127
|
+
no checkpoint exists for the execution.
|
|
128
|
+
|
|
129
|
+
:raises: WorkflowCheckpointError when the load
|
|
130
|
+
operation fails.
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
entry = self._memory_store.retrieve(execution_id)
|
|
134
|
+
|
|
135
|
+
if entry is None:
|
|
136
|
+
rtnval = None
|
|
137
|
+
return rtnval
|
|
138
|
+
|
|
139
|
+
rtnval = WorkflowCheckpoint.from_json(entry.content)
|
|
140
|
+
return rtnval
|
|
141
|
+
|
|
142
|
+
except WorkflowCheckpointError:
|
|
143
|
+
raise
|
|
144
|
+
except Exception as ex:
|
|
145
|
+
raise WorkflowCheckpointError(
|
|
146
|
+
execution_id=execution_id,
|
|
147
|
+
operation="load",
|
|
148
|
+
cause=ex
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def list_checkpoints(self, workflow_name: str) -> list:
|
|
152
|
+
"""
|
|
153
|
+
Returns checkpoints for the workflow, ordered by
|
|
154
|
+
timestamp descending.
|
|
155
|
+
|
|
156
|
+
Searches the MemoryStore for entries tagged with the
|
|
157
|
+
workflow name and the workflow_checkpoint tag, then
|
|
158
|
+
deserializes each entry into a WorkflowCheckpoint and
|
|
159
|
+
sorts by timestamp descending.
|
|
160
|
+
|
|
161
|
+
:param workflow_name: The name of the workflow whose
|
|
162
|
+
checkpoints to list.
|
|
163
|
+
|
|
164
|
+
:returns: A list of WorkflowCheckpoint objects ordered
|
|
165
|
+
by timestamp descending.
|
|
166
|
+
"""
|
|
167
|
+
query = MemoryQuery(
|
|
168
|
+
tags=["workflow_checkpoint", workflow_name]
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
result = self._memory_store.search(query)
|
|
172
|
+
|
|
173
|
+
checkpoints = []
|
|
174
|
+
for entry in result.entries:
|
|
175
|
+
checkpoint = WorkflowCheckpoint.from_json(entry.content)
|
|
176
|
+
checkpoints.append(checkpoint)
|
|
177
|
+
|
|
178
|
+
checkpoints.sort(key=lambda cp: cp.timestamp, reverse=True)
|
|
179
|
+
|
|
180
|
+
rtnval = checkpoints
|
|
181
|
+
return rtnval
|
|
182
|
+
|
|
183
|
+
def delete_checkpoint(self, execution_id: str) -> None:
|
|
184
|
+
"""
|
|
185
|
+
Removes all checkpoints for the execution from the
|
|
186
|
+
MemoryStore.
|
|
187
|
+
|
|
188
|
+
:param execution_id: The unique identifier of the
|
|
189
|
+
workflow execution whose checkpoints to remove.
|
|
190
|
+
"""
|
|
191
|
+
if self._memory_store.contains(execution_id):
|
|
192
|
+
self._memory_store.delete(execution_id)
|
|
193
|
+
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
def __repr__(self) -> str:
|
|
197
|
+
"""
|
|
198
|
+
Returns a detailed string representation including the
|
|
199
|
+
class name and the MemoryStore name.
|
|
200
|
+
|
|
201
|
+
:returns: A repr string for debugging.
|
|
202
|
+
"""
|
|
203
|
+
store_name = getattr(self._memory_store, "store_name", "unknown")
|
|
204
|
+
repr_str = "{}(memory_store={!r})".format(
|
|
205
|
+
self.__class__.__name__, store_name
|
|
206
|
+
)
|
|
207
|
+
return repr_str
|
|
208
|
+
|
|
209
|
+
def __str__(self) -> str:
|
|
210
|
+
"""
|
|
211
|
+
Returns a human-readable summary including the
|
|
212
|
+
MemoryStore name.
|
|
213
|
+
|
|
214
|
+
:returns: A human-readable string describing the
|
|
215
|
+
checkpoint manager.
|
|
216
|
+
"""
|
|
217
|
+
store_name = getattr(self._memory_store, "store_name", "unknown")
|
|
218
|
+
str_val = "CheckpointManager: store={}".format(store_name)
|
|
219
|
+
return str_val
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the CircuitBreaker class for monitoring failure rates and
|
|
3
|
+
preventing cascading failures in the Error Handling & Resilience feature.
|
|
4
|
+
|
|
5
|
+
The CircuitBreaker transitions between CLOSED, OPEN, and HALF_OPEN states
|
|
6
|
+
based on failure and success thresholds. Thread-safe via threading.Lock.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from ccai.agentkit.circuitbreakerconfiguration import CircuitBreakerConfiguration
|
|
14
|
+
from ccai.agentkit.circuitbreakerevent import CircuitBreakerEvent
|
|
15
|
+
from ccai.agentkit.circuitbreakerstate import CircuitBreakerState
|
|
16
|
+
from ccai.agentkit.resilienceerrors import CircuitBreakerOpenError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CircuitBreaker:
|
|
20
|
+
"""
|
|
21
|
+
Monitors the success and failure rate of operations directed at an
|
|
22
|
+
external service and transitions between CLOSED, OPEN, and HALF_OPEN
|
|
23
|
+
states.
|
|
24
|
+
|
|
25
|
+
:param name: The circuit breaker name.
|
|
26
|
+
:param configuration: The CircuitBreakerConfiguration.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, name: str, configuration: CircuitBreakerConfiguration) -> None:
|
|
30
|
+
self._name = name
|
|
31
|
+
self._configuration = configuration
|
|
32
|
+
self._state = CircuitBreakerState.CLOSED
|
|
33
|
+
self._failure_count = 0
|
|
34
|
+
self._success_count = 0
|
|
35
|
+
self._half_open_attempt_count = 0
|
|
36
|
+
self._open_timestamp = None
|
|
37
|
+
self._events = []
|
|
38
|
+
self._lock = threading.Lock()
|
|
39
|
+
self._logger = logging.getLogger("ccai.agentkit.resilience")
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def name(self) -> str:
|
|
44
|
+
"""
|
|
45
|
+
The circuit breaker name.
|
|
46
|
+
|
|
47
|
+
:returns: The name string.
|
|
48
|
+
"""
|
|
49
|
+
return self._name
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def state(self) -> CircuitBreakerState:
|
|
53
|
+
"""
|
|
54
|
+
The current CircuitBreakerState.
|
|
55
|
+
|
|
56
|
+
:returns: The current state.
|
|
57
|
+
"""
|
|
58
|
+
with self._lock:
|
|
59
|
+
return self._state
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def failure_count(self) -> int:
|
|
63
|
+
"""
|
|
64
|
+
The current failure count.
|
|
65
|
+
|
|
66
|
+
:returns: The failure count as an integer.
|
|
67
|
+
"""
|
|
68
|
+
with self._lock:
|
|
69
|
+
return self._failure_count
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def success_count(self) -> int:
|
|
73
|
+
"""
|
|
74
|
+
The current success count.
|
|
75
|
+
|
|
76
|
+
:returns: The success count as an integer.
|
|
77
|
+
"""
|
|
78
|
+
with self._lock:
|
|
79
|
+
return self._success_count
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def events(self) -> list:
|
|
83
|
+
"""
|
|
84
|
+
The list of recorded CircuitBreakerEvent objects.
|
|
85
|
+
|
|
86
|
+
:returns: A list of CircuitBreakerEvent instances.
|
|
87
|
+
"""
|
|
88
|
+
with self._lock:
|
|
89
|
+
return list(self._events)
|
|
90
|
+
|
|
91
|
+
def execute(self, callable_op, *args, **kwargs):
|
|
92
|
+
"""
|
|
93
|
+
Evaluates the current state and either executes the callable or
|
|
94
|
+
rejects the request.
|
|
95
|
+
|
|
96
|
+
:param callable_op: The callable to execute.
|
|
97
|
+
:param args: Positional arguments for the callable.
|
|
98
|
+
:param kwargs: Keyword arguments for the callable.
|
|
99
|
+
|
|
100
|
+
:returns: The callable result on success.
|
|
101
|
+
:raises CircuitBreakerOpenError: If the circuit is OPEN.
|
|
102
|
+
"""
|
|
103
|
+
with self._lock:
|
|
104
|
+
current_state = self._state
|
|
105
|
+
|
|
106
|
+
if current_state == CircuitBreakerState.OPEN:
|
|
107
|
+
elapsed = time.monotonic() - self._open_timestamp
|
|
108
|
+
timeout = self._configuration.open_state_timeout
|
|
109
|
+
|
|
110
|
+
if elapsed >= timeout:
|
|
111
|
+
self._transition_to(CircuitBreakerState.HALF_OPEN, "open state timeout elapsed")
|
|
112
|
+
self._half_open_attempt_count = 0
|
|
113
|
+
self._success_count = 0
|
|
114
|
+
current_state = CircuitBreakerState.HALF_OPEN
|
|
115
|
+
else:
|
|
116
|
+
time_remaining = timeout - elapsed
|
|
117
|
+
raise CircuitBreakerOpenError(self._name, self._name, time_remaining)
|
|
118
|
+
|
|
119
|
+
if current_state == CircuitBreakerState.HALF_OPEN:
|
|
120
|
+
if self._half_open_attempt_count >= self._configuration.half_open_max_attempts:
|
|
121
|
+
time_remaining = self._configuration.open_state_timeout
|
|
122
|
+
raise CircuitBreakerOpenError(self._name, self._name, time_remaining)
|
|
123
|
+
|
|
124
|
+
self._half_open_attempt_count += 1
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
result = callable_op(*args, **kwargs)
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
self._on_failure(current_state)
|
|
130
|
+
raise
|
|
131
|
+
else:
|
|
132
|
+
self._on_success(current_state)
|
|
133
|
+
return result
|
|
134
|
+
|
|
135
|
+
def _on_success(self, state: CircuitBreakerState) -> None:
|
|
136
|
+
"""
|
|
137
|
+
Handles a successful operation outcome.
|
|
138
|
+
|
|
139
|
+
:param state: The state when the operation was executed.
|
|
140
|
+
"""
|
|
141
|
+
with self._lock:
|
|
142
|
+
if state == CircuitBreakerState.HALF_OPEN:
|
|
143
|
+
self._success_count += 1
|
|
144
|
+
if self._success_count >= self._configuration.success_threshold:
|
|
145
|
+
self._transition_to(CircuitBreakerState.CLOSED, "success threshold reached in half-open")
|
|
146
|
+
self._failure_count = 0
|
|
147
|
+
self._success_count = 0
|
|
148
|
+
elif state == CircuitBreakerState.CLOSED:
|
|
149
|
+
self._success_count += 1
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
def _on_failure(self, state: CircuitBreakerState) -> None:
|
|
153
|
+
"""
|
|
154
|
+
Handles a failed operation outcome.
|
|
155
|
+
|
|
156
|
+
:param state: The state when the operation was executed.
|
|
157
|
+
"""
|
|
158
|
+
with self._lock:
|
|
159
|
+
if state == CircuitBreakerState.HALF_OPEN:
|
|
160
|
+
self._transition_to(CircuitBreakerState.OPEN, "failure in half-open state")
|
|
161
|
+
self._open_timestamp = time.monotonic()
|
|
162
|
+
self._success_count = 0
|
|
163
|
+
elif state == CircuitBreakerState.CLOSED:
|
|
164
|
+
self._failure_count += 1
|
|
165
|
+
if self._failure_count >= self._configuration.failure_threshold:
|
|
166
|
+
self._transition_to(CircuitBreakerState.OPEN, "failure threshold reached")
|
|
167
|
+
self._open_timestamp = time.monotonic()
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
def _transition_to(self, new_state: CircuitBreakerState, reason: str) -> None:
|
|
171
|
+
"""
|
|
172
|
+
Records a state transition event and updates the current state.
|
|
173
|
+
Must be called while holding the lock.
|
|
174
|
+
|
|
175
|
+
:param new_state: The new state.
|
|
176
|
+
:param reason: The reason for the transition.
|
|
177
|
+
"""
|
|
178
|
+
previous_state = self._state
|
|
179
|
+
event = CircuitBreakerEvent(
|
|
180
|
+
name=self._name,
|
|
181
|
+
previous_state=previous_state,
|
|
182
|
+
new_state=new_state,
|
|
183
|
+
reason=reason
|
|
184
|
+
)
|
|
185
|
+
self._events.append(event)
|
|
186
|
+
self._state = new_state
|
|
187
|
+
|
|
188
|
+
self._logger.warning(
|
|
189
|
+
"CircuitBreaker '%s' transitioned from %s to %s: %s",
|
|
190
|
+
self._name, previous_state.value, new_state.value, reason
|
|
191
|
+
)
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
def reset(self) -> None:
|
|
195
|
+
"""
|
|
196
|
+
Transitions the CircuitBreaker to the CLOSED state and clears
|
|
197
|
+
all counters and event history.
|
|
198
|
+
"""
|
|
199
|
+
with self._lock:
|
|
200
|
+
self._state = CircuitBreakerState.CLOSED
|
|
201
|
+
self._failure_count = 0
|
|
202
|
+
self._success_count = 0
|
|
203
|
+
self._half_open_attempt_count = 0
|
|
204
|
+
self._open_timestamp = None
|
|
205
|
+
self._events = []
|
|
206
|
+
return
|
|
207
|
+
|
|
208
|
+
def __repr__(self) -> str:
|
|
209
|
+
"""
|
|
210
|
+
Returns a detailed string representation including class name,
|
|
211
|
+
circuit breaker name, and current state.
|
|
212
|
+
|
|
213
|
+
:returns: A repr string for debugging.
|
|
214
|
+
"""
|
|
215
|
+
repr_str = "CircuitBreaker(name={!r}, state={})".format(
|
|
216
|
+
self._name, self._state.value
|
|
217
|
+
)
|
|
218
|
+
return repr_str
|
|
219
|
+
|
|
220
|
+
def __str__(self) -> str:
|
|
221
|
+
"""
|
|
222
|
+
Returns a human-readable summary including the circuit breaker name,
|
|
223
|
+
current state, failure count, and success count.
|
|
224
|
+
|
|
225
|
+
:returns: A human-readable string.
|
|
226
|
+
"""
|
|
227
|
+
str_val = "CircuitBreaker name='{}', state={}, failures={}, successes={}".format(
|
|
228
|
+
self._name, self._state.value, self._failure_count, self._success_count
|
|
229
|
+
)
|
|
230
|
+
return str_val
|