hopx-ai 0.1.17__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.

Potentially problematic release.


This version of hopx-ai might be problematic. Click here for more details.

hopx_ai/cache.py ADDED
@@ -0,0 +1,97 @@
1
+ """Cache management resource for Bunnyshell Sandboxes."""
2
+
3
+ from typing import Dict, Any, Optional
4
+ import logging
5
+ from ._agent_client import AgentHTTPClient
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class Cache:
11
+ """
12
+ Cache management resource.
13
+
14
+ Provides methods for managing execution result cache.
15
+
16
+ Features:
17
+ - Get cache statistics
18
+ - Clear cache
19
+
20
+ Example:
21
+ >>> sandbox = Sandbox.create(template="code-interpreter")
22
+ >>>
23
+ >>> # Get cache stats
24
+ >>> stats = sandbox.cache.stats()
25
+ >>> print(f"Cache hits: {stats['hits']}")
26
+ >>> print(f"Cache size: {stats['size']} MB")
27
+ >>>
28
+ >>> # Clear cache
29
+ >>> sandbox.cache.clear()
30
+ """
31
+
32
+ def __init__(self, client: AgentHTTPClient):
33
+ """
34
+ Initialize Cache resource.
35
+
36
+ Args:
37
+ client: Shared agent HTTP client
38
+ """
39
+ self._client = client
40
+ logger.debug("Cache resource initialized")
41
+
42
+ def stats(self, *, timeout: Optional[int] = None) -> Dict[str, Any]:
43
+ """
44
+ Get cache statistics.
45
+
46
+ Args:
47
+ timeout: Request timeout in seconds (overrides default)
48
+
49
+ Returns:
50
+ Dictionary with cache statistics (hits, misses, size, etc.)
51
+
52
+ Example:
53
+ >>> stats = sandbox.cache.stats()
54
+ >>> print(f"Cache hits: {stats['hits']}")
55
+ >>> print(f"Cache misses: {stats['misses']}")
56
+ >>> print(f"Hit rate: {stats['hit_rate']:.2%}")
57
+ >>> print(f"Cache size: {stats['size']} MB")
58
+ >>> print(f"Entry count: {stats['count']}")
59
+ """
60
+ logger.debug("Getting cache statistics")
61
+
62
+ response = self._client.get(
63
+ "/cache/stats",
64
+ operation="get cache stats",
65
+ timeout=timeout
66
+ )
67
+
68
+ return response.json()
69
+
70
+ def clear(self, *, timeout: Optional[int] = None) -> Dict[str, Any]:
71
+ """
72
+ Clear the execution result cache.
73
+
74
+ Args:
75
+ timeout: Request timeout in seconds (overrides default)
76
+
77
+ Returns:
78
+ Dictionary with confirmation message
79
+
80
+ Example:
81
+ >>> result = sandbox.cache.clear()
82
+ >>> print(result['message']) # "Cache cleared successfully"
83
+ >>> print(f"Entries removed: {result.get('entries_removed', 0)}")
84
+ """
85
+ logger.debug("Clearing cache")
86
+
87
+ response = self._client.post(
88
+ "/cache/clear",
89
+ operation="clear cache",
90
+ timeout=timeout
91
+ )
92
+
93
+ return response.json()
94
+
95
+ def __repr__(self) -> str:
96
+ return f"<Cache client={self._client}>"
97
+
hopx_ai/commands.py ADDED
@@ -0,0 +1,174 @@
1
+ """Command execution resource for Bunnyshell Sandboxes."""
2
+
3
+ from typing import Optional, Dict
4
+ import logging
5
+ from .models import CommandResult
6
+ from ._agent_client import AgentHTTPClient
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class Commands:
12
+ """
13
+ Command execution resource.
14
+
15
+ Provides methods for running shell commands inside the sandbox.
16
+
17
+ Features:
18
+ - Automatic retry with exponential backoff
19
+ - Connection pooling for efficiency
20
+ - Proper error handling
21
+ - Configurable timeouts
22
+
23
+ Example:
24
+ >>> sandbox = Sandbox.create(template="code-interpreter")
25
+ >>>
26
+ >>> # Run simple command
27
+ >>> result = sandbox.commands.run('ls -la /workspace')
28
+ >>> print(result.stdout)
29
+ >>>
30
+ >>> # Check success
31
+ >>> if result.success:
32
+ ... print("Command succeeded!")
33
+ ... else:
34
+ ... print(f"Failed: {result.stderr}")
35
+ """
36
+
37
+ def __init__(self, client: AgentHTTPClient):
38
+ """
39
+ Initialize Commands resource.
40
+
41
+ Args:
42
+ client: Shared agent HTTP client
43
+ """
44
+ self._client = client
45
+ logger.debug("Commands resource initialized")
46
+
47
+ def run(
48
+ self,
49
+ command: str,
50
+ *,
51
+ timeout: int = 30,
52
+ background: bool = False,
53
+ env: Optional[Dict[str, str]] = None,
54
+ working_dir: str = "/workspace",
55
+ ) -> CommandResult:
56
+ """
57
+ Run shell command.
58
+
59
+ Args:
60
+ command: Shell command to run
61
+ timeout: Command timeout in seconds (default: 30)
62
+ background: Run in background (returns immediately)
63
+ env: Optional environment variables for this command only.
64
+ Priority: Request env > Global env > Agent env
65
+ working_dir: Working directory for command (default: /workspace)
66
+
67
+ Returns:
68
+ CommandResult with stdout, stderr, exit_code
69
+
70
+ Raises:
71
+ CommandExecutionError: If command execution fails
72
+ TimeoutError: If command times out
73
+
74
+ Example:
75
+ >>> # Simple command
76
+ >>> result = sandbox.commands.run('ls -la')
77
+ >>> print(result.stdout)
78
+ >>> print(f"Exit code: {result.exit_code}")
79
+ >>>
80
+ >>> # With environment variables
81
+ >>> result = sandbox.commands.run(
82
+ ... 'echo $API_KEY',
83
+ ... env={"API_KEY": "sk-test-123"}
84
+ ... )
85
+ >>>
86
+ >>> # With custom timeout
87
+ >>> result = sandbox.commands.run('npm install', timeout=300)
88
+ >>>
89
+ >>> # Check success
90
+ >>> if result.success:
91
+ ... print("Success!")
92
+ ... else:
93
+ ... print(f"Failed with exit code {result.exit_code}")
94
+ ... print(f"Error: {result.stderr}")
95
+ """
96
+ if background:
97
+ return self._run_background(command, env=env, working_dir=working_dir)
98
+
99
+ logger.debug(f"Running command: {command[:50]}...")
100
+
101
+ # Build request payload
102
+ payload = {
103
+ "command": command,
104
+ "timeout": timeout,
105
+ "working_dir": working_dir
106
+ }
107
+
108
+ # Add optional environment variables
109
+ if env:
110
+ payload["env"] = env
111
+
112
+ response = self._client.post(
113
+ "/commands/run",
114
+ json=payload,
115
+ operation="run command",
116
+ context={"command": command},
117
+ timeout=timeout + 5 # Add buffer to HTTP timeout
118
+ )
119
+
120
+ data = response.json()
121
+
122
+ return CommandResult(
123
+ stdout=data.get("stdout", ""),
124
+ stderr=data.get("stderr", ""),
125
+ exit_code=data.get("exit_code", 0),
126
+ execution_time=data.get("execution_time", 0.0)
127
+ )
128
+
129
+ def _run_background(
130
+ self,
131
+ command: str,
132
+ env: Optional[Dict[str, str]] = None,
133
+ working_dir: str = "/workspace"
134
+ ) -> CommandResult:
135
+ """
136
+ Run command in background.
137
+
138
+ Args:
139
+ command: Shell command to run
140
+ env: Optional environment variables
141
+ working_dir: Working directory
142
+
143
+ Returns:
144
+ CommandResult with process info
145
+ """
146
+ logger.debug(f"Running command in background: {command[:50]}...")
147
+
148
+ # Build request payload
149
+ payload = {"command": command, "working_dir": working_dir}
150
+
151
+ # Add optional environment variables
152
+ if env:
153
+ payload["env"] = env
154
+
155
+ response = self._client.post(
156
+ "/commands/background",
157
+ json=payload,
158
+ operation="run background command",
159
+ context={"command": command},
160
+ timeout=10
161
+ )
162
+
163
+ data = response.json()
164
+
165
+ # Return a CommandResult indicating background execution
166
+ return CommandResult(
167
+ stdout=f"Background process started: {data.get('process_id', 'unknown')}",
168
+ stderr="",
169
+ exit_code=0,
170
+ execution_time=0.0
171
+ )
172
+
173
+ def __repr__(self) -> str:
174
+ return f"<Commands client={self._client}>"