Skip to content

Self-improving AI Employees for everyone

feat: process manager node, workspace isolation, terminal skills, deep agent 200 turns

trohitg6a5064384f94
diff --git a/CLAUDE.md b/CLAUDE.md
index b2a8f80a..0d81eb85 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -416,7 +416,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **106 implemented workflow nodes** with clean service separation (9 AI models + 3 AI agents/memory + 16 specialized agents + 1 skill + 5 dedicated tools + 3 search + 16 Android + 3 WhatsApp + 4 Twitter + 2 Telegram + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 2 Workflow + 7 Google Workspace + 1 Apify + 1 Crawlee + 1 Browser + 3 Email + 3 Proxy + 4 Filesystem/Shell)
+- **107 implemented workflow nodes** with clean service separation (9 AI models + 3 AI agents/memory + 16 specialized agents + 1 skill + 5 dedicated tools + 3 search + 16 Android + 3 WhatsApp + 4 Twitter + 2 Telegram + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 2 Workflow + 7 Google Workspace + 1 Apify + 1 Crawlee + 1 Browser + 3 Email + 3 Proxy + 4 Filesystem/Shell + 1 Process Manager)
- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (89 message handlers)
- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated
@@ -623,9 +623,12 @@ server/skills/
│ ├── progressive-discovery-skill/SKILL.md
│ ├── error-recovery-skill/SKILL.md
│ └── multi-tool-orchestration-skill/SKILL.md
-├── coding_agent/ # Code execution skills
+├── coding_agent/ # Code execution & filesystem skills
│ ├── python-skill/SKILL.md
-│ └── javascript-skill/SKILL.md
+│ ├── javascript-skill/SKILL.md
+│ ├── file-read-skill/SKILL.md
+│ ├── file-modify-skill/SKILL.md
+│ └── fs-search-skill/SKILL.md
├── productivity_agent/ # Google Workspace skills
│ ├── gmail-skill/SKILL.md # Send, search, read emails
│ ├── calendar-skill/SKILL.md # Create, list, update, delete events
@@ -649,6 +652,12 @@ server/skills/
│ └── nearby-places-skill/SKILL.md
├── rlm_agent/ # Recursive Language Model agent skills
│ └── rlm-reasoning-skill/SKILL.md
+├── terminal/ # Shell, process management, OS-specific terminals
+│ ├── shell-skill/SKILL.md # Sandboxed shell (no system PATH)
+│ ├── process-manager-skill/SKILL.md # Long-running processes (full PATH, streams output)
+│ ├── bash-skill/SKILL.md # Linux/macOS terminal patterns
+│ ├── powershell-skill/SKILL.md # Windows terminal patterns
+│ └── wsl-skill/SKILL.md # WSL bridge for Linux tools on Windows
└── web_agent/ # Web automation skills
├── http-request-skill/SKILL.md
├── proxy-config-skill/SKILL.md
@@ -1367,11 +1376,11 @@ 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`. Uses per-workflow workspace from execution context (`context["workspace_dir"]` = `data/workspaces/<workflow_id>/`). `virtual_mode=True` confines paths within the workspace.
+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. Fallback uses `Settings().workspace_base_dir` (never `os.getcwd()`).
- **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).
-- **shell**: **Dual-purpose node** - Execute shell commands with timeout. Works as workflow node OR AI Agent tool (`shell_execute`). Returns stdout, exit_code, truncated flag.
+- **shell**: **Dual-purpose node** - Execute shell commands with timeout. Works as workflow node OR AI Agent tool (`shell_execute`). **Sandboxed: no system PATH** -- use process_manager for npm/python/node commands. All backend calls wrapped in `asyncio.to_thread()` to avoid blocking the event loop. Returns stdout, exit_code, truncated flag.
- **fsSearch**: **Dual-purpose node** - Search the filesystem with three modes. Works as workflow node OR AI Agent tool (`fs_search`). Modes: ls (list directory), glob (pattern match), grep (search file contents).
**Key Files:**
@@ -1379,7 +1388,28 @@ Dual-purpose tool nodes delegating to `deepagents.backends.LocalShellBackend`. U
|------|-------------|
| `client/src/nodeDefinitions/filesystemNodes.ts` | 4 dual-purpose node definitions |
| `server/services/handlers/filesystem.py` | Handlers delegating to `deepagents.backends.LocalShellBackend` |
-| `server/skills/coding_agent/` | Skills: file-read-skill, file-modify-skill, shell-skill, fs-search-skill |
+| `server/skills/coding_agent/` | Skills: file-read-skill, file-modify-skill, fs-search-skill |
+| `server/skills/terminal/` | Skills: shell-skill, process-manager-skill, bash-skill, powershell-skill, wsl-skill |
+
+### Process Manager Node (1 node)
+Cross-platform process manager for long-running subprocesses (dev servers, watchers, build tools). Uses `asyncio.create_subprocess_exec` with full system PATH (`env={**os.environ}`). Output streams to Terminal tab via `broadcast_terminal_log()` and persists to log files in the workspace.
+
+- **processManager**: **Dual-purpose node** - Start, stop, restart, and manage long-running processes. Works as workflow node OR AI Agent tool (`process_manager`). Operations: start, stop, restart, list, send_input, get_output. Max concurrent processes configurable in Settings (default: 10).
+
+**Key Architecture:**
+- **ProcessService** singleton (`server/services/process_service.py`) tracks running processes per workflow
+- Each process writes stdout/stderr to `{workspace}/{agent_node_id}/.processes/{name}/stdout.log` and `stderr.log`
+- AI agents read output selectively via `get_output(name, stream, tail)` with pagination
+- Process tree cleanup via `psutil.children(recursive=True)` on stop and server shutdown
+- `PYTHONUNBUFFERED=1` injected for line-buffered Python output
+
+**Key Files:**
+| File | Description |
+|------|-------------|
+| `server/services/process_service.py` | ProcessService singleton with start/stop/restart/list/send_input/get_output/shutdown |
+| `server/services/handlers/process.py` | Dual-purpose handler (workflow + AI tool) |
+| `client/src/nodeDefinitions/processNodes.ts` | Node definition with operation dropdown |
+| `server/skills/terminal/process-manager-skill/` | Skill for AI agents |
### Utility Nodes (6 nodes)
- **httpRequest**: Make HTTP requests to external APIs (GET, POST, PUT, DELETE, PATCH) with configurable headers, body, timeout, and optional proxy support (`useProxy: true` routes through configured residential proxy)
diff --git a/README.md b/README.md
index 3915944e..87a37e34 100644
--- a/README.md
+++ b/README.md
@@ -123,9 +123,11 @@ Create AI agents that remember conversations, use tools, and work together. Choo
- **16 Specialized Agents** - Android, Coding, Web, Task, Social, Travel, Tool, Productivity, Payments, Consumer, Autonomous, Orchestrator, AI Employee, RLM, Claude Code, Deep Agent
- **Team Monitor** - Real-time visualization of team operations
-### Run Code
+### Run Code & Manage Processes
- Execute Python, JavaScript, and TypeScript code
- Persistent Node.js server for fast JS/TS execution
+- **Process Manager** - Start, stop, and manage long-running processes (dev servers, watchers, build tools) with output streaming to Terminal tab
+- OS-specific terminal skills (Bash, PowerShell, WSL)
## Visual Workflow Builder
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index ce665639..7235e1fb 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -39,6 +39,7 @@ import { PROXY_NODE_TYPES } from './nodeDefinitions/proxyNodes';
import { CRAWLEE_NODE_TYPES } from './nodeDefinitions/crawleeNodes';
import { BROWSER_NODE_TYPES } from './nodeDefinitions/browserNodes';
import { FILESYSTEM_NODE_TYPES } from './nodeDefinitions/filesystemNodes';
+import { PROCESS_NODE_TYPES } from './nodeDefinitions/processNodes';
import { AI_CHAT_MODEL_TYPES } from './nodeDefinitions/aiModelNodes';
import ParameterPanel from './ParameterPanel';
import LocationParameterPanel from './components/LocationParameterPanel';
@@ -160,6 +161,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (FILESYSTEM_NODE_TYPES.includes(type)) {
// Filesystem & shell nodes use SquareNode component
types[type] = SquareNode;
+ } else if (PROCESS_NODE_TYPES.includes(type)) {
+ // Process manager nodes use SquareNode component
+ types[type] = SquareNode;
} else if (SOCIAL_NODE_TYPES.includes(type)) {
// Social nodes use AIAgentNode for multiple output handles support
types[type] = AIAgentNode;
diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsx
index 1edb4f5c..2f68c0ad 100644
--- a/client/src/components/ui/SettingsPanel.tsx
+++ b/client/src/components/ui/SettingsPanel.tsx
@@ -13,6 +13,7 @@ export interface WorkflowSettings {
consolePanelDefaultOpen: boolean;
memoryWindowSize: number;
compactionRatio: number;
+ maxProcesses: number;
}
export const defaultSettings: WorkflowSettings = {
@@ -23,6 +24,7 @@ export const defaultSettings: WorkflowSettings = {
consolePanelDefaultOpen: false,
memoryWindowSize: 100,
compactionRatio: 0.5,
+ maxProcesses: 10,
};
interface SettingsPanelProps {
@@ -66,6 +68,7 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
consolePanelDefaultOpen: dbSettings.console_panel_default_open ?? defaultSettings.consolePanelDefaultOpen,
memoryWindowSize: dbSettings.memory_window_size ?? defaultSettings.memoryWindowSize,
compactionRatio: dbSettings.compaction_ratio ?? defaultSettings.compactionRatio,
+ maxProcesses: dbSettings.max_processes ?? defaultSettings.maxProcesses,
});
}
} catch (error) {
@@ -87,6 +90,7 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
console_panel_default_open: newSettings.consolePanelDefaultOpen,
memory_window_size: newSettings.memoryWindowSize,
compaction_ratio: newSettings.compactionRatio,
+ max_processes: newSettings.maxProcesses,
}
});
if (showMessage) {
@@ -472,6 +476,31 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
</div>
</div>
+ {/* Process Manager Section */}
+ <div style={sectionStyle}>
+ <div style={sectionHeaderStyle}>
+ <div style={{ ...sectionIconStyle, backgroundColor: `${theme.dracula.orange}20` }}>{'\u2699\uFE0F'}</div>
+ <div style={sectionTitleStyle}>Process Manager</div>
+ </div>
+
+ <div style={settingRowStyle}>
+ <div style={settingLabelStyle}>
+ <div style={labelTextStyle}>Max Concurrent Processes</div>
+ <div style={descriptionStyle}>Maximum number of running processes per workflow (1-50)</div>
+ </div>
+ <InputNumber
+ size="small"
+ min={1}
+ max={50}
+ step={1}
+ value={settings.maxProcesses ?? 10}
+ onChange={(value) => handleChange('maxProcesses', value ?? 10)}
+ disabled={isSaving}
+ style={{ width: 80 }}
+ />
+ </div>
+ </div>
+
{/* Help Section */}
<div style={sectionStyle}>
<div style={sectionHeaderStyle}>
diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.ts
index b5d79bfc..162c9190 100644
--- a/client/src/nodeDefinitions.ts
+++ b/client/src/nodeDefinitions.ts
@@ -27,6 +27,7 @@ import { proxyNodes, PROXY_NODE_TYPES } from './nodeDefinitions/proxyNodes';
import { crawleeNodes, CRAWLEE_NODE_TYPES } from './nodeDefinitions/crawleeNodes';
import { browserNodes, BROWSER_NODE_TYPES } from './nodeDefinitions/browserNodes';
import { filesystemNodes, FILESYSTEM_NODE_TYPES } from './nodeDefinitions/filesystemNodes';
+import { processNodes } from './nodeDefinitions/processNodes';
import { emailNodes, EMAIL_NODE_TYPES } from './nodeDefinitions/emailNodes';
@@ -60,6 +61,7 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {
...crawleeNodes,
...browserNodes,
...filesystemNodes,
+ ...processNodes,
...emailNodes
};
diff --git a/client/src/nodeDefinitions/processNodes.ts b/client/src/nodeDefinitions/processNodes.ts
new file mode 100644
index 00000000..47462aae
--- /dev/null
+++ b/client/src/nodeDefinitions/processNodes.ts
@@ -0,0 +1,104 @@
+// Process Manager Node -- start, stop, and manage long-running processes
+// Dual-purpose: workflow node AND AI Agent tool
+
+import {
+ INodeTypeDescription,
+ NodeConnectionType,
+} from '../types/INodeProperties';
+import { dracula } from '../styles/theme';
+
+export const processNodes: Record<string, INodeTypeDescription> = {
+ processManager: {
+ displayName: 'Process Manager',
+ name: 'processManager',
+ icon: '\u{2699}\u{FE0F}',
+ group: ['utility', 'tool'],
+ version: 1,
+ subtitle: 'Manage Processes',
+ description: 'Start, stop, and manage long-running processes (dev servers, watchers, build tools). Streams output to Terminal tab.',
+ defaults: { name: 'Process Manager', color: dracula.orange },
+ inputs: [
+ { name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Input data' },
+ ],
+ outputs: [
+ { name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'Process operation result' },
+ { name: 'tool', displayName: 'Tool', type: 'main' as NodeConnectionType, description: 'Connect to AI Agent tool handle' },
+ ],
+ properties: [
+ // Tool config
+ {
+ displayName: 'Tool Name',
+ name: 'toolName',
+ type: 'string',
+ default: 'process_manager',
+ description: 'Name of this tool when used by AI Agent',
+ },
+ {
+ displayName: 'Tool Description',
+ name: 'toolDescription',
+ type: 'string',
+ default: 'Start, stop, and manage long-running processes. Use for dev servers, watchers, build tools. Output streams to Terminal.',
+ typeOptions: { rows: 2 },
+ description: 'Description shown to AI Agent',
+ },
+
+ // Operation
+ {
+ displayName: 'Operation',
+ name: 'operation',
+ type: 'options',
+ default: 'start',
+ options: [
+ { name: 'Start', value: 'start', description: 'Start a new process' },
+ { name: 'Stop', value: 'stop', description: 'Stop a running process' },
+ { name: 'Restart', value: 'restart', description: 'Restart a process' },
+ { name: 'Send Input', value: 'send_input', description: 'Send text to process stdin' },
+ { name: 'List', value: 'list', description: 'List running processes' },
+ { name: 'Get Output', value: 'get_output', description: 'Get buffered output history' },
+ ],
+ description: 'Process operation to perform',
+ },
+
+ // Conditional parameters
+ {
+ displayName: 'Process Name',
+ name: 'name',
+ type: 'string',
+ default: '',
+ placeholder: 'my-server',
+ description: 'Unique name for this process',
+ displayOptions: { show: { operation: ['start', 'stop', 'restart', 'send_input', 'get_output'] } },
+ },
+ {
+ displayName: 'Command',
+ name: 'command',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'python -m http.server 8080',
+ description: 'Shell command to run as a long-lived process',
+ displayOptions: { show: { operation: ['start'] } },
+ },
+ {
+ displayName: 'Working Directory',
+ name: 'working_directory',
+ type: 'string',
+ default: '',
+ placeholder: 'Uses workflow workspace if empty',
+ description: 'Working directory for the process',
+ displayOptions: { show: { operation: ['start'] } },
+ },
+ {
+ displayName: 'Input Text',
+ name: 'text',
+ type: 'string',
+ default: '',
+ placeholder: 'Text to send to stdin',
+ description: 'Text to write to the process stdin (newline appended automatically)',
+ displayOptions: { show: { operation: ['send_input'] } },
+ },
+ ],
+ },
+};
+
+export const PROCESS_NODE_TYPES = ['processManager'];
diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.ts
index c8965bbf..108ab38e 100644
--- a/client/src/nodeDefinitions/specializedAgentNodes.ts
+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts
@@ -548,8 +548,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {
displayName: 'Max Turns',
name: 'maxTurns',
type: 'number' as any,
- default: 25,
- typeOptions: { minValue: 1, maxValue: 100 },
+ default: 200,
+ typeOptions: { minValue: 1, maxValue: 500 },
description: 'Maximum agentic loop iterations',
},
],
diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.ts
index d8a4bb7c..5cb2ecca 100644
--- a/client/src/services/executionService.ts
+++ b/client/src/services/executionService.ts
@@ -249,6 +249,8 @@ export class ExecutionService {
'fsSearch',
// Todo planning
'writeTodos',
+ // Process manager
+ 'processManager',
// Email (Himalaya CLI)
...EMAIL_NODE_TYPES,
];
diff --git a/server/config/model_registry.json b/server/config/model_registry.json
index 6175adfc..2048c2ae 100644
--- a/server/config/model_registry.json
+++ b/server/config/model_registry.json
@@ -1,7 +1,7 @@
{
- "_generated": "2026-04-11T22:43:55.565493+00:00",
+ "_generated": "2026-04-12T22:46:31.828259+00:00",
"_source": "openrouter",
- "_model_count": 350,
+ "_model_count": 349,
"models": {
"anthropic/claude-opus-4.6-fast": {
"id": "anthropic/claude-opus-4.6-fast",
@@ -1389,7 +1389,7 @@
"provider": "minimax",
"local_id": "minimax-m2.5:free",
"context_length": 196608,
- "max_output_tokens": 196608,
+ "max_output_tokens": 8192,
"input_price_per_mtok": 0.0,
"output_price_per_mtok": 0.0,
"supports_thinking": false,
@@ -1556,9 +1556,9 @@
"provider": "qwen",
"local_id": "qwen3-coder-next",
"context_length": 262144,
- "max_output_tokens": 65536,
- "input_price_per_mtok": 0.12,
- "output_price_per_mtok": 0.75,
+ "max_output_tokens": 262144,
+ "input_price_per_mtok": 0.15,
+ "output_price_per_mtok": 0.8,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -5126,7 +5126,7 @@
"provider": "openai",
"local_id": "gpt-oss-20b:free",
"context_length": 131072,
- "max_output_tokens": 131072,
+ "max_output_tokens": 8192,
"input_price_per_mtok": 0.0,
"output_price_per_mtok": 0.0,
"supports_thinking": true,
@@ -6270,8 +6270,8 @@
"provider": "deepseek",
"local_id": "deepseek-r1-0528",
"context_length": 163840,
- "max_output_tokens": 65536,
- "input_price_per_mtok": 0.45,
+ "max_output_tokens": 0,
+ "input_price_per_mtok": 0.5,
"output_price_per_mtok": 2.15,
"supports_thinking": false,
"thinking_type": "none",
@@ -7012,35 +7012,6 @@
"top_p"
]
},
- "eleutherai/llemma_7b": {
- "id": "eleutherai/llemma_7b",
- "name": "EleutherAI: Llemma 7b",
- "provider": "eleutherai",
- "local_id": "llemma_7b",
- "context_length": 4096,
- "max_output_tokens": 4096,
- "input_price_per_mtok": 0.8,
- "output_price_per_mtok": 1.2,
- "supports_thinking": false,
- "thinking_type": "none",
- "temperature_range": [
- 0.0,
- 2.0
- ],
- "is_reasoning_model": false,
- "supported_parameters": [
- "frequency_penalty",
- "max_tokens",
- "min_p",
- "presence_penalty",
- "repetition_penalty",
- "seed",
- "stop",
- "temperature",
- "top_k",
- "top_p"
- ]
- },
"alfredpros/codellama-7b-instruct-solidity": {
"id": "alfredpros/codellama-7b-instruct-solidity",
"name": "AlfredPros: CodeLLaMa 7B Instruct Solidity",
@@ -9120,6 +9091,36 @@
"top_p"
]
},
+ "meta/llama-3.2-11b-vision-instruct": {
+ "id": "meta-llama/llama-3.2-11b-vision-instruct",
+ "name": "Meta: Llama 3.2 11B Vision Instruct",
+ "provider": "meta",
+ "local_id": "llama-3.2-11b-vision-instruct",
+ "context_length": 131072,
+ "max_output_tokens": 16384,
+ "input_price_per_mtok": 0.245,
+ "output_price_per_mtok": 0.245,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "frequency_penalty",
+ "max_tokens",
+ "min_p",
+ "presence_penalty",
+ "repetition_penalty",
+ "response_format",
+ "seed",
+ "stop",
+ "temperature",
+ "top_k",
+ "top_p"
+ ]
+ },
"meta/llama-3.2-3b-instruct:free": {
"id": "meta-llama/llama-3.2-3b-instruct:free",
"name": "Meta: Llama 3.2 3B Instruct (free)",
@@ -9200,36 +9201,6 @@
"top_p"
]
},
- "meta/llama-3.2-11b-vision-instruct": {
- "id": "meta-llama/llama-3.2-11b-vision-instruct",
- "name": "Meta: Llama 3.2 11B Vision Instruct",
- "provider": "meta",
- "local_id": "llama-3.2-11b-vision-instruct",
- "context_length": 131072,
- "max_output_tokens": 16384,
- "input_price_per_mtok": 0.245,
- "output_price_per_mtok": 0.245,
- "supports_thinking": false,
- "thinking_type": "none",
- "temperature_range": [
- 0.0,
- 2.0
- ],
- "is_reasoning_model": false,
- "supported_parameters": [
- "frequency_penalty",
- "max_tokens",
- "min_p",
- "presence_penalty",
- "repetition_penalty",
- "response_format",
- "seed",
- "stop",
- "temperature",
- "top_k",
- "top_p"
- ]
- },
"qwen/qwen-2.5-72b-instruct": {
"id": "qwen/qwen-2.5-72b-instruct",
"name": "Qwen2.5 72B Instruct",
diff --git a/server/constants.py b/server/constants.py
index 28e028ba..55a1b41b 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -54,6 +54,7 @@ AI_TOOL_TYPES: FrozenSet[str] = frozenset([
'duckduckgoSearch',
'androidTool',
'writeTodos',
+ 'processManager',
])
# Skill node types (connect to Zeenie's input-skill handle)
diff --git a/server/main.py b/server/main.py
index 69bfce59..696dee53 100644
--- a/server/main.py
+++ b/server/main.py
@@ -170,6 +170,18 @@ async def lifespan(app: FastAPI):
from services.agent_team import init_agent_team_service
from services.status_broadcaster import get_status_broadcaster
init_agent_team_service(container.database(), get_status_broadcaster())
+
+ # Wire process service to broadcaster for Terminal tab streaming
+ from services.process_service import get_process_service
+ proc_svc = get_process_service()
+ proc_svc.set_broadcaster(get_status_broadcaster())
+ # Load max_processes from user settings if configured
+ try:
+ user_settings = await container.database().get_user_settings("default")
+ if user_settings and "max_processes" in user_settings:
+ proc_svc.max_processes = int(user_settings["max_processes"])
+ except Exception:
+ pass
logger.info("Agent team service initialized")
# Initialize proxy service (loads providers from DB, reads credentials)
@@ -306,6 +318,10 @@ async def lifespan(app: FastAPI):
from services.browser_service import shutdown_browser_service
await shutdown_browser_service()
+ # Kill all managed processes (process manager node)
+ from services.process_service import shutdown_process_service
+ await shutdown_process_service()
+
# Stop cleanup service
if cleanup_service is not None:
await cleanup_service.stop()
diff --git a/server/package.json b/server/package.json
index 46308863..24a33544 100644
--- a/server/package.json
+++ b/server/package.json
@@ -5,5 +5,9 @@
"scripts": {
"start": "python -m uvicorn main:app --host 0.0.0.0 --port ${PORT:-3010}",
"dev": "python -m uvicorn main:app --host 127.0.0.1 --port ${PORT:-3010} --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning"
+ },
+ "dependencies": {
+ "express": "^5.2.1",
+ "morgan": "^1.10.1"
}
}
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index ee44e9e4..f3302cc4 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -2247,6 +2247,41 @@ async def handle_clear_terminal_logs(data: Dict[str, Any], websocket: WebSocket)
return {"success": True, "message": "Terminal logs cleared"}
+# =============================================================================
+# Process Manager Handlers
+# =============================================================================
+
+@ws_handler()
+async def handle_process_list(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """List running processes."""
+ from services.process_service import get_process_service
+ svc = get_process_service()
+ workflow_id = data.get("workflow_id", "default")
+ return {"success": True, "processes": svc.list_processes(workflow_id), "max_processes": svc.max_processes}
+
+
+@ws_handler("name")
+async def handle_process_get_output(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get output from a process's log file."""
+ from services.process_service import get_process_service
+ name = data["name"]
+ workflow_id = data.get("workflow_id", "default")
+ stream = data.get("stream", "stdout")
+ tail = int(data.get("tail", 50))
+ offset = int(data.get("offset", 0))
+ return {"success": True, **get_process_service().get_output(name, workflow_id, stream, tail, offset)}
+
+
+@ws_handler("name", "text")
+async def handle_process_send_input(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Send stdin text to a running process."""
+ from services.process_service import get_process_service
+ name = data["name"]
+ text = data["text"]
+ workflow_id = data.get("workflow_id", "default")
+ return await get_process_service().send_input(name, workflow_id, text)
+
+
# ============================================================================
# User Skills Handlers
# ============================================================================
@@ -2616,6 +2651,11 @@ async def handle_save_user_settings(data: Dict[str, Any], websocket: WebSocket)
success = await database.save_user_settings(settings_data, user_id)
if success:
+ # Sync process limit if changed
+ if "max_processes" in settings_data:
+ from services.process_service import get_process_service
+ get_process_service().max_processes = int(settings_data["max_processes"])
+
# Fetch the saved settings to return
settings = await database.get_user_settings(user_id)
return {"settings": settings}
@@ -3131,6 +3171,11 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"get_terminal_logs": handle_get_terminal_logs,
"clear_terminal_logs": handle_clear_terminal_logs,
+ # Process Manager
+ "process_list": handle_process_list,
+ "process_get_output": handle_process_get_output,
+ "process_send_input": handle_process_send_input,
+
# User Skills
"get_user_skills": handle_get_user_skills,
"get_user_skill": handle_get_user_skill,
diff --git a/server/services/agents/constants.py b/server/services/agents/constants.py
index d9808090..a342d7c6 100644
--- a/server/services/agents/constants.py
+++ b/server/services/agents/constants.py
@@ -7,4 +7,4 @@ PROVIDER_PREFIX = {
"gemini": "google_genai",
}
-DEFAULT_MAX_TURNS = 25
+DEFAULT_MAX_TURNS = 200
diff --git a/server/services/agents/service.py b/server/services/agents/service.py
index 315ef0b1..4a068626 100644
--- a/server/services/agents/service.py
+++ b/server/services/agents/service.py
@@ -4,6 +4,7 @@ Delegates to adapters for protocol translation and reuses
shared helpers from ai.py for config resolution and memory.
"""
+import os
import time
import warnings
from datetime import datetime
@@ -112,7 +113,11 @@ class DeepAgentService:
executable_tools = []
if tool_data and build_tool_fn:
await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)..."})
- workspace_dir = parameters.get('workspace_dir', '')
+ # Each agent gets its own subfolder: {workspace}/{node_id}/
+ base_workspace = parameters.get('workspace_dir', '')
+ workspace_dir = os.path.join(base_workspace, node_id) if base_workspace else ''
+ if workspace_dir:
+ os.makedirs(workspace_dir, exist_ok=True)
executable_tools = await ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir)
# If write_todos tool is connected, add planning instructions to system message
diff --git a/server/services/ai.py b/server/services/ai.py
index 269637a0..47760ca3 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2438,6 +2438,7 @@ class AIService:
'perplexitySearch': 'perplexity_search',
'taskManager': 'task_manager',
'writeTodos': 'write_todos',
+ 'processManager': 'process_manager',
'timer': 'timer',
'cronScheduler': 'cron_scheduler',
# Filesystem and shell tools (deepagents backends)
@@ -2518,6 +2519,7 @@ class AIService:
'gmaps_nearby_places': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.',
'taskManager': 'Track delegated sub-agent tasks. Operations: list_tasks (see all tasks), get_task (check specific task status/result), mark_done (cleanup completed tasks).',
'writeTodos': 'Create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. Only use this tool if you think it will be helpful in staying organized. If the user\'s request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly. Use for complex multi-step tasks (3+ steps), non-trivial planning, or when user explicitly requests a todo list. Task states: pending, in_progress, completed. Mark tasks as in_progress BEFORE beginning work, completed IMMEDIATELY after finishing. Remove irrelevant tasks. Break complex tasks into smaller steps.',
+ 'processManager': 'Start, stop, and manage long-running processes (dev servers, watchers, build tools). Operations: start (spawn a process), stop (kill process tree), restart, list (show all running), send_input (write to stdin), get_output (read recent output lines). Output streams to Terminal tab. Use get_output to check what a process printed.',
'timer': 'Wait/sleep for a specified duration. Specify duration (1-3600) and unit (seconds, minutes, or hours). Returns timestamp and elapsed time after waiting.',
'cronScheduler': 'Schedule a delayed or recurring execution. Supports seconds, minutes, hours, daily, weekly, monthly frequencies with timezone. Use frequency to set schedule type, then set the relevant interval/time parameters.',
# Filesystem and shell tools (deepagents backends)
@@ -3266,6 +3268,29 @@ class AIService:
return WriteTodosSchema
+ # Process Manager schema (dual-purpose: AI tool + workflow node)
+ if node_type == 'processManager':
+ class ProcessManagerSchema(BaseModel):
+ """Start, stop, and manage long-running processes.
+
+ Use for dev servers, watchers, build tools. Use get_output to read process output.
+ - start: Launch a process (requires command)
+ - stop: Kill a process by name
+ - restart: Stop then start with same command
+ - list: Show all running processes
+ - send_input: Write text to process stdin
+ - get_output: Read recent output lines from a process
+ """
+ operation: str = Field(description="Operation: start, stop, restart, list, send_input, get_output")
+ name: Optional[str] = Field(default=None, description="Process name (required for stop/restart/send_input/get_output)")
+ command: Optional[str] = Field(default=None, description="Shell command to run (required for start)")
+ working_directory: Optional[str] = Field(default=None, description="Working directory for the process")
+ text: Optional[str] = Field(default=None, description="Text to send to stdin (for send_input)")
+ stream: Optional[str] = Field(default="stdout", description="Which stream to read: stdout or stderr (for get_output)")
+ tail: Optional[int] = Field(default=50, description="Number of lines from end to return, 0 for all (for get_output)")
+
+ return ProcessManagerSchema
+
# Task Manager schema (dual-purpose: AI tool + workflow node)
if node_type == 'taskManager':
class TaskManagerSchema(BaseModel):
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index 9f769d0e..bb440ad8 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -143,6 +143,9 @@ from .tools import (
# Todo handler
from .todo import execute_write_todos, handle_write_todos
+# Process manager handler
+from .process import execute_process_manager, handle_process_manager
+
__all__ = [
# AI
'handle_ai_agent',
diff --git a/server/services/handlers/filesystem.py b/server/services/handlers/filesystem.py
index 5ce4c4fe..ed4bbbef 100644
--- a/server/services/handlers/filesystem.py
+++ b/server/services/handlers/filesystem.py
@@ -21,12 +21,13 @@ logger = get_logger(__name__)
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.config import Settings
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, inherit_env=True)
+ root = param_dir or ctx_dir or os.path.join(Settings().workspace_base_dir, 'default')
+ os.makedirs(root, exist_ok=True)
+ logger.info("[Filesystem] root=%s", root)
+ return LocalShellBackend(root_dir=root, virtual_mode=True)
async def handle_file_read(
diff --git a/server/services/handlers/process.py b/server/services/handlers/process.py
new file mode 100644
index 00000000..7cd7400f
--- /dev/null
+++ b/server/services/handlers/process.py
@@ -0,0 +1,75 @@
+"""Process manager handler -- dual-purpose (workflow node + AI tool).
+
+Follows the same pattern as handlers/todo.py.
+"""
+
+import os
+import time
+from typing import Any, Dict
+
+from core.logging import get_logger
+from services.process_service import get_process_service
+
+logger = get_logger(__name__)
+
+
+async def handle_process_manager(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Workflow node entry point."""
+ t0 = time.time()
+ workflow_id = context.get("workflow_id", "default")
+ workspace_dir = context.get("workspace_dir", "")
+
+ # Each agent node gets its own subfolder in the workspace
+ agent_dir = os.path.join(workspace_dir, node_id) if workspace_dir else ""
+
+ tool_args = {
+ "operation": parameters.get("operation", "list"),
+ "name": parameters.get("name", ""),
+ "command": parameters.get("command", ""),
+ "working_directory": parameters.get("working_directory", "") or agent_dir,
+ "text": parameters.get("text", ""),
+ }
+ config = {"workflow_id": workflow_id, "workspace_dir": agent_dir}
+
+ result = await execute_process_manager(tool_args, config)
+ result["node_id"] = node_id
+ result["execution_time"] = time.time() - t0
+ return result
+
+
+async def execute_process_manager(tool_args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:
+ """AI tool entry point. Dispatches by operation."""
+ svc = get_process_service()
+ op = tool_args.get("operation", "list")
+ workflow_id = config.get("workflow_id", "default")
+ name = tool_args.get("name", "")
+
+ logger.info("[ProcessManager] op=%s name=%s", op, name)
+
+ if op == "start":
+ return await svc.start(
+ name=name,
+ command=tool_args.get("command", ""),
+ workflow_id=workflow_id,
+ working_directory=tool_args.get("working_directory", config.get("workspace_dir", "")),
+ )
+ elif op == "stop":
+ return await svc.stop(name, workflow_id)
+ elif op == "restart":
+ return await svc.restart(name, workflow_id)
+ elif op == "send_input":
+ return await svc.send_input(name, workflow_id, tool_args.get("text", ""))
+ elif op == "list":
+ return {"success": True, "result": {"processes": svc.list_processes(workflow_id)}}
+ elif op == "get_output":
+ stream = tool_args.get("stream", "stdout")
+ tail = int(tool_args.get("tail", 50))
+ offset = int(tool_args.get("offset", 0))
+ return {"success": True, "result": svc.get_output(name, workflow_id, stream, tail, offset)}
+ else:
+ return {"success": False, "error": f"Unknown operation: {op}"}
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 64f2968b..c0d9f2b7 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -189,6 +189,11 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
from services.handlers.todo import execute_write_todos
return await execute_write_todos(tool_args, config)
+ # Process Manager (dual-purpose: AI tool + workflow node)
+ if node_type == 'processManager':
+ from services.handlers.process import execute_process_manager
+ return await execute_process_manager(tool_args, config)
+
# Task Manager (dual-purpose: AI tool + workflow node)
if node_type == 'taskManager':
return await _execute_task_manager(tool_args, config)
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index a07f71e7..243a9444 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -49,6 +49,7 @@ from services.handlers.browser import handle_browser
from services.handlers.proxy import handle_proxy_request, handle_proxy_status, handle_proxy_config
from services.handlers.filesystem import handle_file_read, handle_file_modify, handle_shell, handle_fs_search
from services.handlers.todo import handle_write_todos
+from services.handlers.process import handle_process_manager
from services.handlers.email import handle_email_send, handle_email_read, handle_email_receive
# Consolidated Google Workspace handlers (6 services with operation dispatchers)
from services.handlers.gmail import handle_google_gmail, handle_gmail_receive
@@ -198,6 +199,8 @@ class NodeExecutor:
'taskManager': handle_task_manager,
# Todo planning (dual-purpose: workflow node + AI tool)
'writeTodos': handle_write_todos,
+ # Process manager (dual-purpose: workflow node + AI tool)
+ 'processManager': handle_process_manager,
# Team monitoring
'teamMonitor': handle_team_monitor,
# Apify web scraping
diff --git a/server/services/process_service.py b/server/services/process_service.py
new file mode 100644
index 00000000..f3291312
--- /dev/null
+++ b/server/services/process_service.py
@@ -0,0 +1,381 @@
+"""Cross-platform process manager for long-running subprocesses.
+
+Manages lifecycle (start/stop/restart), streams stdout/stderr to the
+Terminal tab via broadcast_terminal_log(), and persists output to temp
+log files so AI agents can fetch output selectively.
+
+Uses stdlib asyncio.create_subprocess_exec -- no third-party deps beyond
+psutil (already a project dependency for process tree killing).
+"""
+
+import asyncio
+import os
+import shlex
+import shutil
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+import psutil
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+MAX_PROCESSES = 10 # Default limit, configurable via Settings panel
+
+
+@dataclass
+class ManagedProcess:
+ name: str
+ command: str
+ argv: List[str]
+ pid: int
+ status: str # running, stopped, error
+ started_at: str
+ workflow_id: str
+ working_directory: str
+ process: asyncio.subprocess.Process
+ log_dir: Path # temp directory for stdout.log / stderr.log
+ stdout_task: Optional[asyncio.Task] = None
+ stderr_task: Optional[asyncio.Task] = None
+ exit_code: Optional[int] = None
+ stdout_lines: int = 0
+ stderr_lines: int = 0
+
+
+class ProcessService:
+ """Singleton managing long-running subprocesses per workflow.
+
+ Output is written to temp files at {tmp}/machina-proc-{name}/stdout.log
+ and stderr.log. AI agents read them via get_output() with tail/offset.
+ Files are cleaned up on stop or shutdown.
+ """
+
+ def __init__(self) -> None:
+ self._processes: Dict[tuple, ManagedProcess] = {}
+ self._broadcaster = None
+ self.max_processes: int = MAX_PROCESSES
+
+ def set_broadcaster(self, broadcaster) -> None:
+ self._broadcaster = broadcaster
+
+ def _key(self, workflow_id: str, name: str) -> tuple:
+ return (workflow_id, name)
+
+ async def start(
+ self,
+ name: str,
+ command: str,
+ workflow_id: str = "default",
+ working_directory: str = "",
+ ) -> Dict[str, Any]:
+ """Start a long-running process."""
+ if not command:
+ return {"success": False, "error": "command is required"}
+
+ # Block destructive commands -- file ops should use the sandboxed shell node
+ cmd_lower = command.lower().strip()
+ blocked = (
+ "rm ", "rm\t", "rmdir", "del ", "rd ", "remove-item",
+ "format ", "mkfs", "dd if=", "shred",
+ "> /dev/", "chmod 777", "chmod -r",
+ )
+ if any(cmd_lower.startswith(b) or f" {b}" in f" {cmd_lower}" for b in blocked):
+ return {
+ "success": False,
+ "error": f"Destructive commands blocked in process_manager. "
+ f"Use shell_execute for file operations (sandboxed, no PATH).",
+ }
+
+ name = name or f"proc_{id(command) % 100000}"
+ key = self._key(workflow_id, name)
+
+ # Check process limit (exclude stopped/error -- only count running)
+ running = sum(1 for m in self._processes.values() if m.status == "running")
+ if key not in self._processes and running >= self.max_processes:
+ return {"success": False, "error": f"Process limit reached ({self.max_processes}). Stop a process first."}
+
+ # Stop existing process with same name
+ if key in self._processes and self._processes[key].status == "running":
+ await self.stop(name, workflow_id)
+
+ argv = shlex.split(command)
+ env = {**os.environ, "PYTHONUNBUFFERED": "1"}
+ cwd = working_directory or os.getcwd()
+
+ # Create log directory inside the workflow workspace
+ # Layout: {workspace}/.processes/{name}/stdout.log, stderr.log
+ log_dir = Path(cwd) / ".processes" / name
+ log_dir.mkdir(parents=True, exist_ok=True)
+ # Clear old logs if restarting
+ for f in ("stdout.log", "stderr.log"):
+ (log_dir / f).write_text("")
+
+ logger.info("[Process] Starting: %s (name=%s, cwd=%s, logs=%s)", command[:200], name, cwd, log_dir)
+
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=cwd,
+ env=env,
+ )
+ except Exception as e:
+ logger.error("[Process] Failed to start: %s -> %s", command[:100], e)
+ return {"success": False, "error": str(e)}
+
+ managed = ManagedProcess(
+ name=name,
+ command=command,
+ argv=argv,
+ pid=proc.pid,
+ status="running",
+ started_at=datetime.now().isoformat(),
+ workflow_id=workflow_id,
+ working_directory=cwd,
+ process=proc,
+ log_dir=log_dir,
+ )
+
+ managed.stdout_task = asyncio.create_task(
+ self._read_stream(managed, proc.stdout, "stdout"),
+ name=f"proc-stdout-{name}",
+ )
+ managed.stderr_task = asyncio.create_task(
+ self._read_stream(managed, proc.stderr, "stderr"),
+ name=f"proc-stderr-{name}",
+ )
+
+ self._processes[key] = managed
+
+ logger.info("[Process] Started: %s (pid=%d)", name, proc.pid)
+ return {"success": True, "result": self._info(managed)}
+
+ async def stop(self, name: str, workflow_id: str = "default") -> Dict[str, Any]:
+ """Stop a running process by killing its process tree."""
+ key = self._key(workflow_id, name)
+ managed = self._processes.get(key)
+ if not managed:
+ return {"success": False, "error": f"Process '{name}' not found"}
+
+ if managed.status != "running":
+ return {"success": True, "result": self._info(managed)}
+
+ logger.info("[Process] Stopping: %s (pid=%d)", name, managed.pid)
+ _kill_process_tree(managed.pid)
+ managed.status = "stopped"
+
+ for task in (managed.stdout_task, managed.stderr_task):
+ if task and not task.done():
+ task.cancel()
+
+ try:
+ managed.exit_code = await asyncio.wait_for(managed.process.wait(), timeout=3)
+ except asyncio.TimeoutError:
+ managed.exit_code = -1
+
+ logger.info("[Process] Stopped: %s (exit=%s)", name, managed.exit_code)
+ return {"success": True, "result": self._info(managed)}
+
+ async def restart(self, name: str, workflow_id: str = "default") -> Dict[str, Any]:
+ """Restart a process with the same command."""
+ key = self._key(workflow_id, name)
+ managed = self._processes.get(key)
+ if not managed:
+ return {"success": False, "error": f"Process '{name}' not found"}
+
+ command = managed.command
+ cwd = managed.working_directory
+ await self.stop(name, workflow_id)
+ return await self.start(name, command, workflow_id, cwd)
+
+ async def send_input(self, name: str, workflow_id: str, text: str) -> Dict[str, Any]:
+ """Write text to a process's stdin."""
+ key = self._key(workflow_id, name)
+ managed = self._processes.get(key)
+ if not managed:
+ return {"success": False, "error": f"Process '{name}' not found"}
+ if managed.status != "running":
+ return {"success": False, "error": f"Process '{name}' is {managed.status}"}
+
+ stdin = managed.process.stdin
+ if not stdin:
+ return {"success": False, "error": "Process has no stdin"}
+
+ data = text if text.endswith("\n") else text + "\n"
+ stdin.write(data.encode())
+ await stdin.drain()
+
+ logger.info("[Process] Sent input to %s: %s", name, text[:100])
+ return {"success": True, "result": {"sent": text}}
+
+ def list_processes(self, workflow_id: str = "default") -> List[Dict[str, Any]]:
+ """List all processes for a workflow."""
+ return [
+ self._info(m)
+ for (wid, _), m in self._processes.items()
+ if wid == workflow_id
+ ]
+
+ def get_output(
+ self,
+ name: str,
+ workflow_id: str = "default",
+ stream: str = "stdout",
+ tail: int = 50,
+ offset: int = 0,
+ ) -> Dict[str, Any]:
+ """Read output from a process's log file.
+
+ Args:
+ stream: 'stdout' or 'stderr'
+ tail: Number of lines from the end (0 = all lines)
+ offset: Skip first N lines (only when tail=0)
+ """
+ key = self._key(workflow_id, name)
+ managed = self._processes.get(key)
+ if not managed:
+ return {"lines": [], "total": 0, "file": ""}
+
+ log_file = managed.log_dir / f"{stream}.log"
+ if not log_file.exists():
+ return {"lines": [], "total": 0, "file": str(log_file)}
+
+ all_lines = log_file.read_text(errors="replace").splitlines()
+ total = len(all_lines)
+
+ if tail > 0:
+ lines = all_lines[-tail:]
+ else:
+ lines = all_lines[offset:]
+
+ return {"lines": lines, "total": total, "file": str(log_file)}
+
+ def cleanup_logs(self, name: str, workflow_id: str = "default") -> None:
+ """Remove log files for a process."""
+ key = self._key(workflow_id, name)
+ managed = self._processes.get(key)
+ if managed and managed.log_dir.exists():
+ shutil.rmtree(managed.log_dir, ignore_errors=True)
+ logger.info("[Process] Cleaned logs: %s", managed.log_dir)
+
+ async def shutdown(self) -> None:
+ """Kill all managed processes and clean up log files."""
+ if not self._processes:
+ return
+ logger.info("[Process] Shutting down %d process(es)", len(self._processes))
+ for key in list(self._processes.keys()):
+ managed = self._processes[key]
+ if managed.status == "running":
+ _kill_process_tree(managed.pid)
+ for task in (managed.stdout_task, managed.stderr_task):
+ if task and not task.done():
+ task.cancel()
+ # Clean up this process's log dir
+ if managed.log_dir.exists():
+ shutil.rmtree(managed.log_dir, ignore_errors=True)
+ self._processes.clear()
+
+ async def _read_stream(
+ self, managed: ManagedProcess, stream: asyncio.StreamReader, stream_name: str
+ ) -> None:
+ """Background task: read lines, write to log file, broadcast to Terminal."""
+ level = "info" if stream_name == "stdout" else "error"
+ source = f"process:{managed.name}"
+ log_file = managed.log_dir / f"{stream_name}.log"
+
+ try:
+ with open(log_file, "a", encoding="utf-8", errors="replace") as f:
+ while True:
+ line = await stream.readline()
+ if not line:
+ break
+ text = line.decode(errors="replace").rstrip()
+
+ # Write to log file
+ f.write(text + "\n")
+ f.flush()
+
+ if stream_name == "stdout":
+ managed.stdout_lines += 1
+ else:
+ managed.stderr_lines += 1
+
+ # Broadcast to Terminal tab
+ if self._broadcaster:
+ await self._broadcaster.broadcast_terminal_log({
+ "timestamp": datetime.now().isoformat(),
+ "level": level,
+ "message": text,
+ "source": source,
+ })
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.debug("[Process] Stream reader %s/%s ended: %s", managed.name, stream_name, e)
+
+ # Stream EOF -- capture exit code (only stdout reader does this)
+ if managed.status == "running" and stream_name == "stdout":
+ try:
+ managed.exit_code = await asyncio.wait_for(managed.process.wait(), timeout=5)
+ except (asyncio.TimeoutError, Exception):
+ managed.exit_code = managed.process.returncode
+ managed.status = "stopped" if managed.exit_code == 0 else "error"
+ logger.info("[Process] Exited: %s (exit=%s)", managed.name, managed.exit_code)
+
+ @staticmethod
+ def _info(m: ManagedProcess) -> Dict[str, Any]:
+ return {
+ "name": m.name,
+ "command": m.command,
+ "pid": m.pid,
+ "status": m.status,
+ "started_at": m.started_at,
+ "exit_code": m.exit_code,
+ "working_directory": m.working_directory,
+ "stdout_lines": m.stdout_lines,
+ "stderr_lines": m.stderr_lines,
+ "log_dir": str(m.log_dir),
+ }
+
+
+def _kill_process_tree(pid: int) -> None:
+ """Kill a process and all descendants (cross-platform via psutil)."""
+ try:
+ parent = psutil.Process(pid)
+ except psutil.NoSuchProcess:
+ return
+ try:
+ descendants = parent.children(recursive=True)
+ except psutil.NoSuchProcess:
+ descendants = []
+ for child in descendants:
+ try:
+ child.kill()
+ except psutil.NoSuchProcess:
+ pass
+ try:
+ parent.kill()
+ except psutil.NoSuchProcess:
+ pass
+
+
+# -- Singleton --
+
+_instance: Optional[ProcessService] = None
+
+
+def get_process_service() -> ProcessService:
+ global _instance
+ if _instance is None:
+ _instance = ProcessService()
+ return _instance
+
+
+async def shutdown_process_service() -> None:
+ if _instance is not None:
+ await _instance.shutdown()
diff --git a/server/skills/coding_agent/shell-skill/SKILL.md b/server/skills/coding_agent/shell-skill/SKILL.md
deleted file mode 100644
index 3e45cdb4..00000000
--- a/server/skills/coding_agent/shell-skill/SKILL.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-name: shell-skill
-description: Execute shell commands and return stdout, stderr, and exit code.
-allowed-tools: shell_execute
-metadata:
- author: machina
- version: "1.0"
- category: execution
- icon: "\U0001F4BB"
- color: "#ff79c6"
----
-
-# Shell Tool
-
-Execute shell commands with timeout control. Uses deepagents LocalShellBackend.
-
-## shell_execute Tool
-
-### Schema Fields
-
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| command | string | Yes | Shell command to execute |
-| timeout | int | No | Timeout in seconds (default: 30, max: 300) |
-
-### Examples
-
-**List files:**
-```json
-{"command": "ls -la /path/to/dir"}
-```
-
-**Run a script:**
-```json
-{"command": "python script.py --arg value", "timeout": 60}
-```
-
-**Check disk usage:**
-```json
-{"command": "df -h"}
-```
-
-**Install a package:**
-```json
-{"command": "pip install requests", "timeout": 120}
-```
-
-### Response Format
-
-```json
-{
- "stdout": "command output here",
- "exit_code": 0,
- "truncated": false,
- "command": "ls -la"
-}
-```
-
-### Guidelines
-
-1. Set appropriate timeouts for long-running commands
-2. Exit code 0 means success, non-zero means failure
-3. Exit code 124 means the command timed out
-4. Check `truncated` flag -- output may be cut if too large
-5. Use absolute paths when possible
-6. Chain commands with `&&` for sequential execution
-7. Avoid interactive commands that require user input
-8. **Do NOT start background servers or daemons** (e.g. `python -m http.server`, `npm start`, `start /B`). The shell waits for the process to exit -- daemons will hang until timeout. Use short-lived commands only.
diff --git a/server/skills/terminal/bash-skill/SKILL.md b/server/skills/terminal/bash-skill/SKILL.md
new file mode 100644
index 00000000..d6558d15
--- /dev/null
+++ b/server/skills/terminal/bash-skill/SKILL.md
@@ -0,0 +1,119 @@
+---
+name: bash-skill
+description: Linux/macOS Bash commands and patterns for process management, file operations, and system administration.
+allowed-tools: process_manager shell_execute
+metadata:
+ author: machina
+ version: "1.0"
+ category: terminal
+ icon: "\U0001F427"
+ color: "#4EAA25"
+---
+
+# Bash Skill (Linux / macOS)
+
+Use this skill when the host system is **Linux or macOS**. Commands run via the `process_manager` tool (which has full PATH access).
+
+## Detect Linux/macOS
+
+Before using Bash commands, verify the OS:
+```json
+{"operation": "start", "name": "os-check", "command": "uname -s"}
+```
+`Linux` = Linux, `Darwin` = macOS. If neither, use the powershell skill.
+
+## Common Patterns
+
+### Install packages
+
+**npm:**
+```json
+{"operation": "start", "name": "npm-install", "command": "npm install express"}
+```
+
+**pip:**
+```json
+{"operation": "start", "name": "pip-install", "command": "pip3 install flask"}
+```
+
+**apt (Debian/Ubuntu):**
+```json
+{"operation": "start", "name": "apt-install", "command": "sudo apt-get install -y curl jq"}
+```
+
+**brew (macOS):**
+```json
+{"operation": "start", "name": "brew-install", "command": "brew install jq"}
+```
+
+### Start a dev server
+```json
+{"operation": "start", "name": "dev-server", "command": "npm run dev"}
+```
+
+### Check what's running on a port
+```json
+{"operation": "start", "name": "port-check", "command": "lsof -ti :3000"}
+```
+
+### Find files
+```json
+{"operation": "start", "name": "find-py", "command": "find . -name '*.py' -type f"}
+```
+
+### Search file contents
+```json
+{"operation": "start", "name": "grep-todo", "command": "grep -rn 'TODO' --include='*.py' ."}
+```
+
+### Disk usage
+```json
+{"operation": "start", "name": "disk", "command": "df -h && echo '---' && du -sh ./*"}
+```
+
+### Environment
+```json
+{"operation": "start", "name": "env", "command": "echo $PATH | tr ':' '\\n'"}
+```
+
+### Kill process by port
+```json
+{"operation": "start", "name": "kill-port", "command": "kill -9 $(lsof -ti :8080)"}
+```
+
+### Download a file
+```json
+{"operation": "start", "name": "download", "command": "curl -fsSL -o file.zip https://example.com/file.zip"}
+```
+
+### Watch a log file
+```json
+{"operation": "start", "name": "tail-log", "command": "tail -f /var/log/app.log"}
+```
+
+## macOS-Specific
+
+| Task | Command |
+|------|---------|
+| Open in Finder | `open .` |
+| System info | `sw_vers` |
+| Package manager | `brew install/uninstall` |
+| Services | `launchctl list` |
+
+## Linux-Specific
+
+| Task | Command |
+|------|---------|
+| Package manager (Debian) | `apt-get install` |
+| Package manager (RHEL) | `dnf install` |
+| Services | `systemctl status/start/stop` |
+| System info | `cat /etc/os-release` |
+
+## Guidelines
+
+- Use `&&` to chain commands (second runs only if first succeeds)
+- Use `||` for fallbacks (`command1 || command2`)
+- Redirect stderr: `command 2>&1`
+- Background with `&` does NOT work in process_manager -- use a separate `start` call instead
+- Use `set -e` at the start of multi-line scripts to fail fast
+- Prefer `$()` over backticks for command substitution
diff --git a/server/skills/terminal/powershell-skill/SKILL.md b/server/skills/terminal/powershell-skill/SKILL.md
new file mode 100644
index 00000000..43c9082d
--- /dev/null
+++ b/server/skills/terminal/powershell-skill/SKILL.md
@@ -0,0 +1,88 @@
+---
+name: powershell-skill
+description: Windows PowerShell commands and patterns for process management, file operations, and system administration.
+allowed-tools: process_manager shell_execute
+metadata:
+ author: machina
+ version: "1.0"
+ category: terminal
+ icon: "\U0001F4BB"
+ color: "#012456"
+---
+
+# PowerShell Skill (Windows)
+
+Use this skill when the host system is **Windows**. Commands run via the `process_manager` tool (which has full PATH access).
+
+## Detect Windows
+
+Before using PowerShell commands, verify the OS:
+```json
+{"operation": "start", "name": "os-check", "command": "powershell -Command \"$env:OS\""}
+```
+If output contains `Windows_NT`, use this skill. Otherwise use the bash skill.
+
+## Common Patterns
+
+### Run a PowerShell command
+```json
+{"operation": "start", "name": "ps-cmd", "command": "powershell -NoProfile -Command \"Get-Process | Sort-Object CPU -Descending | Select-Object -First 10\""}
+```
+
+### Install packages
+```json
+{"operation": "start", "name": "npm-install", "command": "npm install express"}
+```
+```json
+{"operation": "start", "name": "pip-install", "command": "pip install flask"}
+```
+
+### Start a dev server
+```json
+{"operation": "start", "name": "dev-server", "command": "npm run dev"}
+```
+
+### Check what's running on a port
+```json
+{"operation": "start", "name": "port-check", "command": "powershell -Command \"Get-NetTCPConnection -LocalPort 3000 -ErrorAction SilentlyContinue | Select-Object OwningProcess\""}
+```
+
+### List files recursively
+```json
+{"operation": "start", "name": "find-files", "command": "powershell -Command \"Get-ChildItem -Recurse -Filter *.py | Select-Object FullName\""}
+```
+
+### Environment variables
+```json
+{"operation": "start", "name": "env", "command": "powershell -Command \"$env:PATH -split ';'\""}
+```
+
+### Kill a process by port
+```json
+{"operation": "start", "name": "kill-port", "command": "powershell -Command \"Stop-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess -Force\""}
+```
+
+### Download a file
+```json
+{"operation": "start", "name": "download", "command": "powershell -Command \"Invoke-WebRequest -Uri 'https://example.com/file.zip' -OutFile 'file.zip'\""}
+```
+
+## Key Differences from Bash
+
+| Task | Bash | PowerShell |
+|------|------|------------|
+| List files | `ls -la` | `Get-ChildItem` or `dir` |
+| Find files | `find . -name "*.py"` | `Get-ChildItem -Recurse -Filter *.py` |
+| Environment | `echo $PATH` | `$env:PATH` |
+| Process list | `ps aux` | `Get-Process` |
+| Kill process | `kill -9 PID` | `Stop-Process -Id PID -Force` |
+| Download | `curl -O url` | `Invoke-WebRequest -Uri url -OutFile file` |
+| Grep | `grep pattern file` | `Select-String -Pattern pattern -Path file` |
+
+## Guidelines
+
+- Always prefix PowerShell commands with `powershell -NoProfile -Command "..."` when running via process_manager
+- Use `-ErrorAction SilentlyContinue` to suppress non-critical errors
+- Use `Select-Object` to limit output columns
+- Use `ConvertTo-Json` for structured output the agent can parse
+- Escape inner quotes with backtick `` ` `` or use single quotes inside double quotes
diff --git a/server/skills/terminal/process-manager-skill/SKILL.md b/server/skills/terminal/process-manager-skill/SKILL.md
new file mode 100644
index 00000000..e453327e
--- /dev/null
+++ b/server/skills/terminal/process-manager-skill/SKILL.md
@@ -0,0 +1,107 @@
+---
+name: process-manager-skill
+description: Start, stop, and manage long-running processes with full system PATH. Use for npm, python, node, dev servers, watchers, build tools. Destructive file commands blocked.
+allowed-tools: process_manager
+metadata:
+ author: machina
+ version: "3.0"
+ category: execution
+ icon: "\u2699\uFE0F"
+ color: "#ffb86c"
+---
+
+# Process Manager Tool
+
+Manage long-running processes with **full system PATH access**. Use this for anything that needs `npm`, `python`, `node`, or runs as a persistent server/watcher.
+
+## Security
+
+The process manager **blocks destructive file commands** to prevent accidental deletion outside the agent's workspace. Use `shell_execute` for file operations instead (sandboxed, no PATH, confined to workspace).
+
+**Blocked commands:** `rm`, `rmdir`, `del`, `rd`, `Remove-Item`, `format`, `mkfs`, `dd`, `shred`, `chmod 777`
+
+**Allowed:** `npm`, `python`, `node`, `pip`, `cargo`, `go`, servers, build tools, installers
+
+## Operations
+
+### start
+Launch a process. Output streams to the Terminal tab and is saved to log files.
+```json
+{"operation": "start", "name": "dev-server", "command": "python -m http.server 8080"}
+```
+
+### stop
+Kill a process and its entire process tree.
+```json
+{"operation": "stop", "name": "dev-server"}
+```
+
+### restart
+Stop then re-launch with the same command.
+```json
+{"operation": "restart", "name": "dev-server"}
+```
+
+### list
+Show all running processes for this workflow.
+```json
+{"operation": "list"}
+```
+
+### get_output
+Read output from a process's log file. Use `tail` to get last N lines, `stream` to choose stdout or stderr.
+```json
+{"operation": "get_output", "name": "dev-server", "stream": "stdout", "tail": 20}
+```
+Returns `{"lines": [...], "total": 150, "file": "/path/to/stdout.log"}`.
+
+### send_input
+Write text to a process's stdin (newline appended automatically).
+```json
+{"operation": "send_input", "name": "dev-server", "text": "quit"}
+```
+
+## Shell vs Process Manager
+
+| Need | Tool | Why |
+|------|------|-----|
+| `ls`, `cat`, `find`, `grep` | **shell_execute** | Sandboxed, fast, no PATH |
+| `rm`, `mv`, `cp`, file ops | **shell_execute** | Sandboxed, confined to workspace |
+| `npm install`, `pip install` | **process_manager** | Needs PATH |
+| `python script.py` | **process_manager** | Needs PATH |
+| `npm run dev`, `flask run` | **process_manager** | Long-running, streams output |
+| Dev servers, watchers | **process_manager** | Persistent, log files |
+
+## Output Log Files
+
+Each process writes to its own log files in the agent's workspace:
+```
+{workspace}/{agent_node_id}/.processes/{process_name}/
+ stdout.log # Standard output
+ stderr.log # Error output
+```
+
+Use `get_output` to read them selectively. The agent can also read these files directly with the `file_read` tool.
+
+## OS-Specific Commands
+
+Commands differ by platform. Refer to:
+- **bash-skill** -- Linux/macOS (apt, brew, lsof, kill, curl)
+- **powershell-skill** -- Windows (Get-Process, Stop-Process, Invoke-WebRequest)
+- **wsl-skill** -- Running Linux tools on Windows (prefix with `wsl`)
+
+Detect the OS first:
+```json
+{"operation": "start", "name": "os", "command": "python -c \"import platform; print(platform.system())\""}
+```
+Returns `Windows`, `Linux`, or `Darwin` (macOS).
+
+## Guidelines
+
+- Always give processes a meaningful **name** so you can stop/check them later
+- Use **get_output** after starting to verify the process launched correctly
+- Use **stop** to clean up processes when done -- don't leave servers running
+- **Do NOT use process_manager for file deletion** -- use shell_execute instead
+- Processes are automatically killed when the server shuts down
+- Max concurrent processes: configurable in Settings (default: 10)
+- Output streams to the Terminal tab in real-time
diff --git a/server/skills/terminal/shell-skill/SKILL.md b/server/skills/terminal/shell-skill/SKILL.md
new file mode 100644
index 00000000..124c8b49
--- /dev/null
+++ b/server/skills/terminal/shell-skill/SKILL.md
@@ -0,0 +1,86 @@
+---
+name: shell-skill
+description: Execute short-lived shell commands in a sandboxed environment. No PATH access -- use process_manager for npm/python/node commands.
+allowed-tools: shell_execute
+metadata:
+ author: machina
+ version: "2.0"
+ category: execution
+ icon: "\U0001F4BB"
+ color: "#ff79c6"
+---
+
+# Shell Tool
+
+Execute short-lived shell commands in a sandboxed workspace. The shell runs with a **restricted environment** (no system PATH). For commands that need `npm`, `python`, `node`, or other system tools, use the **process_manager** tool instead.
+
+## shell_execute Tool
+
+### Schema
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| command | string | Yes | Shell command to execute |
+| timeout | int | No | Timeout in seconds (default: 30, max: 300) |
+
+### Examples
+
+```json
+{"command": "ls -la"}
+{"command": "cat README.md"}
+{"command": "echo hello > output.txt"}
+{"command": "find . -name '*.py' -type f"}
+```
+
+### Response
+
+```json
+{
+ "stdout": "command output",
+ "exit_code": 0,
+ "truncated": false,
+ "command": "ls -la"
+}
+```
+
+### Exit Codes
+
+| Code | Meaning |
+|------|---------|
+| 0 | Success |
+| 124 | Timed out |
+| non-zero | Failure |
+
+## Shell vs Process Manager
+
+| Need | Tool | Why |
+|------|------|-----|
+| List files, read files, move/copy | **shell_execute** | Sandboxed, safe |
+| Delete files (`rm`, `del`) | **shell_execute** | Confined to workspace |
+| Search content (grep, find) | **shell_execute** | Fast, no PATH needed |
+| Echo, cat, simple file ops | **shell_execute** | Sandboxed |
+| `npm install`, `pip install` | **process_manager** | Needs PATH |
+| `python script.py`, `node app.js` | **process_manager** | Needs PATH |
+| Dev servers, watchers, build tools | **process_manager** | Long-running |
+
+The shell is the **only safe tool for file deletion**. It runs inside the agent's workspace with `virtual_mode=True` (path traversal blocked). The process_manager blocks destructive commands like `rm` since it has full PATH and could reach outside the workspace.
+
+## OS-Specific Commands
+
+For OS-specific syntax and tools, refer to:
+- **bash-skill** -- Linux/macOS commands (find, grep, apt, brew)
+- **powershell-skill** -- Windows commands (Get-ChildItem, Select-String)
+- **wsl-skill** -- Running Linux tools on Windows via WSL
+
+These skills are in the `terminal` skill folder alongside this one.
+
+## Guidelines
+
+1. **Short-lived commands only** -- the shell waits for completion
+2. **No system PATH** -- `npm`, `python`, `node` will not be found. Use process_manager
+3. **No daemons/servers** -- commands that don't exit will hang until timeout
+4. Exit code 124 = timed out
+5. Check `truncated` flag for large output
+6. Use relative paths (workspace is the working directory)
+7. Chain with `&&` for sequential execution
+8. Avoid interactive commands requiring user input
diff --git a/server/skills/terminal/wsl-skill/SKILL.md b/server/skills/terminal/wsl-skill/SKILL.md
new file mode 100644
index 00000000..5d51fdc3
--- /dev/null
+++ b/server/skills/terminal/wsl-skill/SKILL.md
@@ -0,0 +1,81 @@
+---
+name: wsl-skill
+description: Windows Subsystem for Linux (WSL) commands for running Linux tools on Windows.
+allowed-tools: process_manager shell_execute
+metadata:
+ author: machina
+ version: "1.0"
+ category: terminal
+ icon: "\U0001F4E6"
+ color: "#E95420"
+---
+
+# WSL Skill (Windows Subsystem for Linux)
+
+Use this skill when the host is **Windows** but you need Linux tools. WSL provides a full Linux environment alongside Windows.
+
+## Detect WSL
+
+```json
+{"operation": "start", "name": "wsl-check", "command": "wsl --status"}
+```
+If this succeeds, WSL is available.
+
+## Running Linux Commands from Windows
+
+Prefix any Linux command with `wsl` to run it inside the default WSL distro:
+
+```json
+{"operation": "start", "name": "wsl-cmd", "command": "wsl bash -c 'uname -a && cat /etc/os-release'"}
+```
+
+### Install Linux packages
+```json
+{"operation": "start", "name": "wsl-apt", "command": "wsl sudo apt-get update && wsl sudo apt-get install -y curl jq"}
+```
+
+### Run a Linux server
+```json
+{"operation": "start", "name": "wsl-server", "command": "wsl python3 -m http.server 8080"}
+```
+
+### Access Windows files from WSL
+Windows drives are mounted at `/mnt/`:
+```json
+{"operation": "start", "name": "wsl-ls", "command": "wsl ls -la /mnt/c/Users/"}
+```
+
+### Access WSL files from Windows
+```json
+{"operation": "start", "name": "wsl-path", "command": "wsl wslpath -w ~"}
+```
+
+## WSL Management
+
+| Task | Command |
+|------|---------|
+| List distros | `wsl --list --verbose` |
+| Default distro | `wsl --set-default Ubuntu` |
+| Shutdown all | `wsl --shutdown` |
+| Run in specific distro | `wsl -d Ubuntu bash -c "command"` |
+| Check status | `wsl --status` |
+
+## Path Conversion
+
+| Direction | Command |
+|-----------|---------|
+| Windows -> WSL | `wsl wslpath -u 'C:\Users\me\file.txt'` |
+| WSL -> Windows | `wsl wslpath -w '/home/me/file.txt'` |
+
+## Networking
+
+WSL2 shares the Windows network stack. Services started in WSL are accessible on `localhost` from Windows:
+- WSL server on port 8080 -> `http://localhost:8080` from Windows browser
+
+## Guidelines
+
+- Always prefix with `wsl` when running from a Windows process_manager
+- Use `wsl bash -c "..."` for multi-command pipelines
+- Windows paths use `\`, WSL paths use `/` -- use `wslpath` to convert
+- WSL has its own package manager (apt) separate from Windows
+- For long-running servers in WSL, use `process_manager start` (handles lifecycle)