keycase-agent-sdk 0.1.0b2__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.
@@ -0,0 +1,99 @@
1
+ """Keycase Agent SDK - Python SDK for Keycase automation platform.
2
+
3
+ This package provides a robust agent for executing keyword-based automation
4
+ flows, with support for both WebSocket (server-connected) and local execution modes.
5
+
6
+ Basic Usage:
7
+ # WebSocket mode (connects to Keycase server)
8
+ from keycase_agent import KeycaseAgent, load_config, load_keywords
9
+
10
+ load_keywords('my_keywords') # Load your keyword files
11
+ config = load_config()
12
+ agent = KeycaseAgent(config)
13
+ agent.start()
14
+
15
+ # Local mode (standalone execution)
16
+ from keycase_agent import ExecutionManager, load_keywords
17
+
18
+ load_keywords('my_keywords') # Load your keyword files
19
+ manager = ExecutionManager(mode='local')
20
+ results = manager.execute_local(execution_plan)
21
+ """
22
+
23
+ from .agent import KeycaseAgent
24
+ from .auth import AuthService
25
+ from .config import load_config
26
+ from .decorators import (
27
+ AfterRun,
28
+ BeforeRun,
29
+ ParamDirection,
30
+ ParamType,
31
+ get_all_keyword_schemas,
32
+ get_keyword_schema,
33
+ input_param,
34
+ keyword,
35
+ output_param,
36
+ param,
37
+ )
38
+ from .exceptions import (
39
+ AuthenticationError,
40
+ ExecutionError,
41
+ KeycaseError,
42
+ KeywordDefinitionError,
43
+ ParameterValidationError,
44
+ )
45
+ from .execution_manager import ExecutionManager
46
+ from .loader import load_keywords
47
+ from .models.execution_result import ExecutionResultData, FlowResult, StatusEnum
48
+ from .state_tracker import AgentStateTracker
49
+ from .websocket_client import ConnectionState, WebSocketClient
50
+
51
+ __version__ = "0.1.0"
52
+ __author__ = "Keycase Team"
53
+
54
+ __all__ = [
55
+ # Main classes
56
+ "KeycaseAgent",
57
+ "ExecutionManager",
58
+ "AuthService",
59
+ "WebSocketClient",
60
+ "AgentStateTracker",
61
+ # Configuration
62
+ "load_config",
63
+ "load_keywords",
64
+ # Keyword decorators
65
+ "keyword",
66
+ "param",
67
+ "input_param",
68
+ "output_param",
69
+ # Hook decorators
70
+ "BeforeRun",
71
+ "AfterRun",
72
+ # Parameter types
73
+ "ParamType",
74
+ "ParamDirection",
75
+ # Schema utilities
76
+ "get_keyword_schema",
77
+ "get_all_keyword_schemas",
78
+ # Exceptions
79
+ "KeycaseError",
80
+ "KeywordDefinitionError",
81
+ "ParameterValidationError",
82
+ "ExecutionError",
83
+ "AuthenticationError",
84
+ # Models
85
+ "ExecutionResultData",
86
+ "FlowResult",
87
+ "StatusEnum",
88
+ "ConnectionState",
89
+ # Version info
90
+ "__version__",
91
+ ]
92
+
93
+
94
+ def start_agent() -> None:
95
+ """Entry point for starting the Keycase agent from command line."""
96
+ load_keywords()
97
+ config = load_config()
98
+ agent = KeycaseAgent(config)
99
+ agent.start()
keycase_agent/agent.py ADDED
@@ -0,0 +1,358 @@
1
+ """Main Keycase Agent orchestrator module."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import signal
7
+ import time
8
+ from datetime import datetime
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from .auth import AuthService
12
+ from .event_handler import EventHandler
13
+ from .execution_manager import ExecutionManager
14
+ from .models.websocket_event_types import WebSocketEventType
15
+ from .state_tracker import AgentStateTracker
16
+ from .utils.auth_helper import auth_request, auth_request_with_details
17
+ from .utils.event_sender import configure_batching, send_event, status_update
18
+ from .websocket_client import WebSocketClient
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Constants
23
+ MAX_RESULT_RETRIES = 3
24
+ INITIAL_RETRY_INTERVAL_SECONDS = 2
25
+ MAX_FAILED_RESULTS_ENTRIES = 100
26
+ FAILED_RESULTS_DIR = "failed_results"
27
+
28
+ # Error codes that indicate the result was already processed (treat as success)
29
+ ALREADY_COMPLETED_CODES = {5002} # "Execution run is already completed"
30
+
31
+
32
+ class KeycaseAgent:
33
+ """Main Keycase Agent orchestrator.
34
+
35
+ Manages WebSocket connections, authentication, execution management,
36
+ and event handling for the Keycase automation platform.
37
+
38
+ Uses AgentToken-based authentication where:
39
+ - Agent authenticates with AgentToken to get access credentials
40
+ - Server assigns agentId and returns wsUrl dynamically
41
+ - WebSocket URL comes from authentication response
42
+
43
+ Args:
44
+ config: Configuration dictionary containing:
45
+ - HTTP_URL: Base HTTP API URL
46
+ - AGENT_TOKEN: AgentToken (must start with 'agt_')
47
+ - AGENT_NAME: Unique agent name within organization
48
+ - AGENT_VERSION: Agent version (optional)
49
+ - AGENT_CAPABILITIES: List of capabilities (optional)
50
+ - AGENT_TAGS: List of tags (optional)
51
+ """
52
+
53
+ def __init__(self, config: Dict[str, Any]) -> None:
54
+ self.http_url = config["HTTP_URL"]
55
+ self.agent_token = config["AGENT_TOKEN"]
56
+ self.agent_name = config["AGENT_NAME"]
57
+ self.agent_version = config.get("AGENT_VERSION", "1.0.0")
58
+ self.capabilities: List[str] = config.get("AGENT_CAPABILITIES", [])
59
+ self.tags: List[str] = config.get("AGENT_TAGS", [])
60
+
61
+ # These will be set after authentication
62
+ self.agent_id: Optional[int] = None
63
+ self.ws_url: Optional[str] = None
64
+
65
+ # Initialize components
66
+ self.state_tracker = AgentStateTracker()
67
+ self.auth_service = AuthService(
68
+ http_url=self.http_url,
69
+ agent_token=self.agent_token,
70
+ agent_name=self.agent_name,
71
+ version=self.agent_version,
72
+ capabilities=self.capabilities,
73
+ tags=self.tags,
74
+ )
75
+ self.execution_manager = ExecutionManager(
76
+ send_result_callback=self._send_result,
77
+ update_status_callback=self._update_status,
78
+ )
79
+
80
+ self.event_handler = EventHandler(
81
+ execution_manager=self.execution_manager,
82
+ state_tracker=self.state_tracker,
83
+ get_execution_plan=self._get_execution_plan,
84
+ )
85
+
86
+ # WebSocket client will be initialized after authentication
87
+ self.ws_client: Optional[WebSocketClient] = None
88
+
89
+ # Handle shutdown gracefully
90
+ signal.signal(signal.SIGINT, self._on_shutdown_signal)
91
+ signal.signal(signal.SIGTERM, self._on_shutdown_signal)
92
+
93
+ def start(self) -> None:
94
+ """Start the agent by authenticating and establishing WebSocket connection."""
95
+ logger.info("Starting Keycase Agent")
96
+ logger.info(f"Agent name: {self.agent_name}")
97
+ logger.info(f"Agent version: {self.agent_version}")
98
+
99
+ # Authenticate and get credentials (including dynamic wsUrl and agentId)
100
+ credentials = self.auth_service.authenticate()
101
+
102
+ # Store the dynamic agent ID and WebSocket URL from server
103
+ self.agent_id = credentials.agent_id
104
+ self.ws_url = credentials.ws_url
105
+
106
+ logger.info(f"Assigned agent ID: {self.agent_id}")
107
+ logger.info(f"WebSocket URL: {self.ws_url}")
108
+
109
+ # Initialize WebSocket client with dynamic URL
110
+ self.ws_client = WebSocketClient(
111
+ url=self.ws_url,
112
+ on_open=self._on_open,
113
+ on_message=self._on_message,
114
+ on_error=self._on_error,
115
+ on_close=self._on_close,
116
+ )
117
+
118
+ self.ws_client.run_forever()
119
+
120
+ def _on_open(self, ws) -> None:
121
+ """Handle WebSocket connection opened event."""
122
+ logger.info("WebSocket connection opened")
123
+ configure_batching(ws, flush_interval=10.0)
124
+ self._send_auth()
125
+
126
+ def _on_message(self, ws, message: str) -> None:
127
+ """Handle incoming WebSocket messages."""
128
+ self.event_handler.handle(message)
129
+
130
+ def _on_error(self, ws, error: Exception) -> None:
131
+ """Handle WebSocket errors."""
132
+ logger.error(f"WebSocket error: {error}")
133
+ self.execution_manager.stop()
134
+
135
+ def _on_close(self, ws, code: Optional[int], msg: Optional[str]) -> None:
136
+ """Handle WebSocket connection closed event."""
137
+ logger.info(f"WebSocket closed with code={code}, msg={msg}")
138
+ self.execution_manager.stop()
139
+
140
+ def _send_auth(self) -> None:
141
+ """Send authentication event to WebSocket server."""
142
+ token = self.auth_service.get_token()
143
+ payload = {
144
+ "accessToken": token,
145
+ "agentId": self.agent_id,
146
+ }
147
+ logger.info(f"Sending auth event for agent ID: {self.agent_id}")
148
+ send_event(WebSocketEventType.AGENT_AUTH_REQUEST, payload, immediate=True)
149
+
150
+ def _send_result(
151
+ self, project_id: int, run_id: int, result: Dict[str, Any]
152
+ ) -> Optional[Any]:
153
+ """Send execution result to server with retry mechanism and local fallback.
154
+
155
+ Args:
156
+ project_id: Project identifier
157
+ run_id: Run identifier
158
+ result: Execution result data
159
+
160
+ Returns:
161
+ Server response or None if failed and saved locally
162
+ """
163
+ url = f"{self.http_url}/projects/{project_id}/runs/{run_id}/results"
164
+ token = self.auth_service.get_token()
165
+
166
+ if not token:
167
+ logger.error("No authentication token available")
168
+ self._save_result_locally(
169
+ project_id, run_id, result, "No authentication token"
170
+ )
171
+ return None
172
+
173
+ retry_interval = INITIAL_RETRY_INTERVAL_SECONDS
174
+
175
+ for attempt in range(1, MAX_RESULT_RETRIES + 1):
176
+ try:
177
+ logger.info(
178
+ f"Sending run result to {url} "
179
+ f"(attempt {attempt}/{MAX_RESULT_RETRIES})"
180
+ )
181
+ response = auth_request_with_details("POST", url, token, data=result)
182
+
183
+ if response.success:
184
+ logger.info(f"Successfully sent result on attempt {attempt}")
185
+ return response.data
186
+
187
+ # Check if this is an "already completed" error - treat as success
188
+ if response.error_code in ALREADY_COMPLETED_CODES:
189
+ logger.info(
190
+ f"Run {run_id} already completed (server confirmed). "
191
+ "Treating as success."
192
+ )
193
+ return response.data
194
+
195
+ # Log the error for other failures
196
+ logger.warning(
197
+ f"Attempt {attempt} failed: {response.error_message} "
198
+ f"(code: {response.error_code})"
199
+ )
200
+
201
+ except Exception as e:
202
+ logger.error(f"Attempt {attempt} failed to send result: {str(e)}")
203
+
204
+ # If not the last attempt, wait before retrying
205
+ if attempt < MAX_RESULT_RETRIES:
206
+ logger.info(f"Retrying in {retry_interval} seconds...")
207
+ time.sleep(retry_interval)
208
+ retry_interval *= 1.5 # Exponential backoff
209
+
210
+ # All attempts failed, save locally
211
+ logger.error(
212
+ f"All {MAX_RESULT_RETRIES} attempts to send result failed. Saving locally."
213
+ )
214
+ self._save_result_locally(
215
+ project_id, run_id, result, "All retry attempts failed"
216
+ )
217
+ return None
218
+
219
+ def _save_result_locally(
220
+ self, project_id: int, run_id: int, result: Dict[str, Any], reason: str
221
+ ) -> None:
222
+ """Save execution result to local directory when remote sending fails.
223
+
224
+ Args:
225
+ project_id: Project identifier
226
+ run_id: Run identifier
227
+ result: Execution result data
228
+ reason: Reason for local saving
229
+ """
230
+ try:
231
+ # Create results directory if it doesn't exist
232
+ results_dir = os.path.join(os.getcwd(), FAILED_RESULTS_DIR)
233
+ os.makedirs(results_dir, exist_ok=True)
234
+
235
+ # Create filename with timestamp
236
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
237
+ filename = f"result_p{project_id}_r{run_id}_{timestamp}.json"
238
+ filepath = os.path.join(results_dir, filename)
239
+
240
+ # Prepare result data with metadata
241
+ result_data = {
242
+ "metadata": {
243
+ "project_id": project_id,
244
+ "run_id": run_id,
245
+ "timestamp": datetime.now().isoformat(),
246
+ "reason": reason,
247
+ "agent_id": self.agent_id,
248
+ "agent_name": self.agent_name,
249
+ },
250
+ "result": result,
251
+ }
252
+
253
+ # Save to file
254
+ with open(filepath, "w", encoding="utf-8") as f:
255
+ json.dump(result_data, f, indent=2, default=str)
256
+
257
+ logger.info(f"Execution result saved locally to: {filepath}")
258
+
259
+ # Update summary file tracking all failed results
260
+ self._update_failed_results_summary(filepath, project_id, run_id, reason)
261
+
262
+ except Exception as e:
263
+ logger.error(f"Failed to save result locally: {str(e)}")
264
+
265
+ def _update_failed_results_summary(
266
+ self, filepath: str, project_id: int, run_id: int, reason: str
267
+ ) -> None:
268
+ """Update summary file of all failed result submissions.
269
+
270
+ Args:
271
+ filepath: Path where result was saved
272
+ project_id: Project identifier
273
+ run_id: Run identifier
274
+ reason: Reason for failure
275
+ """
276
+ try:
277
+ results_dir = os.path.join(os.getcwd(), FAILED_RESULTS_DIR)
278
+ summary_file = os.path.join(results_dir, "failed_results_summary.json")
279
+
280
+ # Load existing summary or create new
281
+ summary_data: Dict[str, Any] = {"failed_results": []}
282
+ if os.path.exists(summary_file):
283
+ try:
284
+ with open(summary_file, "r", encoding="utf-8") as f:
285
+ summary_data = json.load(f)
286
+ except (json.JSONDecodeError, IOError):
287
+ pass # Use default structure if file is corrupted
288
+
289
+ # Add new entry
290
+ entry = {
291
+ "timestamp": datetime.now().isoformat(),
292
+ "project_id": project_id,
293
+ "run_id": run_id,
294
+ "reason": reason,
295
+ "filepath": filepath,
296
+ "agent_id": self.agent_id,
297
+ "agent_name": self.agent_name,
298
+ }
299
+
300
+ summary_data["failed_results"].append(entry)
301
+
302
+ # Keep only last N entries to avoid file growing too large
303
+ if len(summary_data["failed_results"]) > MAX_FAILED_RESULTS_ENTRIES:
304
+ summary_data["failed_results"] = summary_data["failed_results"][
305
+ -MAX_FAILED_RESULTS_ENTRIES:
306
+ ]
307
+
308
+ # Save summary
309
+ with open(summary_file, "w", encoding="utf-8") as f:
310
+ json.dump(summary_data, f, indent=2, default=str)
311
+
312
+ except Exception as e:
313
+ logger.error(f"Failed to update failed results summary: {str(e)}")
314
+
315
+ def _update_status(self, busy: bool) -> None:
316
+ """Update agent status (busy/idle)."""
317
+ status = self.state_tracker.set_busy(busy)
318
+ status_update("AGENT_STATUS_NOTIFY", status)
319
+
320
+ def _get_execution_plan(self, project_id: int, run_id: int) -> str:
321
+ """Fetch execution plan from server.
322
+
323
+ Args:
324
+ project_id: Project identifier
325
+ run_id: Run identifier
326
+
327
+ Returns:
328
+ JSON string of execution plan
329
+
330
+ Raises:
331
+ Exception: If plan fetch fails
332
+ """
333
+ url = f"{self.http_url}/projects/{project_id}/runs/{run_id}?includePlan=true"
334
+ token = self.auth_service.get_token()
335
+
336
+ if not token:
337
+ raise Exception("No authentication token available")
338
+
339
+ logger.info(f"Fetching execution plan from {url}")
340
+ response = auth_request("GET", url, token)
341
+
342
+ if not response:
343
+ raise Exception("Failed to fetch execution plan")
344
+
345
+ if isinstance(response, str):
346
+ response = json.loads(response)
347
+
348
+ logger.debug(f"Received execution plan response: {response}")
349
+ return json.dumps(response.get("plan", {}))
350
+
351
+ def _on_shutdown_signal(self, signum: int, frame) -> None:
352
+ """Handle shutdown signals for graceful cleanup."""
353
+ logger.info(f"Received shutdown signal ({signum}); cleaning up")
354
+ self.state_tracker.request_shutdown()
355
+ self.execution_manager.stop()
356
+ self.auth_service.stop()
357
+ if self.ws_client:
358
+ self.ws_client.stop()