update shell sandox
This commit is contained in:
+45
-45
@@ -1,4 +1,4 @@
|
||||
|
||||
import asyncio
|
||||
from typing import Optional,ClassVar
|
||||
from pydantic import Field
|
||||
# from app.agentpress.thread_manager import ThreadManager
|
||||
@@ -23,55 +23,55 @@ class SandboxToolsBase(BaseTool):
|
||||
_sandbox_id: Optional[str] = None
|
||||
_sandbox_pass: Optional[str] = None
|
||||
workspace_path: str = Field(default="/workspace", exclude=True)
|
||||
_sessions: dict[str, str] = {}
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True # Allow non-pydantic types like ThreadManager
|
||||
underscore_attrs_are_private = True
|
||||
async def _ensure_sandbox(self) -> Sandbox:
|
||||
"""Ensure we have a valid sandbox instance, retrieving it from the project if needed."""
|
||||
if self._sandbox is None:
|
||||
# try:
|
||||
# # Get database client
|
||||
# client = await self.thread_manager.db.client
|
||||
#
|
||||
# # Get project data
|
||||
# project = await client.table('projects').select('*').eq('project_id', self.project_id).execute()
|
||||
# if not project.data or len(project.data) == 0:
|
||||
# raise ValueError(f"Project {self.project_id} not found")
|
||||
#
|
||||
# project_data = project.data[0]
|
||||
# sandbox_info = project_data.get('sandbox', {})
|
||||
#
|
||||
# if not sandbox_info.get('id'):
|
||||
# raise ValueError(f"No sandbox found for project {self.project_id}")
|
||||
#
|
||||
# # Store sandbox info
|
||||
# self._sandbox_id = sandbox_info['id']
|
||||
# self._sandbox_pass = sandbox_info.get('pass')
|
||||
#
|
||||
# # Get or start the sandbox
|
||||
# self._sandbox = await get_or_start_sandbox(self._sandbox_id)
|
||||
#
|
||||
# # # Log URLs if not already printed
|
||||
# # if not SandboxToolsBase._urls_printed:
|
||||
# # vnc_link = self._sandbox.get_preview_link(6080)
|
||||
# # website_link = self._sandbox.get_preview_link(8080)
|
||||
#
|
||||
# # vnc_url = vnc_link.url if hasattr(vnc_link, 'url') else str(vnc_link)
|
||||
# # website_url = website_link.url if hasattr(website_link, 'url') else str(website_link)
|
||||
#
|
||||
# # print("\033[95m***")
|
||||
# # print(f"VNC URL: {vnc_url}")
|
||||
# # print(f"Website URL: {website_url}")
|
||||
# # print("***\033[0m")
|
||||
# # SandboxToolsBase._urls_printed = True
|
||||
#
|
||||
# except Exception as e:
|
||||
logger.error(f"Error retrieving sandbox for project {self.project_id}: {str(e)}", exc_info=True)
|
||||
raise Exception
|
||||
|
||||
# async def _ensure_sandbox(self) -> Sandbox:
|
||||
# """Ensure we have a valid sandbox instance, retrieving it from the project if needed."""
|
||||
# if self._sandbox is None:
|
||||
# try:
|
||||
# # Get database client
|
||||
# client = await self.thread_manager.db.client
|
||||
|
||||
# # Get project data
|
||||
# project = await client.table('projects').select('*').eq('project_id', self.project_id).execute()
|
||||
# if not project.data or len(project.data) == 0:
|
||||
# raise ValueError(f"Project {self.project_id} not found")
|
||||
|
||||
# project_data = project.data[0]
|
||||
# sandbox_info = project_data.get('sandbox', {})
|
||||
|
||||
# if not sandbox_info.get('id'):
|
||||
# raise ValueError(f"No sandbox found for project {self.project_id}")
|
||||
|
||||
# # Store sandbox info
|
||||
# self._sandbox_id = sandbox_info['id']
|
||||
# self._sandbox_pass = sandbox_info.get('pass')
|
||||
|
||||
# # Get or start the sandbox
|
||||
# self._sandbox = await get_or_start_sandbox(self._sandbox_id)
|
||||
|
||||
# # # Log URLs if not already printed
|
||||
# # if not SandboxToolsBase._urls_printed:
|
||||
# # vnc_link = self._sandbox.get_preview_link(6080)
|
||||
# # website_link = self._sandbox.get_preview_link(8080)
|
||||
|
||||
# # vnc_url = vnc_link.url if hasattr(vnc_link, 'url') else str(vnc_link)
|
||||
# # website_url = website_link.url if hasattr(website_link, 'url') else str(website_link)
|
||||
|
||||
# # print("\033[95m***")
|
||||
# # print(f"VNC URL: {vnc_url}")
|
||||
# # print(f"Website URL: {website_url}")
|
||||
# # print("***\033[0m")
|
||||
# # SandboxToolsBase._urls_printed = True
|
||||
|
||||
# except Exception as e:
|
||||
# logger.error(f"Error retrieving sandbox for project {self.project_id}: {str(e)}", exc_info=True)
|
||||
# raise e
|
||||
|
||||
# return self._sandbox
|
||||
return self._sandbox
|
||||
|
||||
@property
|
||||
def sandbox(self) -> Sandbox:
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import asyncio
|
||||
from typing import Optional, Dict, Any, TypeVar
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from app.tool.base import ToolResult
|
||||
from app.daytona.tool_base import SandboxToolsBase
|
||||
from app.daytona.tool_base import SandboxToolsBase, Sandbox
|
||||
from app.utils.logger import logger
|
||||
|
||||
Context = TypeVar("Context")
|
||||
@@ -76,6 +77,12 @@ class SandboxShellTool(SandboxToolsBase):
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data):
|
||||
"""Initialize with optional sandbox and thread_id."""
|
||||
super().__init__(**data)
|
||||
if sandbox is not None:
|
||||
self._sandbox = sandbox
|
||||
|
||||
async def _ensure_session(self, session_name: str = "default") -> str:
|
||||
"""Ensure a session exists and return its ID."""
|
||||
if session_name not in self._sessions:
|
||||
@@ -334,7 +341,7 @@ class SandboxShellTool(SandboxToolsBase):
|
||||
Returns:
|
||||
ToolResult with the action's output or error
|
||||
"""
|
||||
async with self.lock:
|
||||
async with asyncio.Lock():
|
||||
try:
|
||||
# Navigation actions
|
||||
if action == "execute_command":
|
||||
@@ -357,6 +364,7 @@ class SandboxShellTool(SandboxToolsBase):
|
||||
logger.error(f"Error executing shell action: {e}")
|
||||
return self.fail_response(f"Error executing shell action: {e}")
|
||||
|
||||
|
||||
async def cleanup(self):
|
||||
"""Clean up all sessions."""
|
||||
for session_name in list(self._sessions.keys()):
|
||||
|
||||
@@ -5,18 +5,24 @@ import asyncio
|
||||
async def main():
|
||||
# 创建沙箱和工具
|
||||
sandbox = create_sandbox(password="123456")
|
||||
base_url=sandbox.get_preview_link(8000)
|
||||
print(f"Sandbox base URL: {base_url}")
|
||||
# base_url=sandbox.get_preview_link(8000)
|
||||
# print(f"Sandbox base URL: {base_url}")
|
||||
|
||||
print(f"Sandbox ID: {sandbox.id}")
|
||||
sb_shell_tool = SandboxShellTool.create_with_sandbox(sandbox)
|
||||
|
||||
vnc_link = sandbox.get_preview_link(6080)
|
||||
website_link = sandbox.get_preview_link(8080)
|
||||
print(f"VNC Link: {vnc_link}")
|
||||
print(f"Website Link: {website_link}")
|
||||
sb_shell_tool = SandboxShellTool(sandbox)
|
||||
|
||||
|
||||
# 执行截图操作
|
||||
result = await sb_shell_tool.execute(action="execute_command", command="ls")
|
||||
result = await sb_shell_tool.execute(action="execute_command", command="pwd")
|
||||
print(result)
|
||||
|
||||
# 清理资源(可选)
|
||||
await sb_shell_tool.cleanup()
|
||||
# await sb_shell_tool.cleanup()
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("123")
|
||||
|
||||
Reference in New Issue
Block a user