Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix: route all tool execution through per-workflow workspace directory
trohitg1cc7b77b2679
diff --git a/.env.template b/.env.templateindex 3814165f..07da43c1 100644--- a/.env.template+++ b/.env.template@@ -46,8 +46,8 @@ TEMPORAL_SERVER_ADDRESS=localhost:7233TEMPORAL_NAMESPACE=defaultTEMPORAL_TASK_QUEUE=machina-tasks-# Deep Agent workspace (root directory for filesystem/shell tools)-DEEP_AGENT_WORKSPACE=./workspace+# Per-workflow workspace (nodes save files here, agents access via filesystem tools)+WORKSPACE_BASE_DIR=data/workspaces# LoggingLOG_LEVEL=INFOdiff --git a/CLAUDE.md b/CLAUDE.mdindex 4e0b9126..5d79a60e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1214,7 +1214,7 @@ Residential proxy provider management with geo-targeting, session control, and a- **typescriptExecutor**: **Dual-purpose node** - Execute TypeScript code via persistent Node.js server with type safety, syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`typescript_code`).### Filesystem & Shell Nodes (4 nodes)-Dual-purpose tool nodes delegating to `deepagents.backends.LocalShellBackend`. Workspace path configured via `DEEP_AGENT_WORKSPACE` env var (default: `./workspace`). Uses `virtual_mode=True` to confine paths.+Dual-purpose tool nodes delegating to `deepagents.backends.LocalShellBackend`. Uses per-workflow workspace from execution context (`context["workspace_dir"]` = `data/workspaces/<workflow_id>/`). `virtual_mode=True` confines paths within the workspace.- **fileRead**: **Dual-purpose node** - Read file contents with line numbers and pagination. Works as workflow node OR AI Agent tool (`file_read`). Parameters: file_path, offset, limit.- **fileModify**: **Dual-purpose node** - Write new files or edit existing files with string replacement. Works as workflow node OR AI Agent tool (`file_modify`). Operations: write (create/overwrite), edit (find and replace with old_string/new_string/replace_all).diff --git a/server/core/config.py b/server/core/config.pyindex 4f20d354..2928fae1 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -64,9 +64,6 @@ class Settings(BaseSettings):nodejs_executor_timeout: int = Field(default=30, env="NODEJS_EXECUTOR_TIMEOUT", ge=5, le=300)nodejs_executor_port: int = Field(default=3020, env="NODEJS_EXECUTOR_PORT", ge=1024, le=65535)- # Deep Agent filesystem root (defaults to server working directory)- deep_agent_workspace: str = Field(default="", env="DEEP_AGENT_WORKSPACE")-# AI Proxy Configuration (Ollama-style proxy)ai_proxy_default_port: int = Field(default=11434, env="AI_PROXY_DEFAULT_PORT")diff --git a/server/services/agents/adapters.py b/server/services/agents/adapters.pyindex 13185b8f..85ea2511 100644--- a/server/services/agents/adapters.py+++ b/server/services/agents/adapters.py@@ -28,6 +28,7 @@ class ToolAdapter:build_tool_fn,workflow_id: str = None,broadcaster=None,+ workspace_dir: str = "",) -> List[StructuredTool]:"""Build executable tools from raw tool_data.@@ -36,20 +37,23 @@ class ToolAdapter:build_tool_fn: AIService._build_tool_from_node (async).workflow_id: For scoped status broadcasts.broadcaster: For tool node glow effects.+ workspace_dir: Per-workflow workspace path for filesystem tools.Returns:List of StructuredTools with real async executors."""# Return coroutine - must be awaited- return ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster)+ return ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir)@staticmethod- async def _build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster):+ async def _build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir=""):executable = []for tool_info in tool_data:try:tool, config = await build_tool_fn(tool_info)if tool and config:+ if workspace_dir:+ config['workspace_dir'] = workspace_direxecutable.append(ToolAdapter._wrap(tool, config, workflow_id, broadcaster))diff --git a/server/services/agents/service.py b/server/services/agents/service.pyindex 75251882..19f05c41 100644--- a/server/services/agents/service.py+++ b/server/services/agents/service.py@@ -109,7 +109,8 @@ class DeepAgentService:executable_tools = []if tool_data and build_tool_fn:await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)..."})- executable_tools = await ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster)+ workspace_dir = parameters.get('workspace_dir', '')+ executable_tools = await ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir)# === Convert teammates via SubAgentAdapter ===subagents = SubAgentAdapter.convert(teammates) if teammates else Nonediff --git a/server/services/ai.py b/server/services/ai.pyindex 268f7714..a7003ecf 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1742,6 +1742,7 @@ class AIService:if context:config['nodes'] = context.get('nodes', [])config['edges'] = context.get('edges', [])+ config['workspace_dir'] = context.get('workspace_dir', '')try:result = await execute_tool(tool_name, tool_args, config)@@ -2206,6 +2207,7 @@ class AIService:if context:config['nodes'] = context.get('nodes', [])config['edges'] = context.get('edges', [])+ config['workspace_dir'] = context.get('workspace_dir', '')try:# Execute via handlers/tools.py - same pattern as AI Agentdiff --git a/server/services/handlers/deep_agent.py b/server/services/handlers/deep_agent.pyindex 660038df..899d97fb 100644--- a/server/services/handlers/deep_agent.py+++ b/server/services/handlers/deep_agent.py@@ -65,6 +65,7 @@ async def handle_deep_agent(# 5. Pass workspace directory for filesystem toolsworkspace_dir = context.get('workspace_dir')+ logger.info("[Deep Agent] workspace_dir from context: %s", workspace_dir)if workspace_dir:parameters = {**parameters, 'workspace_dir': workspace_dir}diff --git a/server/services/handlers/filesystem.py b/server/services/handlers/filesystem.pyindex 73378fd8..4924a449 100644--- a/server/services/handlers/filesystem.py+++ b/server/services/handlers/filesystem.py@@ -14,11 +14,14 @@ from core.logging import get_loggerlogger = get_logger(__name__)-def _get_backend(parameters: Dict[str, Any]):- """Get a LocalShellBackend rooted at configured workspace."""+def _get_backend(parameters: Dict[str, Any], context: Dict[str, Any] = None):+ """Get a LocalShellBackend rooted at per-workflow workspace."""from deepagents.backends import LocalShellBackend- from core.container import container- root = parameters.get('working_directory') or container.settings().deep_agent_workspace or os.getcwd()+ param_dir = parameters.get('working_directory')+ ctx_dir = context.get('workspace_dir') if context else None+ root = param_dir or ctx_dir or os.getcwd()+ logger.info("[Filesystem] root=%s (param=%s, context=%s, fallback_cwd=%s)",+ root, param_dir, ctx_dir, os.getcwd())return LocalShellBackend(root_dir=root, virtual_mode=True)@@ -31,7 +34,7 @@ async def handle_file_read(return {"success": False, "node_id": node_id, "error": "file_path is required"}try:- backend = _get_backend(parameters)+ backend = _get_backend(parameters, context)content = backend.read(file_path, offset=int(parameters.get('offset', 0)), limit=int(parameters.get('limit', 100)))return {"success": True, "node_id": node_id,@@ -51,7 +54,7 @@ async def handle_file_modify(return {"success": False, "node_id": node_id, "error": "file_path is required"}try:- backend = _get_backend(parameters)+ backend = _get_backend(parameters, context)if operation == 'write':content = parameters.get('content', '')@@ -93,7 +96,7 @@ async def handle_shell(try:timeout = int(parameters.get('timeout', 30))- backend = _get_backend(parameters)+ backend = _get_backend(parameters, context)result = backend.execute(command, timeout=timeout)return {"success": True, "node_id": node_id,@@ -117,7 +120,7 @@ async def handle_fs_search(pattern = parameters.get('pattern', '')try:- backend = _get_backend(parameters)+ backend = _get_backend(parameters, context)if mode == 'ls':entries = backend.ls_info(path)diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex ebea7f2d..70b20458 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -47,8 +47,12 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],Tool execution result dict"""node_type = config.get('node_type', '')+ node_params = config.get('parameters', {})++ # Execution context available to all tool handlers (workspace, etc.)+ context = {'workspace_dir': config.get('workspace_dir', '')}- logger.debug(f"[Tool] Executing tool '{tool_name}' (node_type: {node_type})")+ logger.info("[Tool] Executing '%s' (node_type=%s, workspace=%s)", tool_name, node_type, context['workspace_dir'])# Calculator toolif node_type == 'calculatorTool':@@ -56,28 +60,28 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],# HTTP Request tool (existing httpRequest node as tool)if node_type in ('httpRequest', 'httpRequestTool'):- return await _execute_http_request(tool_args, config.get('parameters', {}))+ return await _execute_http_request(tool_args, node_params)# Python executor tool (dual-purpose: workflow node + AI tool)if node_type == 'pythonExecutor':- return await _execute_python_code(tool_args, config.get('parameters', {}))+ return await _execute_python_code(tool_args, node_params, context)# JavaScript executor tool (dual-purpose: workflow node + AI tool)if node_type == 'javascriptExecutor':- return await _execute_javascript_code(tool_args, config.get('parameters', {}))+ return await _execute_javascript_code(tool_args, node_params, context)# Current time toolif node_type == 'currentTimeTool':- return await _execute_current_time(tool_args, config.get('parameters', {}))+ return await _execute_current_time(tool_args, node_params)# DuckDuckGo search tool (free, no API key)if node_type == 'duckduckgoSearch':- return await _execute_duckduckgo_search(tool_args, config.get('parameters', {}))+ return await _execute_duckduckgo_search(tool_args, node_params)# Filesystem and shell tools (deepagents backends)if node_type in ('fileRead', 'fileModify', 'shell', 'fsSearch'):from services.handlers.filesystem import handle_file_read, handle_file_modify, handle_shell, handle_fs_search- params = {**config.get('parameters', {}), **tool_args}+ params = {**node_params, **tool_args}handler_map = {'fileRead': handle_file_read,'fileModify': handle_file_modify,@@ -88,7 +92,7 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],node_id=config.get('node_id', f'tool_{node_type}'),node_type=node_type,parameters=params,- context={},+ context=context,)# Timer tool (dual-purpose: workflow node + AI tool)@@ -346,15 +350,14 @@ async def _execute_http_request(args: Dict[str, Any],async def _execute_python_code(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:+ node_params: Dict[str, Any],+ context: Dict[str, Any] = None) -> Dict[str, Any]:"""Execute Python code (dual-purpose: workflow node + AI tool).Args:args: Dict with 'code' from LLM (when used as AI tool)node_params: Node parameters containing code (when used as workflow node), timeout, etc.-- Returns:- Dict with success, result, output, or error+ context: Execution context with workspace_dir for cwd"""import subprocessimport tempfile@@ -409,12 +412,14 @@ except Exception as e:temp_path = f.nametry:- logger.debug(f"[Python Tool] Executing code (timeout: {timeout}s)")+ cwd = (context or {}).get('workspace_dir') or None+ logger.debug(f"[Python Tool] Executing code (timeout: {timeout}s, cwd: {cwd})")result = subprocess.run(['python', temp_path],capture_output=True,text=True,- timeout=timeout+ timeout=timeout,+ cwd=cwd or None,)if result.returncode == 0:@@ -438,12 +443,14 @@ except Exception as e:async def _execute_javascript_code(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:+ node_params: Dict[str, Any],+ context: Dict[str, Any] = None) -> Dict[str, Any]:"""Execute JavaScript code (dual-purpose: workflow node + AI tool).Args:args: Dict with 'code' from LLM (when used as AI tool)node_params: Node parameters containing code (when used as workflow node), timeout, etc.+ context: Execution context with workspace_dir for cwdReturns:Dict with success, result, output, or error@@ -491,12 +498,14 @@ try {{temp_path = f.nametry:- logger.debug(f"[JavaScript Tool] Executing code (timeout: {timeout}s)")+ cwd = (context or {}).get('workspace_dir') or None+ logger.debug(f"[JavaScript Tool] Executing code (timeout: {timeout}s, cwd: {cwd})")result = subprocess.run(['node', temp_path],capture_output=True,text=True,- timeout=timeout+ timeout=timeout,+ cwd=cwd or None,)if result.returncode == 0:diff --git a/server/services/workflow.py b/server/services/workflow.pyindex 23692337..e2548931 100644--- a/server/services/workflow.py+++ b/server/services/workflow.py@@ -139,7 +139,9 @@ class WorkflowService:wf_id = workflow_id or "default"workspace = base / wf_idworkspace.mkdir(parents=True, exist_ok=True)- return str(workspace.resolve())+ resolved = str(workspace.resolve())+ logger.info("[Workspace] workflow_id=%s -> %s", wf_id, resolved)+ return resolvedasync def execute_node(self,