Skip to content

Self-improving AI Employees for everyone

refactor(plugin): Wave 11.D.1 — inline trivial-wrapper handler bodies

trohitg07579e25f0cf
diff --git a/server/nodes/email/email_read.py b/server/nodes/email/email_read.py
index c294d802..488a74b0 100644
--- a/server/nodes/email/email_read.py
+++ b/server/nodes/email/email_read.py
@@ -58,11 +58,6 @@ class EmailReadNode(ActionNode):
@Operation("query", cost={"service": "email", "action": "imap", "count": 1})
async def query(self, ctx: NodeContext, params: EmailReadParams) -> Any:
- from services.handlers.email import handle_email_read
- response = await handle_email_read(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
- )
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "Email read failed")
+ # Body inlined from handlers/email.py (Wave 11.D.1).
+ from services.email_service import get_email_service
+ return await get_email_service().read(params.model_dump(by_alias=True))
diff --git a/server/nodes/email/email_receive.py b/server/nodes/email/email_receive.py
index e5535ad7..0fa3de7e 100644
--- a/server/nodes/email/email_receive.py
+++ b/server/nodes/email/email_receive.py
@@ -60,11 +60,83 @@ class EmailReceiveNode(TriggerNode):
parameters: Dict[str, Any],
context: NodeContext,
) -> Dict[str, Any]:
- from services.handlers.email import handle_email_receive
- return await handle_email_receive(
- node_id=node_id, node_type=self.type,
- parameters=parameters, context=context.raw,
- )
+ """Polling-trigger body inlined from handlers/email.py (Wave 11.D.1).
+
+ Establishes a baseline set of seen message IDs, then polls the
+ IMAP folder at the configured interval. Returns the first new
+ email that arrives; also dispatches an ``email_received`` event
+ so deployment-mode listeners fire.
+ """
+ import asyncio
+ import time
+ from datetime import datetime
+ from services.email_service import get_email_service
+ from services.status_broadcaster import get_status_broadcaster
+ from services import event_waiter
+
+ start_time = time.time()
+ raw_params = parameters
+ try:
+ svc = get_email_service()
+ creds = await svc.resolve_credentials(raw_params)
+ poll = svc.resolve_poll_params(raw_params)
+
+ await get_status_broadcaster().update_node_status(
+ node_id, "waiting",
+ {
+ "message": f"Waiting for email (every {poll['interval']}s)...",
+ "event_type": "email_received",
+ },
+ workflow_id=context.workflow_id,
+ )
+
+ seen = await svc.poll_ids(creds, poll["folder"])
+ from core.logging import get_logger
+ get_logger(__name__).info(
+ f"[EmailReceive] Baseline: {len(seen)} emails in {poll['folder']}",
+ )
+
+ while True:
+ await asyncio.sleep(poll["interval"])
+ new_ids = await svc.poll_ids(creds, poll["folder"]) - seen
+ if not new_ids:
+ continue
+
+ msg_id = next(iter(new_ids))
+ seen.update(new_ids)
+ email_data = await svc.fetch_detail(creds, msg_id, poll["folder"])
+
+ if poll["mark_as_read"]:
+ d = svc.defaults
+ await svc.himalaya.flag_message(
+ creds, msg_id, d.get("flag"), d.get("flag_action"),
+ poll["folder"],
+ )
+
+ event_waiter.dispatch("email_received", email_data)
+ return {
+ "success": True, "node_id": node_id, "node_type": self.type,
+ "result": email_data,
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ except asyncio.CancelledError:
+ return {
+ "success": False, "node_id": node_id, "node_type": self.type,
+ "error": "Cancelled by user",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+ except Exception as e:
+ from core.logging import get_logger
+ get_logger(__name__).error(f"[EmailReceive] {e}")
+ return {
+ "success": False, "node_id": node_id, "node_type": self.type,
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
@Operation("wait")
async def wait(self, ctx: NodeContext, params: EmailReceiveParams) -> EmailReceiveOutput:
diff --git a/server/nodes/email/email_send.py b/server/nodes/email/email_send.py
index 5b16d4f8..2ddf9552 100644
--- a/server/nodes/email/email_send.py
+++ b/server/nodes/email/email_send.py
@@ -55,11 +55,6 @@ class EmailSendNode(ActionNode):
@Operation("send", cost={"service": "email", "action": "send", "count": 1})
async def send(self, ctx: NodeContext, params: EmailSendParams) -> Any:
- from services.handlers.email import handle_email_send
- response = await handle_email_send(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
- )
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "Email send failed")
+ # Body inlined from handlers/email.py (Wave 11.D.1).
+ from services.email_service import get_email_service
+ return await get_email_service().send(params.model_dump(by_alias=True))
diff --git a/server/nodes/filesystem/_backend.py b/server/nodes/filesystem/_backend.py
new file mode 100644
index 00000000..e6d1419b
--- /dev/null
+++ b/server/nodes/filesystem/_backend.py
@@ -0,0 +1,39 @@
+"""Shared deepagents-backend helper for filesystem plugins.
+
+All four filesystem plugins (file_read / file_modify / shell /
+fs_search) open a :class:`deepagents.backends.LocalShellBackend`
+rooted at the per-workflow workspace. This helper centralises that
+setup so each plugin file stays small.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, Optional
+
+
+def get_backend(
+ parameters: Dict[str, Any],
+ context: Optional[Dict[str, Any]] = None,
+):
+ """Return a LocalShellBackend rooted at the per-workflow workspace.
+
+ Resolution order: explicit ``working_directory`` param >
+ ``context.workspace_dir`` > ``Settings().workspace_base_resolved/default``.
+ The directory is created if it doesn't exist. ``virtual_mode=True``
+ sandboxes paths inside the root.
+ """
+ from core.config import Settings
+ from core.logging import get_logger
+ from deepagents.backends import LocalShellBackend
+
+ param_dir = parameters.get("working_directory")
+ ctx_dir = context.get("workspace_dir") if context else None
+ root = (
+ param_dir
+ or ctx_dir
+ or os.path.join(Settings().workspace_base_resolved, "default")
+ )
+ os.makedirs(root, exist_ok=True)
+ get_logger(__name__).info("[Filesystem] root=%s", root)
+ return LocalShellBackend(root_dir=root, virtual_mode=True)
diff --git a/server/nodes/filesystem/file_modify.py b/server/nodes/filesystem/file_modify.py
index 4482cd3d..10a46c84 100644
--- a/server/nodes/filesystem/file_modify.py
+++ b/server/nodes/filesystem/file_modify.py
@@ -49,11 +49,33 @@ class FileModifyNode(ActionNode):
@Operation("modify")
async def modify(self, ctx: NodeContext, params: FileModifyParams) -> Any:
- from services.handlers.filesystem import handle_file_modify
- response = await handle_file_modify(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
- )
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "File modify failed")
+ """Inlined from handlers/filesystem.py (Wave 11.D.1)."""
+ import asyncio
+ from ._backend import get_backend
+
+ if not params.file_path:
+ raise RuntimeError("file_path is required")
+ backend = get_backend(params.model_dump(by_alias=True), ctx.raw)
+
+ if params.operation == "write":
+ result = await asyncio.to_thread(backend.write, params.file_path, params.content)
+ if result.error:
+ raise RuntimeError(result.error)
+ return {"operation": "write", "file_path": result.path or params.file_path}
+
+ if params.operation == "edit":
+ if not params.old_string:
+ raise RuntimeError("old_string is required for edit")
+ result = await asyncio.to_thread(
+ backend.edit, params.file_path, params.old_string, params.new_string,
+ replace_all=params.replace_all,
+ )
+ if result.error:
+ raise RuntimeError(result.error)
+ return {
+ "operation": "edit",
+ "file_path": result.path or params.file_path,
+ "occurrences": result.occurrences,
+ }
+
+ raise RuntimeError(f"Unknown operation: {params.operation}")
diff --git a/server/nodes/filesystem/file_read.py b/server/nodes/filesystem/file_read.py
index d29873e5..2dd4f265 100644
--- a/server/nodes/filesystem/file_read.py
+++ b/server/nodes/filesystem/file_read.py
@@ -46,11 +46,15 @@ class FileReadNode(ActionNode):
@Operation("read")
async def read(self, ctx: NodeContext, params: FileReadParams) -> Any:
- from services.handlers.filesystem import handle_file_read
- response = await handle_file_read(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
+ """Inlined from handlers/filesystem.py (Wave 11.D.1)."""
+ import asyncio
+ from ._backend import get_backend
+
+ if not params.file_path:
+ raise RuntimeError("file_path is required")
+ backend = get_backend(params.model_dump(by_alias=True), ctx.raw)
+ content = await asyncio.to_thread(
+ backend.read, params.file_path,
+ offset=params.offset, limit=params.limit,
)
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "File read failed")
+ return {"content": content, "file_path": params.file_path}
diff --git a/server/nodes/filesystem/fs_search.py b/server/nodes/filesystem/fs_search.py
index 650d8ec6..5f91a1f6 100644
--- a/server/nodes/filesystem/fs_search.py
+++ b/server/nodes/filesystem/fs_search.py
@@ -46,11 +46,46 @@ class FsSearchNode(ActionNode):
@Operation("search")
async def search(self, ctx: NodeContext, params: FsSearchParams) -> Any:
- from services.handlers.filesystem import handle_fs_search
- response = await handle_fs_search(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
- )
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "FS search failed")
+ """Inlined from handlers/filesystem.py (Wave 11.D.1)."""
+ import asyncio
+ from ._backend import get_backend
+
+ backend = get_backend(params.model_dump(by_alias=True), ctx.raw)
+
+ if params.mode == "ls":
+ entries = await asyncio.to_thread(backend.ls_info, params.path)
+ return {
+ "path": params.path,
+ "entries": [dict(e) for e in entries],
+ "count": len(entries),
+ }
+
+ if params.mode == "glob":
+ if not params.pattern:
+ raise RuntimeError("pattern is required for glob mode")
+ matches = await asyncio.to_thread(
+ backend.glob_info, params.pattern, path=params.path,
+ )
+ return {
+ "path": params.path,
+ "pattern": params.pattern,
+ "matches": [dict(m) for m in matches],
+ "count": len(matches),
+ }
+
+ if params.mode == "grep":
+ if not params.pattern:
+ raise RuntimeError("pattern is required for grep mode")
+ result = await asyncio.to_thread(
+ backend.grep_raw, params.pattern, path=params.path,
+ )
+ if isinstance(result, str):
+ raise RuntimeError(result)
+ return {
+ "path": params.path,
+ "pattern": params.pattern,
+ "matches": [dict(m) for m in result],
+ "count": len(result),
+ }
+
+ raise RuntimeError(f"Unknown mode: {params.mode}")
diff --git a/server/nodes/filesystem/shell.py b/server/nodes/filesystem/shell.py
index d101aba5..35ed5a54 100644
--- a/server/nodes/filesystem/shell.py
+++ b/server/nodes/filesystem/shell.py
@@ -47,11 +47,33 @@ class ShellNode(ActionNode):
@Operation("execute")
async def execute_op(self, ctx: NodeContext, params: ShellParams) -> Any:
- from services.handlers.filesystem import handle_shell
- response = await handle_shell(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
+ """Inlined from handlers/filesystem.py (Wave 11.D.1)."""
+ import asyncio
+ from core.logging import get_logger
+ from ._backend import get_backend
+
+ log = get_logger(__name__)
+ backend = get_backend(params.model_dump(by_alias=True), ctx.raw)
+ log.info(
+ "[Shell] Executing (non-blocking): %s (timeout=%ds)",
+ params.command[:200], params.timeout,
+ )
+ result = await asyncio.to_thread(
+ backend.execute, params.command, timeout=params.timeout,
)
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "Shell command failed")
+ if result.exit_code == 124:
+ log.warning("[Shell] Timed out after %ds: %s", params.timeout, params.command[:100])
+ elif result.exit_code != 0:
+ log.warning(
+ "[Shell] Non-zero exit (%d): %s -> %s",
+ result.exit_code, params.command[:100], result.output[:300],
+ )
+ else:
+ log.info("[Shell] Completed: exit=%d len=%d", result.exit_code, len(result.output))
+
+ return {
+ "stdout": result.output,
+ "exit_code": result.exit_code,
+ "truncated": result.truncated,
+ "command": params.command,
+ }
diff --git a/server/nodes/telegram/telegram_send.py b/server/nodes/telegram/telegram_send.py
index 36f11c4a..24536287 100644
--- a/server/nodes/telegram/telegram_send.py
+++ b/server/nodes/telegram/telegram_send.py
@@ -99,12 +99,100 @@ class TelegramSendNode(ActionNode):
@Operation("send", cost={"service": "telegram", "action": "send", "count": 1})
async def send(self, ctx: NodeContext, params: TelegramSendParams) -> Any:
- from services.handlers.telegram import handle_telegram_send
- payload = params.model_dump(by_alias=True)
- response = await handle_telegram_send(
- node_id=ctx.node_id, node_type=self.type,
- parameters=payload, context=ctx.raw,
+ """Inlined from handlers/telegram.py:handle_telegram_send (Wave 11.D.1)."""
+ from core.logging import get_logger
+ from services.telegram_service import get_telegram_service
+
+ log = get_logger(__name__)
+ service = get_telegram_service()
+ if not service.connected:
+ raise RuntimeError(
+ "Telegram bot not connected. Add bot token in Credentials.",
+ )
+
+ if params.recipient_type == "self":
+ chat_id = service.owner_chat_id
+ if not chat_id:
+ try:
+ from core.container import container
+ saved = await container.auth_service().get_api_key("telegram_owner_chat_id")
+ if saved:
+ owner_id = int(saved)
+ await service.set_owner(owner_id)
+ chat_id = owner_id
+ log.info(f"[Telegram] Owner restored from credentials: {owner_id}")
+ except Exception as e:
+ log.warning(f"[Telegram] Failed to restore owner: {e}")
+ if not chat_id:
+ raise RuntimeError(
+ "Bot owner not detected. Send any private message to your bot "
+ "on Telegram to auto-detect, or set TELEGRAM_OWNER_CHAT_ID in .env",
+ )
+ else:
+ chat_id = params.chat_id
+ if not chat_id:
+ raise RuntimeError("chat_id is required")
+
+ parse_mode = params.parse_mode if params.parse_mode != "None" else None
+ reply_to = int(params.reply_to_message_id) if params.reply_to_message_id else None
+
+ common = dict(
+ chat_id=chat_id,
+ disable_notification=params.silent,
+ reply_to_message_id=reply_to,
+ )
+ mt = params.message_type
+ if mt == "text":
+ if not params.text:
+ raise RuntimeError("text is required for text message")
+ result = await service.send_message(
+ text=params.text, parse_mode=parse_mode, **common,
+ )
+ elif mt == "photo":
+ if not params.media_url:
+ raise RuntimeError("media_url is required for photo message")
+ result = await service.send_photo(
+ photo=params.media_url, caption=params.caption or None,
+ parse_mode=parse_mode, **common,
+ )
+ elif mt == "document":
+ if not params.media_url:
+ raise RuntimeError("media_url is required for document message")
+ result = await service.send_document(
+ document=params.media_url, caption=params.caption or None,
+ parse_mode=parse_mode, **common,
+ )
+ elif mt == "location":
+ if params.latitude is None or params.longitude is None:
+ raise RuntimeError(
+ "latitude and longitude are required for location message",
+ )
+ result = await service.send_location(
+ latitude=float(params.latitude),
+ longitude=float(params.longitude),
+ **common,
+ )
+ elif mt == "contact":
+ if not params.phone or not params.first_name:
+ raise RuntimeError(
+ "phone and first_name are required for contact message",
+ )
+ result = await service.send_contact(
+ phone_number=params.phone,
+ first_name=params.first_name,
+ last_name=params.last_name or None,
+ **common,
+ )
+ else:
+ raise RuntimeError(f"Unsupported message type: {mt}")
+
+ log.info(
+ f"[Telegram] Message sent: type={mt}, chat={chat_id}, "
+ f"msg_id={result.get('message_id')}",
)
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "Telegram send failed")
+ return {
+ "message_id": result.get("message_id"),
+ "chat_id": result.get("chat_id"),
+ "message_type": mt,
+ "date": result.get("date"),
+ }
diff --git a/server/nodes/tool/write_todos.py b/server/nodes/tool/write_todos.py
index 3756134c..9f8700f1 100644
--- a/server/nodes/tool/write_todos.py
+++ b/server/nodes/tool/write_todos.py
@@ -52,11 +52,28 @@ class WriteTodosNode(ToolNode):
@Operation("write")
async def write(self, ctx: NodeContext, params: WriteTodosParams) -> Any:
- from services.handlers.todo import execute_write_todos
- config = {
- "node_id": ctx.node_id,
- "workspace_dir": ctx.workspace_dir or "",
- "workflow_id": ctx.workflow_id,
- "session_id": ctx.session_id,
+ """Inlined from handlers/todo.py (Wave 11.D.1)."""
+ from core.logging import get_logger
+ from services.todo_service import get_todo_service
+
+ session_key = ctx.workflow_id or ctx.node_id or "default"
+ service = get_todo_service()
+ stored = service.write(session_key, [t.model_dump() for t in params.todos])
+
+ # Real-time UI broadcast (optional; broadcaster lives on ctx.raw).
+ broadcaster = ctx.raw.get("broadcaster")
+ if broadcaster:
+ await broadcaster.update_node_status(
+ ctx.node_id, "executing",
+ {"phase": "todo_update", "todos": stored},
+ workflow_id=ctx.workflow_id,
+ )
+
+ get_logger(__name__).info(
+ "[WriteTodos] Updated %d todos (session=%s)", len(stored), session_key,
+ )
+ return {
+ "message": f"Updated todo list ({len(stored)} items)",
+ "todos": service.format_for_llm(session_key),
+ "count": len(stored),
}
- return await execute_write_todos(params.model_dump(), config)
diff --git a/server/nodes/utility/process_manager.py b/server/nodes/utility/process_manager.py
index 1c3b15d8..22e244b0 100644
--- a/server/nodes/utility/process_manager.py
+++ b/server/nodes/utility/process_manager.py
@@ -54,11 +54,41 @@ class ProcessManagerNode(ActionNode):
@Operation("dispatch")
async def dispatch(self, ctx: NodeContext, params: ProcessManagerParams) -> Any:
- from services.handlers.process import handle_process_manager
- response = await handle_process_manager(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(by_alias=True), context=ctx.raw,
- )
- if response.get("success"):
- return response.get("result") or response
- raise RuntimeError(response.get("error") or "Process manager failed")
+ """Inlined from handlers/process.py (Wave 11.D.1)."""
+ import os
+ from services.process_service import get_process_service
+
+ svc = get_process_service()
+ workflow_id = ctx.workflow_id or "default"
+ workspace_dir = ctx.workspace_dir or ""
+ # Each agent node gets its own subfolder in the workspace.
+ agent_dir = os.path.join(workspace_dir, ctx.node_id) if workspace_dir else ""
+
+ op = params.operation
+ name = _clean(params.name)
+
+ if op == "start":
+ return await svc.start(
+ name=name,
+ command=_clean(params.command),
+ workflow_id=workflow_id,
+ working_directory=_clean(params.cwd) or agent_dir,
+ )
+ if op == "stop":
+ return await svc.stop(name, workflow_id)
+ if op == "restart":
+ return await svc.restart(name, workflow_id)
+ if op == "send_input":
+ return await svc.send_input(name, workflow_id, _clean(params.input_text))
+ if op == "list":
+ return {"processes": svc.list_processes(workflow_id)}
+ if op == "get_output":
+ return svc.get_output(name, workflow_id, params.stream, params.tail, 0)
+ raise RuntimeError(f"Unknown operation: {op}")
+
+
+def _clean(val: str) -> str:
+ """LLMs sometimes pass literal 'None' string instead of omitting the field."""
+ if not val or val == "None":
+ return ""
+ return val