Skip to content

Self-improving AI Employees for everyone

chore(backend): Wave 11 cleanup — dead code sweep

trohitg170a3d2813ce
diff --git a/server/nodes/chat/chat_history.py b/server/nodes/chat/chat_history.py
index 579a2568..73c3ea8d 100644
--- a/server/nodes/chat/chat_history.py
+++ b/server/nodes/chat/chat_history.py
@@ -46,11 +46,8 @@ class ChatHistoryNode(ActionNode):
@Operation("read")
async def read(self, ctx: NodeContext, params: ChatHistoryParams) -> Any:
- from services.handlers.chat import handle_chat_history
- response = await handle_chat_history(
- 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 "Chat history failed")
+ from core.container import container
+
+ database = container.database()
+ messages = await database.get_chat_messages(params.session_id, limit=params.limit)
+ return ChatHistoryOutput(messages=messages, count=len(messages))
diff --git a/server/nodes/chat/chat_send.py b/server/nodes/chat/chat_send.py
index 7b1f1ff3..20565c64 100644
--- a/server/nodes/chat/chat_send.py
+++ b/server/nodes/chat/chat_send.py
@@ -46,11 +46,13 @@ class ChatSendNode(ActionNode):
@Operation("send")
async def send(self, ctx: NodeContext, params: ChatSendParams) -> Any:
- from services.handlers.chat import handle_chat_send
- response = await handle_chat_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 "Chat send failed")
+ from core.container import container
+
+ if not params.message:
+ raise RuntimeError("Chat message is required")
+
+ database = container.database()
+ ok = await database.add_chat_message(params.session_id, "assistant", params.message)
+ if not ok:
+ raise RuntimeError("Failed to persist chat message")
+ return ChatSendOutput(sent=True, message_id=None)
diff --git a/server/services/ai.py b/server/services/ai.py
index b45bd84e..727108ab 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2701,399 +2701,71 @@ class AIService:
if db_schema_config:
return self._build_schema_from_config(db_schema_config)
- # Wave 11.B.1 plugin fast-path: if this node_type is a registered
- # BaseNode subclass, use its Pydantic Params model directly. The
- # plugin owns the LLM-visible schema; per-type ad-hoc schemas
- # below only fire for not-yet-migrated nodes.
- from services.node_registry import get_node_class
- plugin_cls = get_node_class(node_type)
- if plugin_cls is not None and hasattr(plugin_cls, 'Params'):
- return plugin_cls.Params
-
- # calculatorTool: schema now provided by nodes/tool/calculator_tool.py via plugin fast-path above.
-
- # HTTP Request tool schema
- if node_type in ('httpRequest', 'httpRequestTool'):
- class HttpRequestSchema(BaseModel):
- """Schema for HTTP request tool arguments."""
- url: str = Field(description="URL path or full URL to request")
- method: str = Field(default="GET", description="HTTP method: GET, POST, PUT, DELETE")
- body: Optional[Dict[str, Any]] = Field(default=None, description="Request body as JSON object")
- useProxy: bool = Field(default=False, description="Route request through a configured residential proxy")
-
- return HttpRequestSchema
-
- # Python executor tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'pythonExecutor':
- class PythonCodeSchema(BaseModel):
- """Execute Python code for calculations, data processing, and automation.
-
- Example: {"code": "result = 2 + 2\\noutput = result"}
- """
- code: str = Field(
- description="REQUIRED: Python code string to execute. Must set 'output' variable with the result. Available: input_data (dict), math, json, datetime, Counter, defaultdict. Example: 'output = 2 + 2'"
- )
-
- return PythonCodeSchema
+ # Agent delegation schema — MUST fire before the plugin fast-path.
+ # When an agent is connected to another agent's input-tools handle, we
+ # expose a (task, context) schema for delegation rather than the agent's
+ # own Params (which would leak provider/model/prompt into the parent LLM).
+ _AGENT_DELEGATION_TYPES = (
+ 'aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent',
+ 'task_agent', 'social_agent', 'travel_agent', 'tool_agent',
+ 'productivity_agent', 'payments_agent', 'consumer_agent',
+ 'autonomous_agent', 'orchestrator_agent', 'ai_employee',
+ 'rlm_agent', 'claude_code_agent', 'deep_agent',
+ )
+ if node_type in _AGENT_DELEGATION_TYPES:
+ agent_label = params.get('label', node_type)
- # JavaScript executor tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'javascriptExecutor':
- class JavaScriptCodeSchema(BaseModel):
- """Execute JavaScript code for calculations, data processing, and automation.
+ class DelegateToAgentSchema(BaseModel):
+ """Delegate a task to another AI Agent (non-blocking).
- Example: {"code": "const result = 2 + 2;\\noutput = result;"}
+ The child agent works independently in the background.
+ The 'task' becomes the agent's mission directive (system message).
+ The 'context' becomes the agent's input data (user prompt).
+ Returns a task_id immediately. Use 'check_delegated_tasks'
+ tool to check status and retrieve results when ready.
"""
- code: str = Field(
- description="REQUIRED: JavaScript code string to execute. Must set 'output' variable with the result. Available: input_data (object). Example: 'output = 2 + 2;'"
- )
-
- return JavaScriptCodeSchema
-
- # Current time tool schema
- if node_type == 'currentTimeTool':
- class CurrentTimeSchema(BaseModel):
- """Schema for current time tool arguments."""
- timezone: str = Field(
- default="UTC",
- description="Timezone (e.g., UTC, America/New_York, Europe/London)"
- )
-
- return CurrentTimeSchema
-
- # duckduckgoSearch / braveSearch / perplexitySearch: schemas now provided
- # by nodes/search/*.py via plugin fast-path above. serperSearch keeps its
- # ad-hoc schema until migration.
- if node_type == 'serperSearch':
- class SerperSearchSchema(BaseModel):
- """Search the web using Google via Serper API."""
- query: str = Field(description="Search query to look up on Google")
-
- return SerperSearchSchema
-
- # Timer tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'timer':
- class TimerSchema(BaseModel):
- """Wait/sleep for a specified duration before continuing."""
- duration: int = Field(
- default=5,
- description="Duration to wait (1-3600)"
+ task: str = Field(
+ description=f"The mission directive for '{agent_label}'. Describe the role and goal clearly, e.g. 'You are a coding assistant. Write a Python script that processes the given CSV data.'"
)
- unit: str = Field(
- default="seconds",
- description="Time unit: 'seconds', 'minutes', or 'hours'"
+ context: Optional[str] = Field(
+ default=None,
+ description="Input data or specific details the agent needs to work with, e.g. file contents, user requirements, or parameters"
)
- return TimerSchema
+ return DelegateToAgentSchema
- # Cron Scheduler tool schema (reuses CronSchedulerParams from models/nodes.py)
- if node_type == 'cronScheduler':
- from models.nodes import CronSchedulerParams
- return CronSchedulerParams
+ # Built-in check tool for delegation result retrieval (no plugin).
+ if node_type == '_builtin_check_delegated_tasks':
+ class CheckDelegatedTasksSchema(BaseModel):
+ """Check on previously delegated tasks and retrieve their results.
- # WhatsApp send schema (existing node used as tool)
- if node_type == 'whatsappSend':
- class WhatsAppSendSchema(BaseModel):
- """Send WhatsApp messages to contacts, groups, or channels."""
- recipient_type: str = Field(
- default="phone",
- description="Send to: 'phone' for individual, 'group' for group chat, or 'channel' for newsletter channel"
- )
- phone: Optional[str] = Field(
- default=None,
- description="Phone number without + prefix (e.g., 1234567890). Required for recipient_type='phone'"
- )
- group_id: Optional[str] = Field(
- default=None,
- description="Group JID (e.g., [email protected]). Required for recipient_type='group'"
- )
- channel_jid: Optional[str] = Field(
- default=None,
- description="Newsletter JID (e.g., 120363198765432101@newsletter). Required for recipient_type='channel'. Only supports text, image, video, audio, document."
- )
- message_type: str = Field(
- default="text",
- description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact'. Channels only support: text, image, video, audio, document."
- )
- message: Optional[str] = Field(
- default=None,
- description="Text message content. Required for message_type='text'"
- )
- media_url: Optional[str] = Field(
- default=None,
- description="URL for media (image/video/audio/document/sticker)"
- )
- caption: Optional[str] = Field(
- default=None,
- description="Caption for media messages (image, video, document)"
- )
- latitude: Optional[float] = Field(default=None, description="Latitude for location message")
- longitude: Optional[float] = Field(default=None, description="Longitude for location message")
- location_name: Optional[str] = Field(default=None, description="Display name for location")
- address: Optional[str] = Field(default=None, description="Address text for location")
- contact_name: Optional[str] = Field(default=None, description="Contact card display name")
- vcard: Optional[str] = Field(default=None, description="vCard 3.0 format string for contact")
-
- return WhatsAppSendSchema
-
- # WhatsApp DB schema (existing node used as tool) - query contacts, groups, messages
- if node_type == 'whatsappDb':
- class WhatsAppDbSchema(BaseModel):
- """Query WhatsApp database - contacts, groups, messages, channels.
-
- Operations:
- - chat_history: Get messages from a chat (requires phone or group_id)
- - search_groups: Search groups by name (optional query)
- - get_group_info: Get group details with participant names (requires group_id)
- - get_contact_info: Get full contact info for sending/replying (requires phone)
- - list_contacts: List contacts with saved names (optional query filter)
- - check_contacts: Check WhatsApp registration (requires phones comma-separated)
- - list_channels: List subscribed newsletter channels (optional refresh)
- - get_channel_info: Get channel details (requires channel_jid)
- - channel_messages: Get channel message history (requires channel_jid)
- - channel_stats: Get channel subscriber/view stats (requires channel_jid)
- - channel_follow: Follow/subscribe to a channel (requires channel_jid)
- - channel_unfollow: Unfollow/unsubscribe from a channel (requires channel_jid)
- - channel_create: Create a new newsletter channel (requires channel_name)
- - channel_mute: Mute/unmute a channel (requires channel_jid, mute)
- - channel_mark_viewed: Mark channel messages as viewed (requires channel_jid, server_ids)
+ Call this to see if delegated agents have completed their work.
+ Returns status and results for each task.
"""
- operation: str = Field(
- default="chat_history",
- description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts', 'list_channels', 'get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_create', 'channel_mute', 'channel_mark_viewed', 'newsletter_react', 'newsletter_live_updates', 'contact_profile_pic'"
- )
- # For chat_history
- chat_type: Optional[str] = Field(
- default=None,
- description="For chat_history: 'individual' or 'group'"
- )
- phone: Optional[str] = Field(
- default=None,
- description="Phone number without + prefix. For chat_history (individual), get_contact_info"
- )
- group_id: Optional[str] = Field(
- default=None,
- description="Group JID. For chat_history (group), get_group_info"
- )
- message_filter: Optional[str] = Field(
- default=None,
- description="For chat_history: 'all' or 'text_only'"
- )
- group_filter: Optional[str] = Field(
- default=None,
- description="For chat_history (group): 'all' or 'contact' to filter by sender"
- )
- sender_phone: Optional[str] = Field(
- default=None,
- description="For chat_history (group with group_filter='contact'): filter messages from this phone"
- )
- limit: Optional[int] = Field(
- default=None,
- description="Max results to return. chat_history: 1-500 (default 50), search_groups: 1-50 (default 20), list_contacts: 1-100 (default 50). Use smaller limits to avoid context overflow."
- )
- offset: Optional[int] = Field(default=None, description="For chat_history: pagination offset")
- # For search_groups, list_contacts
- query: Optional[str] = Field(
- default=None,
- description="Search query for search_groups or list_contacts. Use specific queries to narrow results."
- )
- # For check_contacts
- phones: Optional[str] = Field(
- default=None,
- description="For check_contacts: comma-separated phone numbers"
- )
- # For get_group_info
- participant_limit: Optional[int] = Field(
- default=None,
- description="For get_group_info: max participants to return (1-100, default 50). Large groups may have hundreds of members."
- )
- # Channel (newsletter) operations
- channel_jid: Optional[str] = Field(
- default=None,
- description="Newsletter JID (e.g., 120363198765432101@newsletter) or invite link (https://whatsapp.com/channel/...). Required for get_channel_info, channel_messages, channel_stats, channel_follow, channel_unfollow, channel_mute, channel_mark_viewed."
- )
- refresh: Optional[bool] = Field(
- default=None,
- description="For list_channels/get_channel_info: force refresh from server (default uses 24h cache)."
- )
- channel_count: Optional[int] = Field(
- default=None,
- description="For channel_messages/channel_stats: number of items to fetch (1-100, default 20 for messages, 10 for stats)."
- )
- before_server_id: Optional[int] = Field(
- default=None,
- description="For channel_messages: fetch messages before this server ID (pagination)."
- )
- message_offset: Optional[int] = Field(
- default=None,
- description="For channel_messages: pagination offset - skip this many messages."
- )
- since: Optional[str] = Field(
- default=None,
- description="For channel_messages: only return messages after this Unix timestamp."
- )
- until: Optional[str] = Field(
- default=None,
- description="For channel_messages: only return messages before this Unix timestamp."
- )
- media_type: Optional[str] = Field(
- default=None,
- description="For channel_messages: filter by media type ('image', 'video', 'audio', 'document', 'sticker'). Omit for all types."
- )
- search: Optional[str] = Field(
- default=None,
- description="For channel_messages: search for messages containing this text."
- )
- include_media_data: Optional[bool] = Field(
- default=None,
- description="For chat_history/channel_messages: download base64 media data for media messages. May be slow."
- )
- channel_name: Optional[str] = Field(
- default=None,
- description="For channel_create: name of the new channel."
- )
- channel_description: Optional[str] = Field(
- default=None,
- description="For channel_create: description of the new channel."
- )
- mute: Optional[bool] = Field(
- default=None,
- description="For channel_mute: True to mute, False to unmute."
- )
- server_ids: Optional[str] = Field(
- default=None,
- description="For channel_mark_viewed/newsletter_live_updates: comma-separated message server IDs (e.g., '100, 101, 102')."
- )
- # Newsletter react
- react_server_id: Optional[int] = Field(
- default=None,
- description="For newsletter_react: server ID of the message to react to."
- )
- reaction: Optional[str] = Field(
- default=None,
- description="For newsletter_react: reaction emoji (empty string to remove reaction)."
- )
- # Channel create picture
- picture: Optional[str] = Field(
- default=None,
- description="For channel_create: base64-encoded profile picture for the channel."
- )
- # Contact profile picture
- profile_pic_jid: Optional[str] = Field(
- default=None,
- description="For contact_profile_pic: JID or phone number to get profile picture for."
- )
- preview: Optional[bool] = Field(
- default=None,
- description="For contact_profile_pic: get low-resolution preview instead of full picture."
- )
-
- return WhatsAppDbSchema
-
- # Social Send schema (unified messaging to any platform)
- if node_type == 'socialSend':
- class SocialSendSchema(BaseModel):
- """Send messages to any supported chat platform (WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams)."""
- channel: str = Field(
- default="whatsapp",
- description="Target platform: 'whatsapp', 'telegram', 'discord', 'slack', 'signal', 'sms', 'webchat', 'email', 'matrix', 'teams'"
- )
- recipient_type: str = Field(
- default="phone",
- description="Recipient type: 'phone', 'group', 'channel', 'user', 'chat'"
- )
- phone: Optional[str] = Field(
- default=None,
- description="Phone number without + prefix (for recipient_type='phone')"
- )
- group_id: Optional[str] = Field(
- default=None,
- description="Group identifier (for recipient_type='group')"
- )
- channel_id: Optional[str] = Field(
- default=None,
- description="Channel identifier (for recipient_type='channel')"
- )
- user_id: Optional[str] = Field(
- default=None,
- description="User identifier (for recipient_type='user')"
- )
- chat_id: Optional[str] = Field(
- default=None,
- description="Generic chat identifier (for recipient_type='chat')"
- )
- message_type: str = Field(
- default="text",
- description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact', 'poll'"
- )
- message: Optional[str] = Field(
- default=None,
- description="Text message content (for message_type='text')"
- )
- media_url: Optional[str] = Field(
- default=None,
- description="URL for media (image/video/audio/document/sticker)"
- )
- caption: Optional[str] = Field(
+ task_ids: Optional[List[str]] = Field(
default=None,
- description="Caption for media messages"
+ description="Specific task IDs to check. Omit to get ALL delegated tasks."
)
- latitude: Optional[float] = Field(default=None, description="Latitude for location message")
- longitude: Optional[float] = Field(default=None, description="Longitude for location message")
- location_name: Optional[str] = Field(default=None, description="Display name for location")
- address: Optional[str] = Field(default=None, description="Address text for location")
- contact_name: Optional[str] = Field(default=None, description="Contact card display name")
- contact_phone: Optional[str] = Field(default=None, description="Contact phone number")
- vcard: Optional[str] = Field(default=None, description="vCard 3.0 format string for contact")
-
- return SocialSendSchema
-
- # Direct Android service node schema (connected directly to AI Agent tools handle)
- if node_type in ANDROID_SERVICE_NODE_TYPES:
- from services.android_service import SERVICE_ACTIONS
- _svc_id_map = {
- 'batteryMonitor': 'battery',
- 'networkMonitor': 'network',
- 'systemInfo': 'system_info',
- 'location': 'location',
- 'appLauncher': 'app_launcher',
- 'appList': 'app_list',
- 'wifiAutomation': 'wifi_automation',
- 'bluetoothAutomation': 'bluetooth_automation',
- 'audioAutomation': 'audio_automation',
- 'deviceStateAutomation': 'device_state',
- 'screenControlAutomation': 'screen_control',
- 'airplaneModeControl': 'airplane_mode',
- 'motionDetection': 'motion_detection',
- 'environmentalSensors': 'environmental_sensors',
- 'cameraControl': 'camera_control',
- 'mediaControl': 'media_control',
- }
- svc_id = _svc_id_map.get(node_type, node_type)
- actions = SERVICE_ACTIONS.get(svc_id, [])
- action_list = [a['value'] for a in actions] if actions else ['status']
- actions_desc = ', '.join(action_list)
-
- class AndroidServiceSchema(BaseModel):
- """Schema for a direct Android service tool."""
- action: str = Field(
- default=action_list[0] if action_list else 'status',
- description=f"Action to perform. Available: {actions_desc}"
- )
- parameters: Optional[Dict[str, Any]] = Field(
- default=None,
- description="Action-specific parameters (e.g., {{package_name: 'com.app'}} for app_launcher, {{volume: 50}} for audio)"
- )
+ return CheckDelegatedTasksSchema
- return AndroidServiceSchema
+ # Wave 11.B.1 plugin fast-path: if this node_type is a registered
+ # BaseNode subclass, use its Pydantic Params model directly. Every
+ # AI-tool-usable plugin is covered by this lookup (contract invariant
+ # test_fast_path_covers_every_plugin_tool). Wave 11.D.13 stripped the
+ # per-type ad-hoc schemas that used to live below this gate.
+ from services.node_registry import get_node_class
+ plugin_cls = get_node_class(node_type)
+ if plugin_cls is not None and hasattr(plugin_cls, 'Params'):
+ return plugin_cls.Params
- # Android toolkit schema - dynamic based on connected services
- # Follows LangChain dynamic tool binding pattern
+ # androidTool aggregator — dynamic schema derived from the set of
+ # Android service nodes connected to its toolkit handle. No plugin
+ # class, so it stays here.
if node_type == 'androidTool':
connected_services = params.get('connected_services', [])
if not connected_services:
- # No services connected - minimal schema with helpful error
class EmptyAndroidSchema(BaseModel):
"""Android toolkit with no connected services."""
query: str = Field(
@@ -3102,7 +2774,6 @@ class AIService:
)
return EmptyAndroidSchema
- # Build dynamic service list for schema description
from services.android_service import SERVICE_ACTIONS
service_info = []
@@ -3129,622 +2800,6 @@ class AIService:
return AndroidToolSchema
- # Google Maps Geocoding schema (gmaps_locations node as tool)
- # camelCase to match JSON/frontend convention
- if node_type == 'gmaps_locations':
- class GeocodingSchema(BaseModel):
- """Geocode addresses to coordinates or reverse geocode coordinates to addresses."""
- service_type: str = Field(
- default="geocode",
- description="Operation: 'geocode' (address to coordinates) or 'reverse_geocode' (coordinates to address)"
- )
- address: Optional[str] = Field(
- default=None,
- description="Address to geocode (e.g., '1600 Amphitheatre Parkway, Mountain View, CA'). Required for service_type='geocode'"
- )
- lat: Optional[float] = Field(
- default=None,
- description="Latitude for reverse geocoding. Required for service_type='reverse_geocode'"
- )
- lng: Optional[float] = Field(
- default=None,
- description="Longitude for reverse geocoding. Required for service_type='reverse_geocode'"
- )
-
- return GeocodingSchema
-
- # Google Maps Nearby Places schema (gmaps_nearby_places node as tool)
- # snake_case to match Python convention
- if node_type == 'gmaps_nearby_places':
- class NearbyPlacesSchema(BaseModel):
- """Search for nearby places using Google Maps Places API."""
- lat: float = Field(
- description="Center latitude for search (e.g., 40.7484)"
- )
- lng: float = Field(
- description="Center longitude for search (e.g., -73.9857)"
- )
- radius: int = Field(
- default=500,
- description="Search radius in meters (max 50000)"
- )
- type: str = Field(
- default="restaurant",
- description="Place type: restaurant, cafe, bar, hospital, pharmacy, bank, atm, gas_station, supermarket, park, gym, etc."
- )
- keyword: Optional[str] = Field(
- default=None,
- description="Optional keyword to filter results (e.g., 'pizza', 'italian', '24 hour')"
- )
-
- return NearbyPlacesSchema
-
- # Filesystem and shell tool schemas (deepagents backends)
- if node_type == 'fileRead':
- class FileReadSchema(BaseModel):
- """Read file contents with pagination."""
- file_path: str = Field(description="Path to the file to read")
- offset: int = Field(default=0, description="Line number to start from (0-indexed)")
- limit: int = Field(default=100, description="Maximum number of lines to read")
- return FileReadSchema
-
- if node_type == 'fileModify':
- class FileModifySchema(BaseModel):
- """Write a new file or edit an existing file."""
- operation: str = Field(description="Operation: 'write' (create/overwrite) or 'edit' (find and replace)")
- file_path: str = Field(description="Path to the file")
- content: Optional[str] = Field(default=None, description="File content (for write operation)")
- old_string: Optional[str] = Field(default=None, description="Text to find (for edit operation)")
- new_string: Optional[str] = Field(default=None, description="Replacement text (for edit operation)")
- replace_all: bool = Field(default=False, description="Replace all occurrences (for edit operation)")
- return FileModifySchema
-
- if node_type == 'shell':
- class ShellSchema(BaseModel):
- """Execute a shell command."""
- command: str = Field(description="Shell command to execute")
- timeout: int = Field(default=30, description="Timeout in seconds (1-300)")
- return ShellSchema
-
- if node_type == 'fsSearch':
- class FsSearchSchema(BaseModel):
- """Search the filesystem: list directory, glob pattern match, or grep file contents."""
- mode: str = Field(default="ls", description="Mode: 'ls' (list dir), 'glob' (pattern match), 'grep' (search contents)")
- path: str = Field(default=".", description="Directory path to search in")
- pattern: Optional[str] = Field(default=None, description="Glob pattern or grep search text (required for glob/grep)")
- file_filter: Optional[str] = Field(default=None, description="Glob to filter files for grep (e.g. '*.py')")
- return FsSearchSchema
-
- # Write Todos schema (dedicated AI tool for task planning)
- if node_type == 'writeTodos':
- from enum import Enum as PyEnum
-
- class TodoStatus(str, PyEnum):
- pending = "pending"
- in_progress = "in_progress"
- completed = "completed"
-
- class TodoItem(BaseModel):
- """A single todo item."""
- content: str = Field(description="Task description")
- status: TodoStatus = Field(
- default=TodoStatus.pending,
- description="Task status: pending, in_progress, or completed"
- )
-
- class WriteTodosSchema(BaseModel):
- """Create and manage a structured task list for complex multi-step operations.
-
- Use for tasks requiring 3+ steps. Each todo has content and status.
- Mark first task(s) as in_progress immediately. Update as you work.
- Skip this tool for simple tasks that take less than 3 steps.
- """
- todos: List[TodoItem] = Field(
- description="List of todo items with content and status"
- )
-
- 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):
- """Manage delegated tasks - list, check status, mark done.
-
- Use this to track sub-agent tasks you've delegated.
- - list_tasks: See all active and completed tasks
- - get_task: Get details on a specific task
- - mark_done: Clean up a completed task from tracking
- """
- operation: str = Field(
- description="Operation: 'list_tasks', 'get_task', or 'mark_done'"
- )
- task_id: Optional[str] = Field(
- default=None,
- description="Task ID (required for get_task/mark_done)"
- )
- status_filter: Optional[str] = Field(
- default=None,
- description="Filter by status: 'running', 'completed', or 'error' (for list_tasks)"
- )
-
- return TaskManagerSchema
-
- # Twitter Send tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'twitterSend':
- class TwitterSendSchema(BaseModel):
- """Post tweets, replies, retweets, and likes on Twitter/X."""
- action: str = Field(
- default="tweet",
- description="Action: tweet, reply, retweet, like, unlike, delete"
- )
- text: Optional[str] = Field(
- default=None,
- description="Tweet text (max 280 chars). Required for tweet/reply."
- )
- tweet_id: Optional[str] = Field(
- default=None,
- description="Tweet ID for reply/retweet/like/unlike/delete actions."
- )
- reply_to_id: Optional[str] = Field(
- default=None,
- description="Tweet ID to reply to (alias for tweet_id when action=reply)."
- )
-
- return TwitterSendSchema
-
- # Twitter Search tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'twitterSearch':
- class TwitterSearchSchema(BaseModel):
- """Search recent tweets on Twitter/X."""
- query: str = Field(description="Search query (supports X search operators)")
- max_results: int = Field(default=10, description="Max results (10-100)")
-
- return TwitterSearchSchema
-
- # Twitter User tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'twitterUser':
- class TwitterUserSchema(BaseModel):
- """Look up Twitter/X user profiles and social connections."""
- operation: str = Field(default="me", description="Operation: me, by_username, by_id, followers, following")
- username: Optional[str] = Field(default=None, description="Twitter username (without @) for by_username")
- user_id: Optional[str] = Field(default=None, description="Twitter user ID for by_id/followers/following")
- max_results: int = Field(default=100, description="Max results for followers/following (1-1000)")
-
- return TwitterUserSchema
-
- # ============================================================================
- # GOOGLE WORKSPACE CONSOLIDATED TOOL SCHEMAS
- # ============================================================================
-
- # gmail: schema now provided by nodes/google/gmail.py via plugin fast-path above.
-
- if node_type == 'calendar':
- class GoogleCalendarSchema(BaseModel):
- """Manage Google Calendar events.
-
- - create: Create new event (requires title, start_time, end_time)
- - list: List events in date range (requires start_date, end_date)
- - update: Update existing event (requires event_id)
- - delete: Delete event (requires event_id)
- """
- operation: str = Field(
- description="Operation: 'create', 'list', 'update', or 'delete'"
- )
- calendar_id: str = Field(default="primary", description="Calendar ID ('primary' for main calendar)")
- # create/update fields
- title: Optional[str] = Field(default=None, description="[create/update] Event title")
- start_time: Optional[str] = Field(default=None, description="[create/update] Start time ISO 8601 (e.g., '2026-02-22T14:00:00')")
- end_time: Optional[str] = Field(default=None, description="[create/update] End time ISO 8601")
- description: Optional[str] = Field(default=None, description="[create/update] Event description")
- location: Optional[str] = Field(default=None, description="[create/update] Event location")
- attendees: Optional[str] = Field(default=None, description="[create] Comma-separated attendee emails")
- timezone: str = Field(default="UTC", description="[create] Timezone (e.g., 'America/New_York')")
- send_updates: str = Field(default="none", description="[create/update/delete] Notifications: 'all', 'externalOnly', 'none'")
- # list fields
- start_date: Optional[str] = Field(default=None, description="[list] Start date ISO 8601")
- end_date: Optional[str] = Field(default=None, description="[list] End date ISO 8601")
- max_results: int = Field(default=50, description="[list] Max events (1-2500)")
- query: Optional[str] = Field(default=None, description="[list] Text search query")
- # update/delete fields
- event_id: Optional[str] = Field(default=None, description="[update/delete] Event ID")
-
- return GoogleCalendarSchema
-
- if node_type == 'drive':
- class GoogleDriveSchema(BaseModel):
- """Manage Google Drive files.
-
- - upload: Upload file from URL (requires file_url)
- - download: Download file (requires file_id)
- - list: List/search files
- - share: Share file with user (requires file_id, email)
- """
- operation: str = Field(
- description="Operation: 'upload', 'download', 'list', or 'share'"
- )
- # upload fields
- file_url: Optional[str] = Field(default=None, description="[upload] URL of file to upload")
- filename: Optional[str] = Field(default=None, description="[upload] Custom filename (auto-detected from URL)")
- mime_type: Optional[str] = Field(default=None, description="[upload] MIME type (auto-detected if omitted)")
- # upload/list fields
- folder_id: Optional[str] = Field(default=None, description="[upload/list] Folder ID (omit for root)")
- # download/share fields
- file_id: Optional[str] = Field(default=None, description="[download/share] Drive file ID")
- # list fields
- query: Optional[str] = Field(default=None, description="[list] Drive search query")
- max_results: int = Field(default=100, description="[list] Max files (1-1000)")
- file_types: Optional[str] = Field(default=None, description="[list] Filter: 'documents', 'spreadsheets', 'images', etc.")
- # share fields
- email: Optional[str] = Field(default=None, description="[share] Email to share with")
- role: str = Field(default="reader", description="[share] Role: 'reader', 'writer', 'commenter'")
- send_notification: bool = Field(default=True, description="[share] Send email notification")
-
- return GoogleDriveSchema
-
- if node_type == 'sheets':
- class GoogleSheetsSchema(BaseModel):
- """Read and write Google Sheets data.
-
- - read: Read data from range (requires spreadsheet_id, range)
- - write: Write data to range (requires spreadsheet_id, range, values)
- - append: Append rows (requires spreadsheet_id, range, values)
- """
- operation: str = Field(
- description="Operation: 'read', 'write', or 'append'"
- )
- spreadsheet_id: str = Field(description="Spreadsheet ID (from URL between /d/ and /edit)")
- range: str = Field(description="A1 notation range (e.g., 'Sheet1!A1:D10')")
- # write/append fields
- values: Optional[str] = Field(default=None, description="[write/append] 2D array as JSON string (e.g., '[[\"Name\",\"Age\"],[\"Alice\",25]]')")
- value_input_option: str = Field(default="USER_ENTERED", description="[write/append] Input mode: 'USER_ENTERED' or 'RAW'")
- # read fields
- value_render_option: str = Field(default="FORMATTED_VALUE", description="[read] Render: 'FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA'")
- major_dimension: str = Field(default="ROWS", description="[read] Dimension: 'ROWS' or 'COLUMNS'")
- # append fields
- insert_data_option: str = Field(default="INSERT_ROWS", description="[append] Insert mode: 'INSERT_ROWS' or 'OVERWRITE'")
-
- return GoogleSheetsSchema
-
- if node_type == 'tasks':
- class GoogleTasksSchema(BaseModel):
- """Manage Google Tasks.
-
- - create: Create new task (requires title)
- - list: List tasks from a task list
- - complete: Mark task as done (requires task_id)
- - update: Update task (requires task_id)
- - delete: Delete task (requires task_id)
- """
- operation: str = Field(
- description="Operation: 'create', 'list', 'complete', 'update', or 'delete'"
- )
- tasklist_id: str = Field(default="@default", description="Task list ID ('@default' for default list)")
- # create/update fields
- title: Optional[str] = Field(default=None, description="[create/update] Task title")
- notes: Optional[str] = Field(default=None, description="[create/update] Task notes/description")
- due_date: Optional[str] = Field(default=None, description="[create/update] Due date ISO 8601 (e.g., '2026-02-25')")
- # complete/update/delete fields
- task_id: Optional[str] = Field(default=None, description="[complete/update/delete] Task ID")
- # update fields
- status: Optional[str] = Field(default=None, description="[update] Status: 'needsAction' or 'completed'")
- # list fields
- show_completed: bool = Field(default=False, description="[list] Include completed tasks")
- show_hidden: bool = Field(default=False, description="[list] Include hidden tasks")
- max_results: int = Field(default=100, description="[list] Max tasks to return")
-
- return GoogleTasksSchema
-
- if node_type == 'contacts':
- class GoogleContactsSchema(BaseModel):
- """Manage Google Contacts.
-
- - create: Create contact (requires first_name)
- - list: Browse contacts with pagination
- - search: Find contacts by name/email/phone (requires query)
- - get: Get contact details (requires resource_name)
- - update: Update contact (requires resource_name)
- - delete: Delete contact (requires resource_name)
- """
- operation: str = Field(
- description="Operation: 'create', 'list', 'search', 'get', 'update', or 'delete'"
- )
- # create/update fields
- first_name: Optional[str] = Field(default=None, description="[create/update] First name")
- last_name: Optional[str] = Field(default=None, description="[create/update] Last name")
- email: Optional[str] = Field(default=None, description="[create/update] Email address")
- phone: Optional[str] = Field(default=None, description="[create/update] Phone number")
- company: Optional[str] = Field(default=None, description="[create/update] Company name")
- job_title: Optional[str] = Field(default=None, description="[create/update] Job title")
- notes: Optional[str] = Field(default=None, description="[create] Notes about the contact")
- # get/update/delete fields
- resource_name: Optional[str] = Field(default=None, description="[get/update/delete] Contact resource name (e.g., 'people/c12345678')")
- # search fields
- query: Optional[str] = Field(default=None, description="[search] Search query (name, email, phone)")
- # list/search fields
- page_size: int = Field(default=100, description="[list/search] Number of results (1-1000)")
- sort_order: str = Field(default="LAST_MODIFIED_DESCENDING", description="[list] Sort: 'LAST_MODIFIED_DESCENDING', 'FIRST_NAME_ASCENDING', etc.")
- page_token: Optional[str] = Field(default=None, description="[list] Pagination token")
-
- return GoogleContactsSchema
-
- # Check delegated tasks schema (built-in tool for result retrieval)
- if node_type == '_builtin_check_delegated_tasks':
- class CheckDelegatedTasksSchema(BaseModel):
- """Check on previously delegated tasks and retrieve their results.
-
- Call this to see if delegated agents have completed their work.
- Returns status and results for each task.
- """
- task_ids: Optional[List[str]] = Field(
- default=None,
- description="Specific task IDs to check. Omit to get ALL delegated tasks."
- )
-
- return CheckDelegatedTasksSchema
-
- # AI Agent delegation schema (fire-and-forget async delegation)
- if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'):
- agent_label = params.get('label', node_type)
-
- class DelegateToAgentSchema(BaseModel):
- """Delegate a task to another AI Agent (non-blocking).
-
- The child agent works independently in the background.
- The 'task' becomes the agent's mission directive (system message).
- The 'context' becomes the agent's input data (user prompt).
- Returns a task_id immediately. Use 'check_delegated_tasks'
- tool to check status and retrieve results when ready.
- """
- task: str = Field(
- description=f"The mission directive for '{agent_label}'. Describe the role and goal clearly, e.g. 'You are a coding assistant. Write a Python script that processes the given CSV data.'"
- )
- context: Optional[str] = Field(
- default=None,
- description="Input data or specific details the agent needs to work with, e.g. file contents, user requirements, or parameters"
- )
-
- return DelegateToAgentSchema
-
- # Apify Actor tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'apifyActor':
- class ApifyActorSchema(BaseModel):
- """Run Apify web scrapers for social media, websites, and search engines.
-
- Popular actors:
- - apify/instagram-scraper: Scrape Instagram profiles, posts, hashtags
- - clockworks/tiktok-scraper: Scrape TikTok profiles and hashtags
- - apidojo/tweet-scraper: Scrape Twitter/X tweets and users
- - curious_coder/linkedin-profile-scraper: Scrape LinkedIn profiles
- - apify/facebook-posts-scraper: Scrape Facebook posts
- - apify/google-search-scraper: Scrape Google search results
- - apify/website-content-crawler: Crawl any website
- """
- actor_id: str = Field(
- description="Apify actor ID (e.g., 'apify/instagram-scraper', 'clockworks/tiktok-scraper', 'apidojo/tweet-scraper', 'apify/google-search-scraper', 'apify/website-content-crawler')"
- )
- input_json: str = Field(
- default="{}",
- description="Actor input as JSON string. Examples: Instagram: {\"directUrls\": [\"https://instagram.com/username\"]}, TikTok: {\"profiles\": [\"username\"]}, Google: {\"searchQuery\": \"AI tools\"}, Crawler: {\"startUrls\": [{\"url\": \"https://example.com\"}]}"
- )
- max_results: int = Field(
- default=100,
- description="Maximum items to return from the dataset (1-10000)"
- )
-
- return ApifyActorSchema
-
- # Crawlee web reader tool schema (dual-purpose: workflow node + AI tool)
- # Browser automation (dual-purpose: workflow node + AI tool)
- if node_type == 'browser':
- class BrowserSchema(BaseModel):
- """Control a web browser. Use snapshot to see the page (returns @eN refs).
- Then click/type/fill using those refs. Workflow: navigate -> snapshot -> interact."""
- operation: str = Field(
- description="Operation: navigate, click, type, fill, screenshot, snapshot, get_text, get_html, eval, wait, scroll, select"
- )
- url: Optional[str] = Field(default=None, description="[navigate] URL to open")
- selector: Optional[str] = Field(default=None, description="[click/type/fill/get_text/get_html/wait/select] CSS selector or @eN ref from snapshot")
- text: Optional[str] = Field(default=None, description="[type] Text to type")
- value: Optional[str] = Field(default=None, description="[fill/select] Value to fill or option to select")
- expression: Optional[str] = Field(default=None, description="[eval] JavaScript to execute")
- direction: Optional[str] = Field(default="down", description="[scroll] up, down, left, right")
- amount: Optional[int] = Field(default=500, description="[scroll] Pixels to scroll")
- fullPage: Optional[bool] = Field(default=False, description="[screenshot] Capture full scrollable page")
-
- return BrowserSchema
-
- if node_type == 'crawleeScraper':
- class CrawleeScraperSchema(BaseModel):
- """Read content from any web page URL. Call this tool immediately when the user provides a URL.
- Always try beautifulsoup first. Do not warn about potential failures - just call the tool."""
- url: str = Field(description="URL to read (https://...)")
- crawlerType: str = Field(
- default="beautifulsoup",
- description="Engine: beautifulsoup (static HTML, fast), playwright (JS-rendered), adaptive (auto-detect)"
- )
- mode: str = Field(default="single", description="single (one page) or crawl (follow links)")
- cssSelector: Optional[str] = Field(default=None, description="CSS selector to extract specific content")
- maxPages: int = Field(default=10, description="Max pages for crawl mode (1-1000)")
- outputFormat: str = Field(default="text", description="Output: text, html, or markdown")
- useProxy: bool = Field(default=False, description="Route through configured proxy")
-
- return CrawleeScraperSchema
-
- # Proxy Request tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'proxyRequest':
- class ProxyRequestSchema(BaseModel):
- """Make HTTP requests through residential proxy providers with geo-targeting and failover."""
- url: str = Field(
- description="Target URL to request through the proxy"
- )
- method: Optional[str] = Field(
- default="GET",
- description="HTTP method: GET, POST, PUT, DELETE, PATCH"
- )
- headers: Optional[str] = Field(
- default=None,
- description="JSON string of HTTP headers (e.g. '{\"Authorization\": \"Bearer token\"}')"
- )
- body: Optional[str] = Field(
- default=None,
- description="Request body (for POST/PUT/PATCH). JSON string or plain text."
- )
- proxyProvider: Optional[str] = Field(
- default=None,
- description="Provider name to use, or omit for auto-selection (best health score)"
- )
- proxyCountry: Optional[str] = Field(
- default=None,
- description="ISO 3166-1 alpha-2 country code for geo-targeting (e.g. US, GB, DE)"
- )
- sessionType: Optional[str] = Field(
- default="rotating",
- description="Session type: 'rotating' (new IP per request) or 'sticky' (same IP)"
- )
- timeout: Optional[int] = Field(
- default=30,
- description="Request timeout in seconds (5-300)"
- )
- maxRetries: Optional[int] = Field(
- default=3,
- description="Max retry attempts with failover (0-10)"
- )
-
- return ProxyRequestSchema
-
- # Proxy Status tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'proxyStatus':
- class ProxyStatusSchema(BaseModel):
- """Get proxy provider health stats, scores, and usage statistics."""
- providerFilter: Optional[str] = Field(
- default=None,
- description="Filter by specific provider name, or omit for all providers"
- )
-
- return ProxyStatusSchema
-
- # Proxy Config tool schema (dual-purpose: workflow node + AI tool)
- if node_type == 'proxyConfig':
- class ProxyConfigSchema(BaseModel):
- """Manage proxy providers and routing rules.
-
- Operations: list_providers, add_provider, update_provider, remove_provider,
- set_credentials, test_provider, get_stats, add_routing_rule, list_routing_rules, remove_routing_rule.
- """
- operation: str = Field(
- description="Operation: list_providers, add_provider, update_provider, remove_provider, set_credentials, test_provider, get_stats, add_routing_rule, list_routing_rules, remove_routing_rule"
- )
- name: Optional[str] = Field(
- default=None,
- description="Provider name (required for add/update/remove/set_credentials/test_provider)"
- )
- gateway_host: Optional[str] = Field(
- default=None,
- description="Gateway hostname (for add_provider/update_provider)"
- )
- gateway_port: Optional[int] = Field(
- default=None,
- description="Gateway port (for add_provider/update_provider)"
- )
- url_template: Optional[str] = Field(
- default=None,
- description="JSON template config for proxy URL encoding (for add_provider/update_provider)"
- )
- username: Optional[str] = Field(
- default=None,
- description="Proxy username (for set_credentials)"
- )
- password: Optional[str] = Field(
- default=None,
- description="Proxy password (for set_credentials)"
- )
- enabled: Optional[bool] = Field(
- default=None,
- description="Enable/disable provider (for add_provider/update_provider)"
- )
- priority: Optional[int] = Field(
- default=None,
- description="Provider priority, lower=preferred (for add_provider/update_provider)"
- )
- cost_per_gb: Optional[float] = Field(
- default=None,
- description="Cost per GB in USD (for add_provider/update_provider)"
- )
- domain_pattern: Optional[str] = Field(
- default=None,
- description="Domain glob pattern (for add_routing_rule, e.g. '*.linkedin.com')"
- )
- preferred_providers: Optional[str] = Field(
- default=None,
- description="JSON array of provider names (for add_routing_rule)"
- )
- required_country: Optional[str] = Field(
- default=None,
- description="ISO country code (for add_routing_rule)"
- )
- session_type: Optional[str] = Field(
- default=None,
- description="Session type: 'rotating' or 'sticky' (for add_routing_rule)"
- )
- rule_id: Optional[int] = Field(
- default=None,
- description="Routing rule ID (for remove_routing_rule)"
- )
-
- return ProxyConfigSchema
-
- # Email Send (dual-purpose: workflow node + AI tool)
- if node_type == 'emailSend':
- class EmailSendSchema(BaseModel):
- """Send an email via SMTP."""
- to: str = Field(description="Recipient email address(es), comma-separated")
- subject: str = Field(description="Email subject line")
- body: str = Field(description="Email body content")
- cc: Optional[str] = Field(default=None, description="CC recipients, comma-separated")
- bcc: Optional[str] = Field(default=None, description="BCC recipients, comma-separated")
- body_type: str = Field(default="text", description="Body format: text or html")
-
- return EmailSendSchema
-
- # Email Read (dual-purpose: workflow node + AI tool)
- if node_type == 'emailRead':
- class EmailReadSchema(BaseModel):
- """Read and manage emails via IMAP."""
- operation: str = Field(description="Operation: list, search, read, folders, move, delete, flag")
- folder: Optional[str] = Field(default=None, description="Mailbox folder")
- message_id: Optional[str] = Field(default=None, description="Message ID (for read/move/delete/flag)")
- query: Optional[str] = Field(default=None, description="Search query (for search)")
- target_folder: Optional[str] = Field(default=None, description="Destination folder (for move)")
- flag: Optional[str] = Field(default=None, description="Flag: Seen, Answered, Flagged, Draft, Deleted")
- flag_action: Optional[str] = Field(default=None, description="add or remove")
- page: Optional[int] = Field(default=None, description="Page number (for list)")
- page_size: Optional[int] = Field(default=None, description="Results per page (for list)")
-
- return EmailReadSchema
-
# Generic schema for other nodes
class GenericToolSchema(BaseModel):
"""Generic schema for tool arguments."""
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index bb440ad8..aacc3462 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -17,7 +17,6 @@ This package contains all node execution handlers organized by category:
- sheets.py: Consolidated Sheets handler (read, write, append)
- tasks.py: Consolidated Tasks handler (create, list, complete, update, delete)
- contacts.py: Consolidated Contacts handler (create, list, search, get, update, delete)
-- polyglot.py: Polyglot server integration (standalone, not auto-imported)
"""
# AI handlers
diff --git a/server/services/handlers/polyglot.py b/server/services/handlers/polyglot.py
deleted file mode 100644
index 5a216da3..00000000
--- a/server/services/handlers/polyglot.py
+++ /dev/null
@@ -1,105 +0,0 @@
-"""Polyglot node handlers - execute nodes via polyglot-server plugin registry.
-
-This module provides handlers for routing node execution to polyglot-server.
-It is designed to be optionally integrated without modifying the existing
-workflow execution flow.
-
-Usage:
- # Optional integration - only if polyglot-server is running
- from services.handlers.polyglot import handle_polyglot_node, POLYGLOT_NODE_TYPES
-"""
-
-import time
-from datetime import datetime
-from typing import Dict, Any
-
-from core.logging import get_logger
-
-logger = get_logger(__name__)
-
-
-async def handle_polyglot_node(
- node_id: str,
- node_type: str,
- parameters: Dict[str, Any],
- context: Dict[str, Any],
- polyglot_client, # Injected via functools.partial
-) -> Dict[str, Any]:
- """Execute a workflow node via polyglot-server plugin registry.
-
- Args:
- node_id: The workflow node ID
- node_type: The node type (e.g., 'discordNode', 'telegramNode')
- parameters: Resolved node parameters
- context: Execution context
- polyglot_client: PolyglotClient instance
-
- Returns:
- Execution result dict
- """
- start_time = time.time()
-
- # Extract plugin name from node_type
- plugin_name = node_type.replace("Node", "").lower()
- action = parameters.get("action", "default")
- params = {k: v for k, v in parameters.items() if k != "action"}
-
- logger.info(
- "[Polyglot] Executing plugin",
- node_id=node_id,
- plugin=plugin_name,
- action=action,
- )
-
- try:
- result = await polyglot_client.execute(plugin_name, action, params)
- execution_time = time.time() - start_time
-
- if result.get("success", False):
- return {
- "success": True,
- "node_id": node_id,
- "node_type": node_type,
- "result": result.get("result", {}),
- "timestamp": datetime.now().isoformat(),
- "execution_time": execution_time,
- }
- else:
- return {
- "success": False,
- "node_id": node_id,
- "node_type": node_type,
- "error": result.get("error", "Unknown error"),
- "timestamp": datetime.now().isoformat(),
- "execution_time": execution_time,
- }
-
- except Exception as e:
- return {
- "success": False,
- "node_id": node_id,
- "node_type": node_type,
- "error": str(e),
- "timestamp": datetime.now().isoformat(),
- "execution_time": time.time() - start_time,
- }
-
-
-# Node types that can be routed to polyglot-server (for future use)
-POLYGLOT_NODE_TYPES = frozenset([
- "discordNode",
- "telegramNode",
- "slackNode",
- "signalNode",
- "notionNode",
- "todoistNode",
- "gmailNode",
- "outlookNode",
- "twitterNode",
- "instagramNode",
- "linkedinNode",
- "dalleNode",
- "stableDiffusionNode",
- "githubNode",
- "gitlabNode",
-])
diff --git a/server/services/polyglot_client.py b/server/services/polyglot_client.py
deleted file mode 100644
index 225deb79..00000000
--- a/server/services/polyglot_client.py
+++ /dev/null
@@ -1,169 +0,0 @@
-"""Polyglot Server Client - HTTP client for polyglot-server plugin registry."""
-
-import aiohttp
-from typing import Dict, Any, List, Optional
-
-from core.logging import get_logger
-
-logger = get_logger(__name__)
-
-
-class PolyglotClient:
- """Client for polyglot-server plugin registry.
-
- Provides async HTTP methods to interact with the polyglot-server
- for plugin discovery, schema retrieval, and execution.
- """
-
- def __init__(self, base_url: str = "http://localhost:8080"):
- self.base_url = base_url.rstrip("/")
- self._session: Optional[aiohttp.ClientSession] = None
-
- async def initialize(self) -> None:
- """Initialize the HTTP session."""
- if self._session is None or self._session.closed:
- timeout = aiohttp.ClientTimeout(total=30)
- self._session = aiohttp.ClientSession(timeout=timeout)
- logger.info("PolyglotClient initialized", base_url=self.base_url)
-
- async def close(self) -> None:
- """Close the HTTP session."""
- if self._session and not self._session.closed:
- await self._session.close()
- self._session = None
- logger.info("PolyglotClient closed")
-
- async def _ensure_session(self) -> aiohttp.ClientSession:
- """Ensure session is initialized and return it."""
- if self._session is None or self._session.closed:
- await self.initialize()
- return self._session
-
- async def health_check(self) -> Dict[str, Any]:
- """Check polyglot-server health status."""
- session = await self._ensure_session()
- try:
- async with session.get(f"{self.base_url}/api/health") as resp:
- if resp.status == 200:
- return await resp.json()
- return {"status": "error", "code": resp.status}
- except aiohttp.ClientError as e:
- logger.warning("Polyglot health check failed", error=str(e))
- return {"status": "unreachable", "error": str(e)}
-
- async def list_plugins(self) -> List[Dict[str, Any]]:
- """List all available plugins from polyglot-server."""
- session = await self._ensure_session()
- try:
- async with session.get(f"{self.base_url}/api/plugins") as resp:
- if resp.status == 200:
- data = await resp.json()
- return data.get("plugins", [])
- logger.warning("Failed to list plugins", status=resp.status)
- return []
- except aiohttp.ClientError as e:
- logger.error("Failed to list plugins", error=str(e))
- return []
-
- async def get_plugin(self, name: str) -> Optional[Dict[str, Any]]:
- """Get details for a specific plugin."""
- session = await self._ensure_session()
- try:
- async with session.get(f"{self.base_url}/api/plugins/{name}") as resp:
- if resp.status == 200:
- return await resp.json()
- return None
- except aiohttp.ClientError as e:
- logger.error("Failed to get plugin", plugin=name, error=str(e))
- return None
-
- async def get_schema(self, plugin_name: str) -> Optional[Dict[str, Any]]:
- """Get plugin input/output schema for workflow node integration."""
- session = await self._ensure_session()
- try:
- async with session.get(
- f"{self.base_url}/api/plugins/{plugin_name}/schema"
- ) as resp:
- if resp.status == 200:
- return await resp.json()
- return None
- except aiohttp.ClientError as e:
- logger.error("Failed to get schema", plugin=plugin_name, error=str(e))
- return None
-
- async def execute(
- self,
- plugin_name: str,
- action: str = "default",
- params: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Execute a plugin action.
-
- Args:
- plugin_name: Name of the plugin to execute
- action: Action to perform (default: "default")
- params: Optional parameters for the action
-
- Returns:
- Execution result with success status and result/error
- """
- session = await self._ensure_session()
- payload = {
- "action": action,
- "params": params or {},
- }
-
- try:
- async with session.post(
- f"{self.base_url}/api/plugins/{plugin_name}/execute",
- json=payload,
- ) as resp:
- result = await resp.json()
- if resp.status == 200:
- return result
- return {
- "success": False,
- "error": result.get("error", f"HTTP {resp.status}"),
- }
- except aiohttp.ClientError as e:
- logger.error(
- "Plugin execution failed",
- plugin=plugin_name,
- action=action,
- error=str(e),
- )
- return {"success": False, "error": str(e)}
-
- async def list_categories(self) -> List[str]:
- """List available plugin categories."""
- session = await self._ensure_session()
- try:
- async with session.get(f"{self.base_url}/api/categories") as resp:
- if resp.status == 200:
- data = await resp.json()
- return data.get("categories", [])
- return []
- except aiohttp.ClientError as e:
- logger.error("Failed to list categories", error=str(e))
- return []
-
-
-# Global client instance for simple usage
-_client: Optional[PolyglotClient] = None
-
-
-async def get_polyglot_client(base_url: str = "http://localhost:8080") -> PolyglotClient:
- """Get or create the global polyglot client instance."""
- global _client
- if _client is None:
- _client = PolyglotClient(base_url)
- await _client.initialize()
- return _client
-
-
-async def close_polyglot_client() -> None:
- """Close the global polyglot client instance."""
- global _client
- if _client is not None:
- await _client.close()
- _client = None