Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(plugin): Wave 11.D.4/5 — Google Workspace inlined
trohitgfcb09dd368ab
diff --git a/server/config/model_registry.json b/server/config/model_registry.jsonindex e103173c..aa524fbe 100644--- a/server/config/model_registry.json+++ b/server/config/model_registry.json@@ -1,7 +1,7 @@{- "_generated": "2026-04-13T23:09:24.941879+00:00",+ "_generated": "2026-04-15T01:33:08.748282+00:00","_source": "openrouter",- "_model_count": 350,+ "_model_count": 344,"models": {"openrouter/elephant-alpha": {"id": "openrouter/elephant-alpha",@@ -3179,7 +3179,7 @@"provider": "moonshotai","local_id": "kimi-k2-thinking","context_length": 262144,- "max_output_tokens": 0,+ "max_output_tokens": 262144,"input_price_per_mtok": 0.6,"output_price_per_mtok": 2.5,"supports_thinking": false,@@ -4453,40 +4453,6 @@"top_p"]},- "meituan/longcat-flash-chat": {- "id": "meituan/longcat-flash-chat",- "name": "Meituan: LongCat Flash Chat",- "provider": "meituan",- "local_id": "longcat-flash-chat",- "context_length": 131072,- "max_output_tokens": 131072,- "input_price_per_mtok": 0.2,- "output_price_per_mtok": 0.8,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logit_bias",- "max_tokens",- "min_p",- "presence_penalty",- "repetition_penalty",- "response_format",- "seed",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_k",- "top_p"- ]- },"qwen/qwen-plus-2025-07-28:thinking": {"id": "qwen/qwen-plus-2025-07-28:thinking","name": "Qwen: Qwen Plus 0728 (thinking)",@@ -5437,10 +5403,8 @@"presence_penalty","reasoning","repetition_penalty",- "response_format","seed","stop",- "structured_outputs","temperature","tool_choice","tools",@@ -6033,32 +5997,6 @@"top_p"]},- "inception/mercury": {- "id": "inception/mercury",- "name": "Inception: Mercury",- "provider": "inception",- "local_id": "mercury",- "context_length": 128000,- "max_output_tokens": 32000,- "input_price_per_mtok": 0.25,- "output_price_per_mtok": 0.75,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "max_tokens",- "response_format",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools"- ]- },"mistralai/mistral-small-3.2-24b-instruct": {"id": "mistralai/mistral-small-3.2-24b-instruct","name": "Mistral: Mistral Small 3.2 24B",@@ -6629,32 +6567,6 @@"top_p"]},- "inception/mercury-coder": {- "id": "inception/mercury-coder",- "name": "Inception: Mercury Coder",- "provider": "inception",- "local_id": "mercury-coder",- "context_length": 128000,- "max_output_tokens": 32000,- "input_price_per_mtok": 0.25,- "output_price_per_mtok": 0.75,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "max_tokens",- "response_format",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools"- ]- },"meta/llama-guard-4-12b": {"id": "meta-llama/llama-guard-4-12b","name": "Meta: Llama Guard 4 12B",@@ -6942,34 +6854,6 @@"tools"]},- "qwen/qwen2.5-coder-7b-instruct": {- "id": "qwen/qwen2.5-coder-7b-instruct",- "name": "Qwen: Qwen2.5 Coder 7B Instruct",- "provider": "qwen",- "local_id": "qwen2.5-coder-7b-instruct",- "context_length": 32768,- "max_output_tokens": 0,- "input_price_per_mtok": 0.03,- "output_price_per_mtok": 0.09,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "max_tokens",- "presence_penalty",- "repetition_penalty",- "response_format",- "structured_outputs",- "temperature",- "top_k",- "top_p"- ]- },"openai/gpt-4.1": {"id": "openai/gpt-4.1","name": "OpenAI: GPT-4.1",@@ -7145,36 +7029,6 @@"top_p"]},- "nvidia/llama-3.1-nemotron-ultra-253b-v1": {- "id": "nvidia/llama-3.1-nemotron-ultra-253b-v1",- "name": "NVIDIA: Llama 3.1 Nemotron Ultra 253B v1",- "provider": "nvidia",- "local_id": "llama-3.1-nemotron-ultra-253b-v1",- "context_length": 131072,- "max_output_tokens": 0,- "input_price_per_mtok": 0.6,- "output_price_per_mtok": 1.8,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "include_reasoning",- "max_tokens",- "presence_penalty",- "reasoning",- "repetition_penalty",- "response_format",- "structured_outputs",- "temperature",- "top_k",- "top_p"- ]- },"meta/llama-4-maverick": {"id": "meta-llama/llama-4-maverick","name": "Meta: Llama 4 Maverick",@@ -7909,8 +7763,8 @@"local_id": "llama-guard-3-8b","context_length": 131072,"max_output_tokens": 0,- "input_price_per_mtok": 0.02,- "output_price_per_mtok": 0.06,+ "input_price_per_mtok": 0.48,+ "output_price_per_mtok": 0.03,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9051,11 +8905,11 @@"top_p"]},- "inflection/inflection-3-productivity": {- "id": "inflection/inflection-3-productivity",- "name": "Inflection: Inflection 3 Productivity",+ "inflection/inflection-3-pi": {+ "id": "inflection/inflection-3-pi",+ "name": "Inflection: Inflection 3 Pi","provider": "inflection",- "local_id": "inflection-3-productivity",+ "local_id": "inflection-3-pi","context_length": 8000,"max_output_tokens": 1024,"input_price_per_mtok": 2.5,@@ -9074,11 +8928,11 @@"top_p"]},- "inflection/inflection-3-pi": {- "id": "inflection/inflection-3-pi",- "name": "Inflection: Inflection 3 Pi",+ "inflection/inflection-3-productivity": {+ "id": "inflection/inflection-3-productivity",+ "name": "Inflection: Inflection 3 Productivity","provider": "inflection",- "local_id": "inflection-3-pi",+ "local_id": "inflection-3-productivity","context_length": 8000,"max_output_tokens": 1024,"input_price_per_mtok": 2.5,@@ -9133,15 +8987,15 @@"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)",+ "meta/llama-3.2-1b-instruct": {+ "id": "meta-llama/llama-3.2-1b-instruct",+ "name": "Meta: Llama 3.2 1B Instruct","provider": "meta",- "local_id": "llama-3.2-3b-instruct:free",- "context_length": 131072,+ "local_id": "llama-3.2-1b-instruct",+ "context_length": 60000,"max_output_tokens": 0,- "input_price_per_mtok": 0.0,- "output_price_per_mtok": 0.0,+ "input_price_per_mtok": 0.027,+ "output_price_per_mtok": 0.2,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9153,21 +9007,22 @@"frequency_penalty","max_tokens","presence_penalty",- "stop",+ "repetition_penalty",+ "seed","temperature","top_k","top_p"]},- "meta/llama-3.2-3b-instruct": {- "id": "meta-llama/llama-3.2-3b-instruct",- "name": "Meta: Llama 3.2 3B Instruct",+ "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-3b-instruct",- "context_length": 80000,- "max_output_tokens": 0,- "input_price_per_mtok": 0.051,- "output_price_per_mtok": 0.34,+ "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": [@@ -9178,23 +9033,26 @@"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-1b-instruct": {- "id": "meta-llama/llama-3.2-1b-instruct",- "name": "Meta: Llama 3.2 1B Instruct",+ "meta/llama-3.2-3b-instruct:free": {+ "id": "meta-llama/llama-3.2-3b-instruct:free",+ "name": "Meta: Llama 3.2 3B Instruct (free)","provider": "meta",- "local_id": "llama-3.2-1b-instruct",- "context_length": 60000,+ "local_id": "llama-3.2-3b-instruct:free",+ "context_length": 131072,"max_output_tokens": 0,- "input_price_per_mtok": 0.027,- "output_price_per_mtok": 0.2,+ "input_price_per_mtok": 0.0,+ "output_price_per_mtok": 0.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9206,22 +9064,21 @@"frequency_penalty","max_tokens","presence_penalty",- "repetition_penalty",- "seed",+ "stop","temperature","top_k","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",+ "meta/llama-3.2-3b-instruct": {+ "id": "meta-llama/llama-3.2-3b-instruct",+ "name": "Meta: Llama 3.2 3B 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,+ "local_id": "llama-3.2-3b-instruct",+ "context_length": 80000,+ "max_output_tokens": 0,+ "input_price_per_mtok": 0.051,+ "output_price_per_mtok": 0.34,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9232,12 +9089,9 @@"supported_parameters": ["frequency_penalty","max_tokens",- "min_p","presence_penalty","repetition_penalty",- "response_format","seed",- "stop","temperature","top_k","top_p"@@ -9621,11 +9475,11 @@"top_p"]},- "openai/gpt-4o-mini-2024-07-18": {- "id": "openai/gpt-4o-mini-2024-07-18",- "name": "OpenAI: GPT-4o-mini (2024-07-18)",+ "openai/gpt-4o-mini": {+ "id": "openai/gpt-4o-mini",+ "name": "OpenAI: GPT-4o-mini","provider": "openai",- "local_id": "gpt-4o-mini-2024-07-18",+ "local_id": "gpt-4o-mini","context_length": 128000,"max_output_tokens": 16384,"input_price_per_mtok": 0.15,@@ -9641,6 +9495,7 @@"frequency_penalty","logit_bias","logprobs",+ "max_completion_tokens","max_tokens","presence_penalty","response_format",@@ -9655,11 +9510,11 @@"web_search_options"]},- "openai/gpt-4o-mini": {- "id": "openai/gpt-4o-mini",- "name": "OpenAI: GPT-4o-mini",+ "openai/gpt-4o-mini-2024-07-18": {+ "id": "openai/gpt-4o-mini-2024-07-18",+ "name": "OpenAI: GPT-4o-mini (2024-07-18)","provider": "openai",- "local_id": "gpt-4o-mini",+ "local_id": "gpt-4o-mini-2024-07-18","context_length": 128000,"max_output_tokens": 16384,"input_price_per_mtok": 0.15,@@ -9675,7 +9530,6 @@"frequency_penalty","logit_bias","logprobs",- "max_completion_tokens","max_tokens","presence_penalty","response_format",@@ -9717,32 +9571,6 @@"top_p"]},- "gemini/gemma-2-9b-it": {- "id": "google/gemma-2-9b-it",- "name": "Google: Gemma 2 9B",- "provider": "gemini",- "local_id": "gemma-2-9b-it",- "context_length": 8192,- "max_output_tokens": 0,- "input_price_per_mtok": 0.03,- "output_price_per_mtok": 0.09,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "max_tokens",- "presence_penalty",- "repetition_penalty",- "temperature",- "top_k",- "top_p"- ]- },"sao10k/l3-euryale-70b": {"id": "sao10k/l3-euryale-70b","name": "Sao10k: Llama 3 Euryale 70B v2.1",@@ -9803,15 +9631,15 @@"top_p"]},- "openai/gpt-4o-2024-05-13": {- "id": "openai/gpt-4o-2024-05-13",- "name": "OpenAI: GPT-4o (2024-05-13)",+ "openai/gpt-4o": {+ "id": "openai/gpt-4o",+ "name": "OpenAI: GPT-4o","provider": "openai",- "local_id": "gpt-4o-2024-05-13",+ "local_id": "gpt-4o","context_length": 128000,- "max_output_tokens": 4096,- "input_price_per_mtok": 5.0,- "output_price_per_mtok": 15.0,+ "max_output_tokens": 16384,+ "input_price_per_mtok": 2.5,+ "output_price_per_mtok": 10.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9838,15 +9666,15 @@"web_search_options"]},- "openai/gpt-4o": {- "id": "openai/gpt-4o",- "name": "OpenAI: GPT-4o",+ "openai/gpt-4o:extended": {+ "id": "openai/gpt-4o:extended",+ "name": "OpenAI: GPT-4o (extended)","provider": "openai",- "local_id": "gpt-4o",+ "local_id": "gpt-4o:extended","context_length": 128000,- "max_output_tokens": 16384,- "input_price_per_mtok": 2.5,- "output_price_per_mtok": 10.0,+ "max_output_tokens": 64000,+ "input_price_per_mtok": 6.0,+ "output_price_per_mtok": 18.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9858,7 +9686,6 @@"frequency_penalty","logit_bias","logprobs",- "max_completion_tokens","max_tokens","presence_penalty","response_format",@@ -9873,15 +9700,15 @@"web_search_options"]},- "openai/gpt-4o:extended": {- "id": "openai/gpt-4o:extended",- "name": "OpenAI: GPT-4o (extended)",+ "openai/gpt-4o-2024-05-13": {+ "id": "openai/gpt-4o-2024-05-13",+ "name": "OpenAI: GPT-4o (2024-05-13)","provider": "openai",- "local_id": "gpt-4o:extended",+ "local_id": "gpt-4o-2024-05-13","context_length": 128000,- "max_output_tokens": 64000,- "input_price_per_mtok": 6.0,- "output_price_per_mtok": 18.0,+ "max_output_tokens": 4096,+ "input_price_per_mtok": 5.0,+ "output_price_per_mtok": 15.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9893,6 +9720,7 @@"frequency_penalty","logit_bias","logprobs",+ "max_completion_tokens","max_tokens","presence_penalty","response_format",@@ -10115,15 +9943,15 @@"top_p"]},- "openai/gpt-4-turbo-preview": {- "id": "openai/gpt-4-turbo-preview",- "name": "OpenAI: GPT-4 Turbo Preview",+ "openai/gpt-3.5-turbo-0613": {+ "id": "openai/gpt-3.5-turbo-0613",+ "name": "OpenAI: GPT-3.5 Turbo (older v0613)","provider": "openai",- "local_id": "gpt-4-turbo-preview",- "context_length": 128000,+ "local_id": "gpt-3.5-turbo-0613",+ "context_length": 4095,"max_output_tokens": 4096,- "input_price_per_mtok": 10.0,- "output_price_per_mtok": 30.0,+ "input_price_per_mtok": 1.0,+ "output_price_per_mtok": 2.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -10135,7 +9963,7 @@"frequency_penalty","logit_bias","logprobs",- "max_tokens",+ "max_completion_tokens","presence_penalty","response_format","seed",@@ -10148,15 +9976,15 @@"top_p"]},- "openai/gpt-3.5-turbo-0613": {- "id": "openai/gpt-3.5-turbo-0613",- "name": "OpenAI: GPT-3.5 Turbo (older v0613)",+ "openai/gpt-4-turbo-preview": {+ "id": "openai/gpt-4-turbo-preview",+ "name": "OpenAI: GPT-4 Turbo Preview","provider": "openai",- "local_id": "gpt-3.5-turbo-0613",- "context_length": 4095,+ "local_id": "gpt-4-turbo-preview",+ "context_length": 128000,"max_output_tokens": 4096,- "input_price_per_mtok": 1.0,- "output_price_per_mtok": 2.0,+ "input_price_per_mtok": 10.0,+ "output_price_per_mtok": 30.0,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -10168,7 +9996,7 @@"frequency_penalty","logit_bias","logprobs",- "max_completion_tokens",+ "max_tokens","presence_penalty","response_format","seed",@@ -10199,7 +10027,6 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",- "logit_bias","max_tokens","min_p","presence_penalty",@@ -10518,11 +10345,11 @@"top_p"]},- "openai/gpt-4-0314": {- "id": "openai/gpt-4-0314",- "name": "OpenAI: GPT-4 (older v0314)",+ "openai/gpt-4": {+ "id": "openai/gpt-4",+ "name": "OpenAI: GPT-4","provider": "openai",- "local_id": "gpt-4-0314",+ "local_id": "gpt-4","context_length": 8191,"max_output_tokens": 4096,"input_price_per_mtok": 30.0,@@ -10538,6 +10365,7 @@"frequency_penalty","logit_bias","logprobs",+ "max_completion_tokens","max_tokens","presence_penalty","response_format",@@ -10551,11 +10379,11 @@"top_p"]},- "openai/gpt-4": {- "id": "openai/gpt-4",- "name": "OpenAI: GPT-4",+ "openai/gpt-4-0314": {+ "id": "openai/gpt-4-0314",+ "name": "OpenAI: GPT-4 (older v0314)","provider": "openai",- "local_id": "gpt-4",+ "local_id": "gpt-4-0314","context_length": 8191,"max_output_tokens": 4096,"input_price_per_mtok": 30.0,@@ -10571,7 +10399,6 @@"frequency_penalty","logit_bias","logprobs",- "max_completion_tokens","max_tokens","presence_penalty","response_format",diff --git a/server/nodes/google/_base.py b/server/nodes/google/_base.pynew file mode 100644index 00000000..8e23312d--- /dev/null+++ b/server/nodes/google/_base.py@@ -0,0 +1,84 @@+"""Shared helpers for Google Workspace plugins (Wave 11.D.4).++Every Google plugin follows the same pattern:++ creds -> googleapiclient.discovery.build(name, version) -> .execute()+ track usage via pricing service -> return result++These two helpers capture that boilerplate so each ``@Operation`` in a+plugin shrinks to the API-specific call + argument shaping.+"""++from __future__ import annotations++import asyncio+from typing import Any, Dict++from googleapiclient.discovery import build++from core.logging import get_logger+from services.handlers.google_auth import get_google_credentials+from services.pricing import get_pricing_service++logger = get_logger(__name__)+++async def build_google_service(+ api_name: str,+ api_version: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+):+ """Build an authenticated Google API client (runs in executor).++ Args:+ api_name: Google API short name (``gmail`` / ``calendar`` / ``drive`` /+ ``sheets`` / ``tasks`` / ``people``).+ api_version: API version (e.g. ``v1``, ``v3``).+ parameters: Node parameters (forwarded to ``get_google_credentials``).+ context: Execution context (forwarded).+ """+ creds = await get_google_credentials(parameters, context)+ loop = asyncio.get_event_loop()+ return await loop.run_in_executor(+ None, lambda: build(api_name, api_version, credentials=creds),+ )+++async def track_google_usage(+ service: str,+ node_id: str,+ action: str,+ resource_count: int,+ context: Dict[str, Any],+) -> Dict[str, float]:+ """Record a Google API call in ``api_usage_metrics``.++ ``service`` must match a pricing-config key: ``gmail`` /+ ``google_calendar`` / ``google_drive`` / ``google_sheets`` /+ ``google_tasks`` / ``google_contacts``. Google APIs are free at our+ tier — this is analytics bookkeeping, cost is $0.+ """+ from core.container import container++ pricing = get_pricing_service()+ cost_data = pricing.calculate_api_cost(service, action, resource_count)++ db = container.database()+ await db.save_api_usage_metric({+ 'session_id': context.get('session_id', 'default'),+ 'node_id': node_id,+ 'workflow_id': context.get('workflow_id'),+ 'service': service,+ 'operation': cost_data.get('operation', action),+ 'endpoint': action,+ 'resource_count': resource_count,+ 'cost': cost_data.get('total_cost', 0.0),+ })+ return cost_data+++async def run_sync(fn):+ """Run a blocking googleapiclient call in the default executor."""+ loop = asyncio.get_event_loop()+ return await loop.run_in_executor(None, fn)diff --git a/server/nodes/google/_gmail.py b/server/nodes/google/_gmail.pynew file mode 100644index 00000000..3d576d1b--- /dev/null+++ b/server/nodes/google/_gmail.py@@ -0,0 +1,106 @@+"""Gmail-specific shared helpers (Wave 11.D.4).++Used by both gmail (send/search/read) and gmail_receive (polling).+Lives here because it's Gmail-internal — not reusable across other+Google Workspace plugins.+"""++from __future__ import annotations++import base64+from typing import Any, Dict, List, Set++from ._base import run_sync+++async def poll_gmail_ids(service, query: str, max_results: int = 20) -> Set[str]:+ """Fetch message IDs matching a Gmail query."""+ result = await run_sync(lambda: service.users().messages().list(+ userId='me', q=query, maxResults=max_results,+ ).execute())+ return {m.get('id') for m in result.get('messages', []) if m.get('id')}+++async def fetch_email_details(service, message_id: str) -> Dict[str, Any]:+ """Fetch full email message + format it for output."""+ result = await run_sync(lambda: service.users().messages().get(+ userId='me', id=message_id, format='full',+ metadataHeaders=['From', 'To', 'Subject', 'Date', 'Cc', 'Bcc'],+ ).execute())+ return format_message(result, include_body=True)+++async def mark_email_as_read(service, message_id: str) -> None:+ """Remove the UNREAD label from a message."""+ await run_sync(lambda: service.users().messages().modify(+ userId='me', id=message_id, body={'removeLabelIds': ['UNREAD']},+ ).execute())+++def format_message(message: Dict[str, Any], include_body: bool = False) -> Dict[str, Any]:+ """Convert a raw Gmail message payload into a flat, LLM-friendly dict."""+ headers: Dict[str, str] = {}+ payload = message.get('payload', {})+ for header in payload.get('headers', []):+ name = header.get('name', '').lower()+ if name in ('from', 'to', 'subject', 'date', 'cc', 'bcc'):+ headers[name] = header.get('value', '')++ formatted: Dict[str, Any] = {+ 'message_id': message.get('id'),+ 'thread_id': message.get('threadId'),+ 'from': headers.get('from', ''),+ 'to': headers.get('to', ''),+ 'cc': headers.get('cc', ''),+ 'subject': headers.get('subject', ''),+ 'date': headers.get('date', ''),+ 'snippet': message.get('snippet', ''),+ 'labels': message.get('labelIds', []),+ 'size_estimate': message.get('sizeEstimate', 0),+ }++ if include_body:+ formatted['body'] = _extract_body(payload)++ attachments = _extract_attachments(payload)+ if attachments:+ formatted['attachments'] = attachments++ return formatted+++def _extract_body(payload: Dict[str, Any]) -> str:+ """Extract text body from a (possibly multipart) Gmail payload."""+ if payload.get('body', {}).get('data'):+ return base64.urlsafe_b64decode(payload['body']['data']).decode('utf-8', errors='ignore')++ body = ""+ for part in payload.get('parts', []):+ mime = part.get('mimeType', '')+ data = part.get('body', {}).get('data')+ if mime == 'text/plain' and data:+ return base64.urlsafe_b64decode(data).decode('utf-8', errors='ignore')+ if mime == 'text/html' and data and not body:+ body = base64.urlsafe_b64decode(data).decode('utf-8', errors='ignore')+ elif mime.startswith('multipart/'):+ nested = _extract_body(part)+ if nested:+ return nested+ return body+++def _extract_attachments(payload: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Flatten attachment metadata from a multipart payload."""+ attachments: List[Dict[str, Any]] = []+ for part in payload.get('parts', []):+ filename = part.get('filename', '')+ if filename:+ attachments.append({+ 'filename': filename,+ 'mime_type': part.get('mimeType', ''),+ 'size': part.get('body', {}).get('size', 0),+ 'attachment_id': part.get('body', {}).get('attachmentId', ''),+ })+ if part.get('parts'):+ attachments.extend(_extract_attachments(part))+ return attachmentsdiff --git a/server/nodes/google/calendar.py b/server/nodes/google/calendar.pyindex 55a7dd4e..0431462d 100644--- a/server/nodes/google/calendar.py+++ b/server/nodes/google/calendar.py@@ -1,25 +1,41 @@-"""Google Calendar — Wave 11.C migration."""+"""Google Calendar — Wave 11.D.4 inlined."""from __future__ import annotations-from typing import Any, Literal, Optional+from datetime import datetime, timedelta+from typing import List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+class CalendarParams(BaseModel):operation: Literal["create", "list", "update", "delete"] = "list"calendar_id: str = Field(default="primary", alias="calendarId")- event_id: str = Field(default="", alias="eventId")- summary: str = Field(default="")- description: str = Field(default="")- start_time: str = Field(default="", alias="startTime")- end_time: str = Field(default="", alias="endTime")- location: str = Field(default="")- attendees: str = Field(default="")+ event_id: Optional[str] = Field(default=None, alias="eventId")+ title: Optional[str] = None+ description: Optional[str] = None+ start_time: Optional[str] = Field(default=None, alias="startTime")+ end_time: Optional[str] = Field(default=None, alias="endTime")+ location: Optional[str] = None+ attendees: Optional[str] = None+ timezone: str = "UTC"+ reminder_minutes: int = Field(default=30, alias="reminderMinutes")+ start_date: Optional[str] = Field(default=None, alias="startDate")+ end_date: Optional[str] = Field(default=None, alias="endDate")max_results: int = Field(default=10, alias="maxResults", ge=1, le=250)+ single_events: bool = Field(default=True, alias="singleEvents")+ order_by: str = Field(default="startTime", alias="orderBy")+ send_updates: str = Field(default="all", alias="sendUpdates")++ update_title: Optional[str] = Field(default=None, alias="updateTitle")+ update_start_time: Optional[str] = Field(default=None, alias="updateStartTime")+ update_end_time: Optional[str] = Field(default=None, alias="updateEndTime")+ update_description: Optional[str] = Field(default=None, alias="updateDescription")+ update_location: Optional[str] = Field(default=None, alias="updateLocation")model_config = ConfigDict(populate_by_name=True, extra="allow")@@ -27,13 +43,32 @@ class CalendarParams(BaseModel):class CalendarOutput(BaseModel):operation: Optional[str] = Noneevent_id: Optional[str] = None- events: Optional[list] = None+ title: Optional[str] = None+ start: Optional[str] = None+ end: Optional[str] = None+ html_link: Optional[str] = None+ status: Optional[str] = None+ created: Optional[str] = None+ updated: Optional[str] = None+ events: Optional[List[dict]] = Nonecount: Optional[int] = None+ time_range: Optional[dict] = Nonedeleted: Optional[bool] = Nonemodel_config = ConfigDict(extra="allow")+def _iso_or_shortcut(value: Optional[str], default_offset_days: int = 0) -> str:+ now = datetime.utcnow()+ if not value or value.lower() == "today":+ base = now.replace(hour=0, minute=0, second=0, microsecond=0) if default_offset_days == 0 else now + timedelta(days=default_offset_days)+ return base.isoformat() + "Z"+ if value.startswith("today+"):+ days = int(value.replace("today+", "").replace("d", ""))+ return (now + timedelta(days=days)).isoformat() + "Z"+ return value if value.endswith("Z") else value + "Z"++class CalendarNode(ActionNode):type = "calendar"display_name = "Calendar"@@ -57,12 +92,128 @@ class CalendarNode(ActionNode):Output = CalendarOutput@Operation("dispatch", cost={"service": "calendar", "action": "op", "count": 1})- async def dispatch(self, ctx: NodeContext, params: CalendarParams) -> Any:- from services.handlers.calendar import handle_google_calendar- response = await handle_google_calendar(- 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 "Calendar op failed")+ async def dispatch(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ svc = await build_google_service("calendar", "v3", params.model_dump(by_alias=True), ctx.raw)+ events_svc = svc.events()+ op = params.operation+ cal_id = params.calendar_id++ if op == "create":+ if not params.title:+ raise RuntimeError("Event title is required")+ if not params.start_time or not params.end_time:+ raise RuntimeError("Start time and end time are required")++ event = {+ 'summary': params.title,+ 'start': {'dateTime': params.start_time, 'timeZone': params.timezone},+ 'end': {'dateTime': params.end_time, 'timeZone': params.timezone},+ }+ if params.description:+ event['description'] = params.description+ if params.location:+ event['location'] = params.location+ if params.attendees:+ att = [{'email': e.strip()} for e in params.attendees.split(',') if e.strip()]+ if att:+ event['attendees'] = att+ if params.reminder_minutes:+ event['reminders'] = {+ 'useDefault': False,+ 'overrides': [{'method': 'popup', 'minutes': int(params.reminder_minutes)}],+ }++ result = await run_sync(lambda: events_svc.insert(+ calendarId=cal_id, body=event, sendUpdates=params.send_updates,+ ).execute())+ await track_google_usage("google_calendar", ctx.node_id, "create", 1, ctx.raw)+ return CalendarOutput(+ operation="create",+ event_id=result.get('id'),+ title=result.get('summary'),+ start=result.get('start', {}).get('dateTime'),+ end=result.get('end', {}).get('dateTime'),+ html_link=result.get('htmlLink'),+ status=result.get('status'),+ created=result.get('created'),+ )++ if op == "list":+ time_min = _iso_or_shortcut(params.start_date)+ time_max = _iso_or_shortcut(params.end_date, default_offset_days=7)+ single = params.single_events+ kwargs = dict(+ calendarId=cal_id, timeMin=time_min, timeMax=time_max,+ maxResults=min(params.max_results, 250), singleEvents=single,+ )+ if single:+ kwargs['orderBy'] = params.order_by++ result = await run_sync(lambda: events_svc.list(**kwargs).execute())+ raw = result.get('items', [])+ formatted = [{+ "event_id": e.get('id'),+ "title": e.get('summary', 'No Title'),+ "start": e.get('start', {}).get('dateTime', e.get('start', {}).get('date')),+ "end": e.get('end', {}).get('dateTime', e.get('end', {}).get('date')),+ "description": e.get('description', ''),+ "location": e.get('location', ''),+ "status": e.get('status'),+ "html_link": e.get('htmlLink'),+ "attendees": [a.get('email') for a in e.get('attendees', [])],+ } for e in raw]+ await track_google_usage("google_calendar", ctx.node_id, "list", len(formatted), ctx.raw)+ return CalendarOutput(+ operation="list",+ events=formatted,+ count=len(formatted),+ time_range={"start": time_min, "end": time_max},+ )++ if op in ("update", "delete"):+ if not params.event_id:+ raise RuntimeError("Event ID is required")++ if op == "delete":+ await run_sync(lambda: events_svc.delete(+ calendarId=cal_id, eventId=params.event_id, sendUpdates=params.send_updates,+ ).execute())+ await track_google_usage("google_calendar", ctx.node_id, "delete", 1, ctx.raw)+ return CalendarOutput(operation="delete", deleted=True, event_id=params.event_id)++ event = await run_sync(lambda: events_svc.get(calendarId=cal_id, eventId=params.event_id).execute())+ title = params.update_title or params.title+ start = params.update_start_time or params.start_time+ end = params.update_end_time or params.end_time+ desc = params.update_description if params.update_description is not None else params.description+ loc = params.update_location if params.update_location is not None else params.location++ if title:+ event['summary'] = title+ if start:+ tz = event.get('start', {}).get('timeZone', 'UTC')+ event['start'] = {'dateTime': start, 'timeZone': tz}+ if end:+ tz = event.get('end', {}).get('timeZone', 'UTC')+ event['end'] = {'dateTime': end, 'timeZone': tz}+ if desc is not None:+ event['description'] = desc+ if loc is not None:+ event['location'] = loc++ result = await run_sync(lambda: events_svc.update(+ calendarId=cal_id, eventId=params.event_id, body=event,+ sendUpdates=params.send_updates,+ ).execute())+ await track_google_usage("google_calendar", ctx.node_id, "update", 1, ctx.raw)+ return CalendarOutput(+ operation="update",+ event_id=result.get('id'),+ title=result.get('summary'),+ start=result.get('start', {}).get('dateTime'),+ end=result.get('end', {}).get('dateTime'),+ updated=result.get('updated'),+ html_link=result.get('htmlLink'),+ )++ raise RuntimeError(f"Unknown Calendar operation: {op}")diff --git a/server/nodes/google/contacts.py b/server/nodes/google/contacts.pyindex 3354d258..bab28158 100644--- a/server/nodes/google/contacts.py+++ b/server/nodes/google/contacts.py@@ -1,35 +1,82 @@-"""Google Contacts — Wave 11.C migration."""+"""Google Contacts — Wave 11.D.4 inlined (People API v1)."""from __future__ import annotations-from typing import Any, Literal, Optional+from typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+class ContactsParams(BaseModel):operation: Literal["create", "list", "search", "get", "update", "delete"] = "list"- contact_id: str = Field(default="", alias="contactId")- given_name: str = Field(default="", alias="givenName")- family_name: str = Field(default="", alias="familyName")- email: str = Field(default="")- phone: str = Field(default="")- query: str = Field(default="")- max_results: int = Field(default=20, alias="maxResults", ge=1, le=1000)+ resource_name: Optional[str] = Field(default=None, alias="resourceName")+ first_name: Optional[str] = Field(default=None, alias="firstName")+ last_name: Optional[str] = Field(default=None, alias="lastName")+ email: Optional[str] = None+ phone: Optional[str] = None+ company: Optional[str] = None+ job_title: Optional[str] = Field(default=None, alias="jobTitle")+ notes: Optional[str] = None+ query: Optional[str] = None+ page_size: int = Field(default=100, alias="pageSize")+ page_token: Optional[str] = Field(default=None, alias="pageToken")+ sort_order: str = Field(default="LAST_MODIFIED_DESCENDING", alias="sortOrder")++ update_first_name: Optional[str] = Field(default=None, alias="updateFirstName")+ update_last_name: Optional[str] = Field(default=None, alias="updateLastName")+ update_email: Optional[str] = Field(default=None, alias="updateEmail")+ update_phone: Optional[str] = Field(default=None, alias="updatePhone")+ update_company: Optional[str] = Field(default=None, alias="updateCompany")+ update_job_title: Optional[str] = Field(default=None, alias="updateJobTitle")model_config = ConfigDict(populate_by_name=True, extra="allow")class ContactsOutput(BaseModel):operation: Optional[str] = None- contact_id: Optional[str] = None- contacts: Optional[list] = None+ contact: Optional[dict] = None+ contacts: Optional[List[dict]] = None+ count: Optional[int] = None+ total_people: Optional[int] = None+ next_page_token: Optional[str] = None+ deleted: Optional[bool] = None+ resource_name: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")+def _format_contact(person: Dict[str, Any]) -> Dict[str, Any]:+ names = person.get('names', [{}])+ emails = person.get('emailAddresses', [])+ phones = person.get('phoneNumbers', [])+ orgs = person.get('organizations', [])+ photos = person.get('photos', [])++ primary_name = names[0] if names else {}+ primary_email = next((e for e in emails if e.get('metadata', {}).get('primary')), emails[0] if emails else {})+ primary_phone = next((p for p in phones if p.get('metadata', {}).get('primary')), phones[0] if phones else {})+ primary_org = orgs[0] if orgs else {}+ primary_photo = next((p for p in photos if p.get('metadata', {}).get('primary')), photos[0] if photos else {})++ return {+ 'resource_name': person.get('resourceName'),+ 'display_name': primary_name.get('displayName', ''),+ 'given_name': primary_name.get('givenName', ''),+ 'family_name': primary_name.get('familyName', ''),+ 'email': primary_email.get('value', ''),+ 'phone': primary_phone.get('value', ''),+ 'company': primary_org.get('name', ''),+ 'job_title': primary_org.get('title', ''),+ 'photo_url': primary_photo.get('url', ''),+ 'emails': [e.get('value') for e in emails],+ 'phones': [p.get('value') for p in phones],+ }++class ContactsNode(ActionNode):type = "contacts"display_name = "Contacts"@@ -53,12 +100,125 @@ class ContactsNode(ActionNode):Output = ContactsOutput@Operation("dispatch", cost={"service": "contacts", "action": "op", "count": 1})- async def dispatch(self, ctx: NodeContext, params: ContactsParams) -> Any:- from services.handlers.contacts import handle_google_contacts- response = await handle_google_contacts(- 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 "Contacts op failed")+ async def dispatch(self, ctx: NodeContext, params: ContactsParams) -> ContactsOutput:+ svc = await build_google_service("people", "v1", params.model_dump(by_alias=True), ctx.raw)+ people_svc = svc.people()+ op = params.operation++ if op == "create":+ if not params.first_name:+ raise RuntimeError("First name is required")+ body: Dict[str, Any] = {+ 'names': [{'givenName': params.first_name, 'familyName': params.last_name or ''}],+ }+ if params.email:+ body['emailAddresses'] = [{'value': params.email}]+ if params.phone:+ body['phoneNumbers'] = [{'value': params.phone}]+ if params.company or params.job_title:+ body['organizations'] = [{'name': params.company or '', 'title': params.job_title or ''}]+ if params.notes:+ body['biographies'] = [{'value': params.notes, 'contentType': 'TEXT_PLAIN'}]++ result = await run_sync(lambda: people_svc.createContact(body=body).execute())+ await track_google_usage("google_contacts", ctx.node_id, "create", 1, ctx.raw)+ return ContactsOutput(operation="create", contact=_format_contact(result))++ if op == "list":+ list_kwargs = {+ 'resourceName': 'people/me',+ 'pageSize': params.page_size,+ 'personFields': 'names,emailAddresses,phoneNumbers,organizations,photos,biographies',+ 'sortOrder': params.sort_order,+ }+ if params.page_token:+ list_kwargs['pageToken'] = params.page_token+ result = await run_sync(lambda: people_svc.connections().list(**list_kwargs).execute())+ connections = result.get('connections', [])+ contacts = [_format_contact(p) for p in connections]+ await track_google_usage("google_contacts", ctx.node_id, "list", len(contacts), ctx.raw)+ return ContactsOutput(+ operation="list",+ contacts=contacts,+ count=len(contacts),+ total_people=result.get('totalPeople', 0),+ next_page_token=result.get('nextPageToken'),+ )++ if op == "search":+ if not params.query:+ raise RuntimeError("Search query is required")+ result = await run_sync(lambda: people_svc.searchContacts(+ query=params.query,+ pageSize=min(params.page_size, 30),+ readMask='names,emailAddresses,phoneNumbers,organizations,photos',+ ).execute())+ contacts = [_format_contact(r.get('person', {})) for r in result.get('results', [])]+ await track_google_usage("google_contacts", ctx.node_id, "search", len(contacts), ctx.raw)+ return ContactsOutput(operation="search", contacts=contacts, count=len(contacts))++ if op == "get":+ if not params.resource_name:+ raise RuntimeError("Resource name is required")+ result = await run_sync(lambda: people_svc.get(+ resourceName=params.resource_name,+ personFields='names,emailAddresses,phoneNumbers,organizations,photos,biographies,addresses',+ ).execute())+ await track_google_usage("google_contacts", ctx.node_id, "get", 1, ctx.raw)+ return ContactsOutput(operation="get", contact=_format_contact(result))++ if op == "delete":+ if not params.resource_name:+ raise RuntimeError("Resource name is required")+ await run_sync(lambda: people_svc.deleteContact(resourceName=params.resource_name).execute())+ await track_google_usage("google_contacts", ctx.node_id, "delete", 1, ctx.raw)+ return ContactsOutput(operation="delete", deleted=True, resource_name=params.resource_name)++ if op == "update":+ if not params.resource_name:+ raise RuntimeError("Resource name is required")++ current = await run_sync(lambda: people_svc.get(+ resourceName=params.resource_name,+ personFields='names,emailAddresses,phoneNumbers,organizations,metadata',+ ).execute())++ first = params.update_first_name or params.first_name+ last = params.update_last_name or params.last_name+ email = params.update_email or params.email+ phone = params.update_phone or params.phone+ company = params.update_company or params.company+ job_title = params.update_job_title or params.job_title++ body: Dict[str, Any] = {'etag': current.get('etag')}+ update_fields: List[str] = []++ if first or last:+ cur_names = current.get('names', [{}])[0]+ body['names'] = [{+ 'givenName': first or cur_names.get('givenName', ''),+ 'familyName': last or cur_names.get('familyName', ''),+ }]+ update_fields.append('names')+ if email:+ body['emailAddresses'] = [{'value': email}]+ update_fields.append('emailAddresses')+ if phone:+ body['phoneNumbers'] = [{'value': phone}]+ update_fields.append('phoneNumbers')+ if company or job_title:+ body['organizations'] = [{'name': company or '', 'title': job_title or ''}]+ update_fields.append('organizations')++ if not update_fields:+ raise RuntimeError("At least one field to update is required")++ result = await run_sync(lambda: people_svc.updateContact(+ resourceName=params.resource_name,+ body=body,+ updatePersonFields=','.join(update_fields),+ ).execute())+ await track_google_usage("google_contacts", ctx.node_id, "update", 1, ctx.raw)+ return ContactsOutput(operation="update", contact=_format_contact(result))++ raise RuntimeError(f"Unknown Contacts operation: {op}")diff --git a/server/nodes/google/drive.py b/server/nodes/google/drive.pyindex 7e1df6ac..b793c84e 100644--- a/server/nodes/google/drive.py+++ b/server/nodes/google/drive.py@@ -1,26 +1,38 @@-"""Google Drive — Wave 11.C migration."""+"""Google Drive — Wave 11.D.4 inlined."""from __future__ import annotations-from typing import Any, Literal, Optional+import base64+import io+from typing import List, Literal, Optional+import httpx+from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUploadfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+class DriveParams(BaseModel):operation: Literal["upload", "download", "list", "share"] = "list"- file_id: str = Field(default="", alias="fileId")- file_name: str = Field(default="", alias="fileName")- file_path: str = Field(default="", alias="filePath")- folder_id: str = Field(default="", alias="folderId")- mime_type: str = Field(default="", alias="mimeType")- share_email: str = Field(default="", alias="shareEmail")- share_role: Literal["reader", "writer", "commenter"] = Field(- default="reader", alias="shareRole",- )+ file_id: Optional[str] = Field(default=None, alias="fileId")+ filename: Optional[str] = None+ file_url: Optional[str] = Field(default=None, alias="fileUrl")+ file_content: Optional[str] = Field(default=None, alias="fileContent")+ folder_id: Optional[str] = Field(default=None, alias="folderId")+ mime_type: str = Field(default="application/octet-stream", alias="mimeType")+ description: Optional[str] = None+ output_format: Literal["base64", "url"] = Field(default="base64", alias="outputFormat")+ query: Optional[str] = None+ file_types: str = Field(default="all", alias="fileTypes")+ order_by: str = Field(default="modifiedTime desc", alias="orderBy")max_results: int = Field(default=20, alias="maxResults", ge=1, le=1000)+ email: Optional[str] = None+ role: str = "reader"+ send_notification: bool = Field(default=True, alias="sendNotification")+ message: Optional[str] = Nonemodel_config = ConfigDict(populate_by_name=True, extra="allow")@@ -28,12 +40,32 @@ class DriveParams(BaseModel):class DriveOutput(BaseModel):operation: Optional[str] = Nonefile_id: Optional[str] = None- files: Optional[list] = None- download_path: Optional[str] = None+ name: Optional[str] = None+ mime_type: Optional[str] = None+ size: Optional[int] = None+ web_link: Optional[str] = None+ download_link: Optional[str] = None+ download_url: Optional[str] = None+ created_time: Optional[str] = None+ content_base64: Optional[str] = None+ files: Optional[List[dict]] = None+ count: Optional[int] = None+ next_page_token: Optional[str] = None+ permission_id: Optional[str] = None+ file_name: Optional[str] = None+ shared_with: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")+_FILE_TYPE_QUERY = {+ 'folder': "mimeType = 'application/vnd.google-apps.folder'",+ 'document': "mimeType = 'application/vnd.google-apps.document'",+ 'spreadsheet': "mimeType = 'application/vnd.google-apps.spreadsheet'",+ 'image': "mimeType contains 'image/'",+}++class DriveNode(ActionNode):type = "drive"display_name = "Drive"@@ -57,12 +89,158 @@ class DriveNode(ActionNode):Output = DriveOutput@Operation("dispatch", cost={"service": "drive", "action": "op", "count": 1})- async def dispatch(self, ctx: NodeContext, params: DriveParams) -> Any:- from services.handlers.drive import handle_google_drive- response = await handle_google_drive(- 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 "Drive op failed")+ async def dispatch(self, ctx: NodeContext, params: DriveParams) -> DriveOutput:+ svc = await build_google_service("drive", "v3", params.model_dump(by_alias=True), ctx.raw)+ files_svc = svc.files()+ op = params.operation++ if op == "upload":+ if not params.filename:+ raise RuntimeError("Filename is required")+ if not params.file_url and not params.file_content:+ raise RuntimeError("Either file_url or file_content is required")++ metadata = {'name': params.filename}+ if params.folder_id:+ metadata['parents'] = [params.folder_id]+ if params.description:+ metadata['description'] = params.description++ mime_type = params.mime_type+ if params.file_url:+ async with httpx.AsyncClient() as client:+ resp = await client.get(params.file_url, timeout=60.0)+ resp.raise_for_status()+ file_bytes = resp.content+ if mime_type == 'application/octet-stream' and 'content-type' in resp.headers:+ mime_type = resp.headers['content-type'].split(';')[0]+ else:+ file_bytes = base64.b64decode(params.file_content)++ media = MediaIoBaseUpload(io.BytesIO(file_bytes), mimetype=mime_type, resumable=True)+ result = await run_sync(lambda: files_svc.create(+ body=metadata, media_body=media,+ fields='id, name, mimeType, size, webViewLink, webContentLink, createdTime',+ ).execute())+ await track_google_usage("google_drive", ctx.node_id, "upload", 1, ctx.raw)+ return DriveOutput(+ operation="upload",+ file_id=result.get('id'),+ name=result.get('name'),+ mime_type=result.get('mimeType'),+ size=int(result.get('size')) if result.get('size') else None,+ web_link=result.get('webViewLink'),+ download_link=result.get('webContentLink'),+ created_time=result.get('createdTime'),+ )++ if op == "download":+ if not params.file_id:+ raise RuntimeError("File ID is required")++ metadata = await run_sync(lambda: files_svc.get(+ fileId=params.file_id,+ fields='id, name, mimeType, size, webViewLink, webContentLink',+ ).execute())++ if params.output_format == "url":+ await track_google_usage("google_drive", ctx.node_id, "download", 1, ctx.raw)+ return DriveOutput(+ operation="download",+ file_id=metadata.get('id'),+ name=metadata.get('name'),+ mime_type=metadata.get('mimeType'),+ size=int(metadata.get('size')) if metadata.get('size') else None,+ download_url=metadata.get('webContentLink'),+ web_link=metadata.get('webViewLink'),+ )++ def _download():+ request = files_svc.get_media(fileId=params.file_id)+ buf = io.BytesIO()+ downloader = MediaIoBaseDownload(buf, request)+ done = False+ while not done:+ _, done = downloader.next_chunk()+ return buf.getvalue()++ file_bytes = await run_sync(_download)+ await track_google_usage("google_drive", ctx.node_id, "download", 1, ctx.raw)+ return DriveOutput(+ operation="download",+ file_id=metadata.get('id'),+ name=metadata.get('name'),+ mime_type=metadata.get('mimeType'),+ size=len(file_bytes),+ content_base64=base64.b64encode(file_bytes).decode('utf-8'),+ )++ if op == "list":+ query_parts = []+ if params.folder_id:+ query_parts.append(f"'{params.folder_id}' in parents")+ if params.query:+ query_parts.append(params.query)+ if params.file_types in _FILE_TYPE_QUERY:+ query_parts.append(_FILE_TYPE_QUERY[params.file_types])+ query_parts.append("trashed = false")+ full_query = ' and '.join(query_parts)++ list_kwargs = {+ 'pageSize': min(params.max_results, 1000),+ 'fields': 'nextPageToken, files(id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime, parents, owners)',+ 'orderBy': params.order_by,+ }+ if full_query:+ list_kwargs['q'] = full_query++ result = await run_sync(lambda: files_svc.list(**list_kwargs).execute())+ raw = result.get('files', [])+ formatted = [{+ "file_id": f.get('id'),+ "name": f.get('name'),+ "mime_type": f.get('mimeType'),+ "size": f.get('size'),+ "web_link": f.get('webViewLink'),+ "download_link": f.get('webContentLink'),+ "created_time": f.get('createdTime'),+ "modified_time": f.get('modifiedTime'),+ "parent_ids": f.get('parents', []),+ "owner": f.get('owners', [{}])[0].get('emailAddress') if f.get('owners') else None,+ } for f in raw]+ await track_google_usage("google_drive", ctx.node_id, "list", len(formatted), ctx.raw)+ return DriveOutput(+ operation="list",+ files=formatted,+ count=len(formatted),+ next_page_token=result.get('nextPageToken'),+ )++ if op == "share":+ if not params.file_id:+ raise RuntimeError("File ID is required")+ if not params.email:+ raise RuntimeError("Email address is required")++ perm = await run_sync(lambda: svc.permissions().create(+ fileId=params.file_id,+ body={'type': 'user', 'role': params.role, 'emailAddress': params.email},+ sendNotificationEmail=params.send_notification,+ emailMessage=params.message or None,+ fields='id, type, role, emailAddress',+ ).execute())+ file_info = await run_sync(lambda: files_svc.get(+ fileId=params.file_id, fields='id, name, webViewLink',+ ).execute())+ await track_google_usage("google_drive", ctx.node_id, "share", 1, ctx.raw)+ return DriveOutput(+ operation="share",+ permission_id=perm.get('id'),+ file_id=params.file_id,+ file_name=file_info.get('name'),+ shared_with=params.email,+ role=params.role,+ web_link=file_info.get('webViewLink'),+ )++ raise RuntimeError(f"Unknown Drive operation: {op}")diff --git a/server/nodes/google/gmail.py b/server/nodes/google/gmail.pyindex d0dfabf9..cb9c442c 100644--- a/server/nodes/google/gmail.py+++ b/server/nodes/google/gmail.py@@ -1,45 +1,29 @@-"""Gmail — Wave 11.B reference migration (multi-op ActionNode).--Demonstrates the ``@Operation`` dispatch pattern: three operations-(send / search / read) declared as methods, dispatched on-``parameters.operation`` automatically by :class:`BaseNode._pick_operation`.--Replaces:-- ``server/nodes/services.py:gmail`` metadata-only registration- (removed).-- Legacy ``node_executor.py`` routes ``gmail`` → plugin handler via- the additive plugin registry merge — no code change in the executor.--Per-op bodies delegate to the existing Google-auth + Google-API-client-code in ``handlers/gmail.py``. 11.E converts to a declarative-``GoogleCredential`` shared with calendar/drive/sheets.--This migration also keeps the tool-mode path intact —-``handlers/tools.py`` calls ``handle_google_gmail`` directly for-AI-agent-invoked gmail operations. 11.D unifies that path.-"""+"""Gmail — Wave 11.D.4 inlined (multi-op ActionNode)."""from __future__ import annotations-from typing import Any, ClassVar, Dict, List, Literal, Optional+import base64+from email.mime.multipart import MIMEMultipart+from email.mime.text import MIMEText+from typing import List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+from ._gmail import fetch_email_details, format_message-class GmailParams(BaseModel):- """All three ops share one Params model — per-field gating via- ``displayOptions.show`` hides irrelevant UI rows in the parameter- panel, same pattern the legacy ``GmailParams`` uses."""+class GmailParams(BaseModel):operation: Literal["send", "search", "read"] = "send"- # sendto: str = Field(default="",json_schema_extra={"displayOptions": {"show": {"operation": ["send"]}}},)+ cc: str = Field(default="", json_schema_extra={"displayOptions": {"show": {"operation": ["send"]}}})+ bcc: str = Field(default="", json_schema_extra={"displayOptions": {"show": {"operation": ["send"]}}})subject: str = Field(default="",json_schema_extra={"displayOptions": {"show": {"operation": ["send"]}}},@@ -52,8 +36,8 @@ class GmailParams(BaseModel):"displayOptions": {"show": {"operation": ["send"]}},},)+ body_type: Literal["text", "html"] = Field(default="text", alias="bodyType")- # searchquery: str = Field(default="",json_schema_extra={@@ -61,13 +45,15 @@ class GmailParams(BaseModel):"displayOptions": {"show": {"operation": ["search"]}},},)+ max_results: int = Field(default=10, alias="maxResults", ge=1, le=100)+ include_body: bool = Field(default=False, alias="includeBody")- # readmessage_id: str = Field(default="",alias="messageId",json_schema_extra={"displayOptions": {"show": {"operation": ["read"]}}},)+ format: Literal["full", "minimal", "raw", "metadata"] = "full"model_config = ConfigDict(populate_by_name=True, extra="ignore")@@ -76,15 +62,19 @@ class GmailOutput(BaseModel):operation: Optional[str] = Nonemessage_id: Optional[str] = Nonethread_id: Optional[str] = None- emails: Optional[list] = None- count: Optional[int] = None+ label_ids: Optional[List[str]] = None+ to: Optional[str] = Nonesubject: Optional[str] = None+ messages: Optional[List[dict]] = None+ count: Optional[int] = None+ query: Optional[str] = None+ result_size_estimate: Optional[int] = Nonefrom_: Optional[str] = Field(default=None, alias="from")- to: Optional[str] = Nonedate: Optional[str] = Nonebody: Optional[str] = Nonesnippet: Optional[str] = None- labels: Optional[list] = None+ labels: Optional[List[str]] = None+ attachments: Optional[List[dict]] = Nonemodel_config = ConfigDict(populate_by_name=True, extra="allow")@@ -104,8 +94,6 @@ class GmailNode(ActionNode):{"name": "output-main", "kind": "output", "position": "right","label": "Output", "role": "main"},)- # Google OAuth stays on the legacy ``google_auth`` helper during- # thin-delegation phase. 11.E introduces ``GoogleCredential``.credentials = ()annotations = {"destructive": False, "readonly": False, "open_world": True}task_queue = TaskQueue.REST_API@@ -114,32 +102,84 @@ class GmailNode(ActionNode):Params = GmailParamsOutput = GmailOutput+ async def _service(self, ctx: NodeContext, params: GmailParams):+ return await build_google_service(+ "gmail", "v1", params.model_dump(by_alias=True), ctx.raw,+ )+@Operation("send", cost={"service": "gmail", "action": "send", "count": 1})- async def send(self, ctx: NodeContext, params: GmailParams) -> Dict[str, Any]:- from services.handlers.gmail import handle_gmail_send- return await self._delegate(handle_gmail_send, ctx, params)+ async def send(self, ctx: NodeContext, params: GmailParams) -> GmailOutput:+ if not params.to:+ raise RuntimeError("Recipient email address (to) is required")+ if not params.subject:+ raise RuntimeError("Email subject is required")+ if not params.body:+ raise RuntimeError("Email body is required")++ if params.body_type == "html":+ message = MIMEMultipart('alternative')+ message.attach(MIMEText(params.body, 'html'))+ else:+ message = MIMEText(params.body, 'plain')+ message['to'] = params.to+ message['subject'] = params.subject+ if params.cc:+ message['cc'] = params.cc+ if params.bcc:+ message['bcc'] = params.bcc++ raw = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')+ svc = await self._service(ctx, params)+ result = await run_sync(lambda: svc.users().messages().send(+ userId='me', body={'raw': raw},+ ).execute())+ await track_google_usage("gmail", ctx.node_id, "send", 1, ctx.raw)+ return GmailOutput(+ operation="send",+ message_id=result.get('id'),+ thread_id=result.get('threadId'),+ label_ids=result.get('labelIds', []),+ to=params.to,+ subject=params.subject,+ )@Operation("search", cost={"service": "gmail", "action": "search", "count": 1})- async def search(self, ctx: NodeContext, params: GmailParams) -> Dict[str, Any]:- from services.handlers.gmail import handle_gmail_search- return await self._delegate(handle_gmail_search, ctx, params)+ async def search(self, ctx: NodeContext, params: GmailParams) -> GmailOutput:+ if not params.query:+ raise RuntimeError("Search query is required")+ svc = await self._service(ctx, params)+ listing = await run_sync(lambda: svc.users().messages().list(+ userId='me', q=params.query, maxResults=min(params.max_results, 100),+ ).execute())++ messages = listing.get('messages', [])+ formatted = []+ fmt = 'full' if params.include_body else 'metadata'+ for msg in messages:+ mid = msg.get('id')+ detail = await run_sync(lambda m=mid: svc.users().messages().get(+ userId='me', id=m, format=fmt,+ metadataHeaders=['From', 'To', 'Subject', 'Date'],+ ).execute())+ formatted.append(format_message(detail, include_body=params.include_body))++ await track_google_usage("gmail", ctx.node_id, "search", len(formatted), ctx.raw)+ return GmailOutput(+ operation="search",+ messages=formatted,+ count=len(formatted),+ query=params.query,+ result_size_estimate=listing.get('resultSizeEstimate', 0),+ )@Operation("read", cost={"service": "gmail", "action": "read", "count": 1})- async def read(self, ctx: NodeContext, params: GmailParams) -> Dict[str, Any]:- from services.handlers.gmail import handle_gmail_read- return await self._delegate(handle_gmail_read, ctx, params)-- async def _delegate(self, handler, ctx: NodeContext, params: GmailParams) -> Any:- """Call a legacy handler with the original ``parameters`` dict,- unwrap its ``{success, result, ...}`` envelope, return just the- ``result`` — :meth:`BaseNode._wrap_success` re-wraps.- """- payload = params.model_dump(by_alias=True)- response = await handler(- node_id=ctx.node_id, node_type=self.type,- parameters=payload, context=ctx.raw,- )- if response.get("success"):- return response.get("result") or response- # Surface failure via the BaseNode error path.- raise RuntimeError(response.get("error") or "gmail operation failed")+ async def read(self, ctx: NodeContext, params: GmailParams) -> GmailOutput:+ if not params.message_id:+ raise RuntimeError("message_id is required")+ svc = await self._service(ctx, params)+ result = await run_sync(lambda: svc.users().messages().get(+ userId='me', id=params.message_id, format=params.format,+ ).execute())+ await track_google_usage("gmail", ctx.node_id, "read", 1, ctx.raw)+ formatted = format_message(result, include_body=(params.format == 'full'))+ return GmailOutput(operation="read", **{k: v for k, v in formatted.items() if k != 'size_estimate'})diff --git a/server/nodes/google/gmail_receive.py b/server/nodes/google/gmail_receive.pyindex 6528c46d..3cf18cf3 100644--- a/server/nodes/google/gmail_receive.py+++ b/server/nodes/google/gmail_receive.py@@ -1,30 +1,22 @@-"""Gmail Receive — Wave 11.B reference migration (polling trigger).--Polls the Gmail API on a configurable interval for new messages-matching a filter query. Delegates the actual poll loop to the-existing ``handlers/gmail.handle_gmail_receive`` — 11.B establishes the-plugin shell + schema; the full loop port lands in 11.C alongside the-other Google Workspace nodes so it can reuse the Connection facade for-OAuth refresh.--Replaces:-- ``server/nodes/triggers.py:gmailReceive`` metadata-only registration.- The legacy handler + its entry in ``node_executor.py`` stay — plugin- :meth:`execute` delegates to it, which is an explicit thin-wrapper- pattern the plan accepts for this sub-wave.--Deployment-mode polling lifecycle (``deployment/manager.py``) is-unaffected: it checks ``node_type == 'gmailReceive'`` directly.-"""+"""Gmail Receive — Wave 11.D.5 fully inlined (polling trigger)."""from __future__ import annotations-from typing import Any, ClassVar, Dict, Literal, Optional+import asyncio+import time+from datetime import datetime+from typing import Any, Dict, Literal, Optional, Setfrom pydantic import BaseModel, ConfigDict, Field+from core.logging import get_loggerfrom services.plugin import NodeContext, Operation, TaskQueue, TriggerNode+from ._base import build_google_service, track_google_usage+from ._gmail import fetch_email_details, mark_email_as_read, poll_gmail_ids++logger = get_logger(__name__)+class GmailReceiveParams(BaseModel):filter_query: str = Field(@@ -70,9 +62,6 @@ class GmailReceiveNode(TriggerNode):{"name": "output-main", "kind": "output", "position": "right","label": "Output", "role": "main"},)- # Google OAuth handled by the legacy google_auth helper during the- # thin-delegation phase. 11.C converts this to a declarative- # GoogleCredential subclass shared with gmail/calendar/drive/…task_queue = TaskQueue.TRIGGERS_POLLmode = "polling"default_poll_interval = 60@@ -86,35 +75,17 @@ class GmailReceiveNode(TriggerNode):parameters: Dict[str, Any],context: NodeContext,) -> Dict[str, Any]:- """Polling-trigger body inlined from handlers/gmail.py (Wave 11.D.5).-- Baseline → poll → dispatch. Private helpers- (``_poll_gmail_ids`` / ``_fetch_email_details`` /- ``_mark_email_as_read`` / ``_get_gmail_service`` /- ``_track_gmail_usage``) stay in handlers/gmail.py because they- are shared with gmail send/search/read operations — delete in- 11.D.13 along with the whole google handlers module.- """- import asyncio- import time- from datetime import datetime- from core.logging import get_logger+ """Polling loop: baseline existing IDs, sleep, fetch new ones, dispatch."""from services import event_waiter- from services.handlers.gmail import (- _get_gmail_service, _poll_gmail_ids,- _fetch_email_details, _mark_email_as_read,- _track_gmail_usage,- )from services.status_broadcaster import get_status_broadcaster- log = get_logger(__name__)start_time = time.time()try:- service = await _get_gmail_service(parameters, context.raw)+ svc = await build_google_service("gmail", "v1", parameters, context.raw)poll_interval = max(10, min(3600, parameters.get("poll_interval", 60)))filter_query = parameters.get("filter_query", "is:unread")label_filter = parameters.get("label_filter", "INBOX")- mark_as_read = parameters.get("mark_as_read", False)+ mark_read = parameters.get("mark_as_read", False)query = filter_queryif label_filter and label_filter != "all":@@ -129,44 +100,40 @@ class GmailReceiveNode(TriggerNode):workflow_id=context.workflow_id,)- seen_ids = set()+ seen_ids: Set[str] = set()try:- seen_ids.update(await _poll_gmail_ids(service, query))- log.info(- f"[GmailReceive] Baseline: {len(seen_ids)} existing emails "- f"for query '{query}'",+ seen_ids.update(await poll_gmail_ids(svc, query))+ logger.info(+ f"[GmailReceive] Baseline: {len(seen_ids)} existing emails for query '{query}'",)except Exception as e:- log.warning(- f"[GmailReceive] Baseline fetch failed (will treat all as new): {e}",- )+ logger.warning(f"[GmailReceive] Baseline fetch failed (treating all as new): {e}")while True:await asyncio.sleep(poll_interval)try:- current_ids = await _poll_gmail_ids(service, query)+ current_ids = await poll_gmail_ids(svc, query)new_ids = current_ids - seen_idsif not new_ids:continuenewest_id = next(iter(new_ids))seen_ids.update(new_ids)- email_data = await _fetch_email_details(service, newest_id)+ email_data = await fetch_email_details(svc, newest_id)- if mark_as_read:+ if mark_read:try:- await _mark_email_as_read(service, newest_id)+ await mark_email_as_read(svc, newest_id)except Exception as e:- log.warning(f"[GmailReceive] Failed to mark as read: {e}")+ logger.warning(f"[GmailReceive] Failed to mark as read: {e}")- await _track_gmail_usage(- node_id, "receive", 1,- context.workflow_id, context.session_id,+ await track_google_usage(+ "gmail", node_id, "receive", 1,+ {"workflow_id": context.workflow_id, "session_id": context.session_id},)event_waiter.dispatch("gmail_email_received", email_data)- log.info(- f"[GmailReceive] New email found: "- f"{email_data.get('subject', 'no subject')}",+ logger.info(+ f"[GmailReceive] New email: {email_data.get('subject', 'no subject')}",)return {"success": True, "node_id": node_id, "node_type": self.type,@@ -177,10 +144,10 @@ class GmailReceiveNode(TriggerNode):except asyncio.CancelledError:raiseexcept Exception as e:- log.error(f"[GmailReceive] Poll error (will retry): {e}")+ logger.error(f"[GmailReceive] Poll error (will retry): {e}")except asyncio.CancelledError:- log.info(f"[GmailReceive] Cancelled by user: node_id={node_id}")+ logger.info(f"[GmailReceive] Cancelled by user: node_id={node_id}")return {"success": False, "node_id": node_id, "node_type": self.type,"error": "Cancelled by user",@@ -188,7 +155,7 @@ class GmailReceiveNode(TriggerNode):"timestamp": datetime.now().isoformat(),}except Exception as e:- log.error(f"[GmailReceive] Error: {e}")+ logger.error(f"[GmailReceive] Error: {e}")return {"success": False, "node_id": node_id, "node_type": self.type,"error": str(e),diff --git a/server/nodes/google/sheets.py b/server/nodes/google/sheets.pyindex de8b4544..b2305f52 100644--- a/server/nodes/google/sheets.py+++ b/server/nodes/google/sheets.py@@ -1,31 +1,57 @@-"""Google Sheets — Wave 11.C migration."""+"""Google Sheets — Wave 11.D.4 inlined.++Reads / writes / appends cells via the Sheets v4 API.+"""from __future__ import annotations+import jsonfrom typing import Any, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+class SheetsParams(BaseModel):operation: Literal["read", "write", "append"] = "read"spreadsheet_id: str = Field(default="", alias="spreadsheetId")range: str = Field(default="A1:Z1000")- values: List[List[Any]] = Field(default_factory=list)+ values: Any = Field(default_factory=list)+ value_input_option: str = Field(default="USER_ENTERED", alias="valueInputOption")+ value_render_option: str = Field(default="FORMATTED_VALUE", alias="valueRenderOption")+ major_dimension: str = Field(default="ROWS", alias="majorDimension")+ insert_data_option: str = Field(default="INSERT_ROWS", alias="insertDataOption")model_config = ConfigDict(populate_by_name=True, extra="allow")class SheetsOutput(BaseModel):operation: Optional[str] = None- rows: Optional[list] = None+ values: Optional[List[List[Any]]] = None+ range: Optional[str] = None+ rows: Optional[int] = None+ columns: Optional[int] = None+ major_dimension: Optional[str] = None+ updated_range: Optional[str] = None+ updated_rows: Optional[int] = None+ updated_columns: Optional[int] = Noneupdated_cells: Optional[int] = None+ table_range: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")+def _coerce_values(raw: Any) -> List[List[Any]]:+ if isinstance(raw, str):+ raw = json.loads(raw)+ if raw and not isinstance(raw[0], list):+ raw = [raw]+ return raw++class SheetsNode(ActionNode):type = "sheets"display_name = "Sheets"@@ -49,12 +75,77 @@ class SheetsNode(ActionNode):Output = SheetsOutput@Operation("dispatch", cost={"service": "sheets", "action": "op", "count": 1})- async def dispatch(self, ctx: NodeContext, params: SheetsParams) -> Any:- from services.handlers.sheets import handle_google_sheets- response = await handle_google_sheets(- 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 "Sheets op failed")+ async def dispatch(self, ctx: NodeContext, params: SheetsParams) -> SheetsOutput:+ if not params.spreadsheet_id:+ raise RuntimeError("Spreadsheet ID is required")+ if not params.range:+ raise RuntimeError("Range is required (e.g., 'Sheet1!A1:D10')")++ svc = await build_google_service("sheets", "v4", params.model_dump(by_alias=True), ctx.raw)+ values_svc = svc.spreadsheets().values()+ op = params.operation++ if op == "read":+ result = await run_sync(lambda: values_svc.get(+ spreadsheetId=params.spreadsheet_id,+ range=params.range,+ valueRenderOption=params.value_render_option,+ majorDimension=params.major_dimension,+ ).execute())+ rows = result.get('values', [])+ await track_google_usage("google_sheets", ctx.node_id, "read", len(rows), ctx.raw)+ return SheetsOutput(+ operation="read",+ values=rows,+ range=result.get('range'),+ rows=len(rows),+ columns=len(rows[0]) if rows else 0,+ major_dimension=result.get('majorDimension'),+ )++ if op in ("write", "append"):+ values = _coerce_values(params.values)+ if not values:+ raise RuntimeError("Values are required")++ if op == "write":+ result = await run_sync(lambda: values_svc.update(+ spreadsheetId=params.spreadsheet_id,+ range=params.range,+ valueInputOption=params.value_input_option,+ body={'values': values},+ ).execute())+ await track_google_usage(+ "google_sheets", ctx.node_id, "write",+ result.get('updatedCells', 0), ctx.raw,+ )+ return SheetsOutput(+ operation="write",+ updated_range=result.get('updatedRange'),+ updated_rows=result.get('updatedRows'),+ updated_columns=result.get('updatedColumns'),+ updated_cells=result.get('updatedCells'),+ )++ result = await run_sync(lambda: values_svc.append(+ spreadsheetId=params.spreadsheet_id,+ range=params.range,+ valueInputOption=params.value_input_option,+ insertDataOption=params.insert_data_option,+ body={'values': values},+ ).execute())+ updates = result.get('updates', {})+ await track_google_usage(+ "google_sheets", ctx.node_id, "append",+ updates.get('updatedCells', 0), ctx.raw,+ )+ return SheetsOutput(+ operation="append",+ updated_range=updates.get('updatedRange'),+ updated_rows=updates.get('updatedRows'),+ updated_columns=updates.get('updatedColumns'),+ updated_cells=updates.get('updatedCells'),+ table_range=result.get('tableRange'),+ )++ raise RuntimeError(f"Unknown Sheets operation: {op}. Supported: read, write, append")diff --git a/server/nodes/google/tasks.py b/server/nodes/google/tasks.pyindex 14d9906f..6f8c35b3 100644--- a/server/nodes/google/tasks.py+++ b/server/nodes/google/tasks.py@@ -1,21 +1,36 @@-"""Google Tasks — Wave 11.C migration."""+"""Google Tasks — Wave 11.D.4 inlined."""from __future__ import annotations-from typing import Any, Literal, Optional+from typing import List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from ._base import build_google_service, run_sync, track_google_usage+++def _ensure_rfc3339(due: str) -> str:+ return due if 'T' in due else f"{due}T00:00:00.000Z"+class TasksParams(BaseModel):operation: Literal["create", "list", "complete", "update", "delete"] = "list"- task_list_id: str = Field(default="@default", alias="taskListId")- task_id: str = Field(default="", alias="taskId")- title: str = Field(default="")- notes: str = Field(default="")- due: str = Field(default="")+ tasklist_id: str = Field(default="@default", alias="tasklistId")+ task_id: Optional[str] = Field(default=None, alias="taskId")+ title: Optional[str] = None+ notes: Optional[str] = None+ due_date: Optional[str] = Field(default=None, alias="dueDate")+ status: Optional[str] = None+ show_completed: bool = Field(default=False, alias="showCompleted")+ show_hidden: bool = Field(default=False, alias="showHidden")+ max_results: int = Field(default=100, alias="maxResults")++ update_title: Optional[str] = Field(default=None, alias="updateTitle")+ update_notes: Optional[str] = Field(default=None, alias="updateNotes")+ update_due_date: Optional[str] = Field(default=None, alias="updateDueDate")+ update_status: Optional[str] = Field(default=None, alias="updateStatus")model_config = ConfigDict(populate_by_name=True, extra="allow")@@ -23,7 +38,15 @@ class TasksParams(BaseModel):class TasksOutput(BaseModel):operation: Optional[str] = Nonetask_id: Optional[str] = None- tasks: Optional[list] = None+ title: Optional[str] = None+ notes: Optional[str] = None+ due: Optional[str] = None+ status: Optional[str] = None+ completed: Optional[str] = None+ self_link: Optional[str] = None+ tasks: Optional[List[dict]] = None+ count: Optional[int] = None+ deleted: Optional[bool] = Nonemodel_config = ConfigDict(extra="allow")@@ -51,12 +74,87 @@ class TasksNode(ActionNode):Output = TasksOutput@Operation("dispatch", cost={"service": "tasks", "action": "op", "count": 1})- async def dispatch(self, ctx: NodeContext, params: TasksParams) -> Any:- from services.handlers.tasks import handle_google_tasks- response = await handle_google_tasks(- 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 "Tasks op failed")+ async def dispatch(self, ctx: NodeContext, params: TasksParams) -> TasksOutput:+ svc = await build_google_service("tasks", "v1", params.model_dump(by_alias=True), ctx.raw)+ tasks_svc = svc.tasks()+ op = params.operation+ tasklist = params.tasklist_id++ if op == "create":+ if not params.title:+ raise RuntimeError("Task title is required")+ body = {'title': params.title}+ if params.notes:+ body['notes'] = params.notes+ if params.due_date:+ body['due'] = _ensure_rfc3339(params.due_date)+ result = await run_sync(lambda: tasks_svc.insert(tasklist=tasklist, body=body).execute())+ await track_google_usage("google_tasks", ctx.node_id, "create", 1, ctx.raw)+ return TasksOutput(+ operation="create",+ task_id=result.get('id'),+ title=result.get('title'),+ notes=result.get('notes'),+ due=result.get('due'),+ status=result.get('status'),+ self_link=result.get('selfLink'),+ )++ if op == "list":+ result = await run_sync(lambda: tasks_svc.list(+ tasklist=tasklist,+ showCompleted=params.show_completed,+ showHidden=params.show_hidden,+ maxResults=params.max_results,+ ).execute())+ items = result.get('items', [])+ formatted = [{+ 'task_id': t.get('id'), 'title': t.get('title'), 'notes': t.get('notes'),+ 'due': t.get('due'), 'status': t.get('status'),+ 'completed': t.get('completed'), 'position': t.get('position'),+ } for t in items]+ await track_google_usage("google_tasks", ctx.node_id, "list", len(formatted), ctx.raw)+ return TasksOutput(operation="list", tasks=formatted, count=len(formatted))++ if op in ("complete", "update", "delete"):+ if not params.task_id:+ raise RuntimeError("Task ID is required")++ if op == "delete":+ await run_sync(lambda: tasks_svc.delete(tasklist=tasklist, task=params.task_id).execute())+ await track_google_usage("google_tasks", ctx.node_id, "delete", 1, ctx.raw)+ return TasksOutput(operation="delete", deleted=True, task_id=params.task_id)++ current = await run_sync(lambda: tasks_svc.get(tasklist=tasklist, task=params.task_id).execute())++ if op == "complete":+ current['status'] = 'completed'+ else:+ title = params.update_title or params.title+ notes = params.update_notes or params.notes+ due = params.update_due_date or params.due_date+ status = params.update_status or params.status+ if title:+ current['title'] = title+ if notes:+ current['notes'] = notes+ if due:+ current['due'] = _ensure_rfc3339(due)+ if status:+ current['status'] = status++ result = await run_sync(lambda: tasks_svc.update(+ tasklist=tasklist, task=params.task_id, body=current,+ ).execute())+ await track_google_usage("google_tasks", ctx.node_id, op, 1, ctx.raw)+ return TasksOutput(+ operation=op,+ task_id=result.get('id'),+ title=result.get('title'),+ notes=result.get('notes'),+ due=result.get('due'),+ status=result.get('status'),+ completed=result.get('completed'),+ )++ raise RuntimeError(f"Unknown Tasks operation: {op}")diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pyindex b871d745..e07e1044 100644--- a/server/services/deployment/manager.py+++ b/server/services/deployment/manager.py@@ -700,13 +700,15 @@ class DeploymentManager:Establishes a baseline of existing emails to avoid triggering on old messages."""async def poll(queue: asyncio.Queue, is_running_fn: Callable):- from services.handlers.gmail import (- _get_gmail_service, _poll_gmail_ids,- _fetch_email_details, _mark_email_as_read+ from nodes.google._base import build_google_service+ from nodes.google._gmail import (+ poll_gmail_ids as _poll_gmail_ids,+ fetch_email_details as _fetch_email_details,+ mark_email_as_read as _mark_email_as_read,)# Authenticate with Gmail API- service = await _get_gmail_service(params, {})+ service = await build_google_service("gmail", "v1", params, {})poll_interval = max(10, min(3600, params.get('poll_interval', 60)))filter_query = params.get('filter_query', 'is:unread')diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex aacc3462..b2e7de6d 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -79,13 +79,7 @@ from .twitter import (handle_twitter_user,)-# Google Workspace handlers (consolidated)-from .gmail import handle_google_gmail, handle_gmail_receive-from .calendar import handle_google_calendar-from .drive import handle_google_drive-from .sheets import handle_google_sheets-from .tasks import handle_google_tasks-from .contacts import handle_google_contacts+# Google Workspace handlers inlined into nodes/google/*.py (Wave 11.D.4).# Social handlers (unified messaging)from .social import (@@ -182,14 +176,6 @@ __all__ = ['handle_twitter_send','handle_twitter_search','handle_twitter_user',- # Google Workspace (consolidated)- 'handle_google_gmail',- 'handle_gmail_receive',- 'handle_google_calendar',- 'handle_google_drive',- 'handle_google_sheets',- 'handle_google_tasks',- 'handle_google_contacts',# Social'handle_social_receive','handle_social_send',diff --git a/server/services/handlers/calendar.py b/server/services/handlers/calendar.pydeleted file mode 100644index 344bbfc7..00000000--- a/server/services/handlers/calendar.py+++ /dev/null@@ -1,448 +0,0 @@-"""Google Calendar node handlers using Google API Python client.--API Reference: https://developers.google.com/workspace/calendar/api/v3/reference-"""--import asyncio-import time-from datetime import datetime, timedelta-from typing import Any, Dict--from googleapiclient.discovery import build--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_calendar_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Google Calendar API usage for analytics.-- Note: Calendar API is free but rate limited (1M requests/min).- We track for analytics purposes with $0 cost.- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('google_calendar', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'google_calendar',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Calendar] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_calendar_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Google Calendar service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("calendar", "v3", credentials=creds)-- loop = asyncio.get_event_loop()- service = await loop.run_in_executor(None, build_service)-- return service---async def handle_calendar_create(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Create a calendar event.-- Parameters:- title: Event title/summary (required)- start_time: Start time in ISO format or datetime string (required)- end_time: End time in ISO format or datetime string (required)- description: Event description (optional)- location: Event location (optional)- attendees: Comma-separated email addresses (optional)- reminder_minutes: Minutes before event for reminder (optional, default: 30)- calendar_id: Calendar ID (optional, default: 'primary')- timezone: Timezone for the event (optional, default: UTC)- """- start_time = time.time()-- try:- service = await _get_calendar_service(parameters, context)-- title = parameters.get('title', '')- event_start = parameters.get('start_time', '')- event_end = parameters.get('end_time', '')- description = parameters.get('description', '')- location = parameters.get('location', '')- attendees_str = parameters.get('attendees', '')- reminder_minutes = parameters.get('reminder_minutes', 30)- calendar_id = parameters.get('calendar_id', 'primary')- timezone = parameters.get('timezone', 'UTC')-- if not title:- raise ValueError("Event title is required")- if not event_start:- raise ValueError("Start time is required")- if not event_end:- raise ValueError("End time is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Build event body- event = {- 'summary': title,- 'start': {'dateTime': event_start, 'timeZone': timezone},- 'end': {'dateTime': event_end, 'timeZone': timezone},- }-- if description:- event['description'] = description- if location:- event['location'] = location-- # Parse attendees- if attendees_str:- attendees = [{'email': e.strip()} for e in attendees_str.split(',') if e.strip()]- if attendees:- event['attendees'] = attendees-- # Add reminder- if reminder_minutes:- event['reminders'] = {- 'useDefault': False,- 'overrides': [- {'method': 'popup', 'minutes': int(reminder_minutes)},- ],- }-- def create_event():- return service.events().insert(- calendarId=calendar_id,- body=event,- sendUpdates='all' # Send email notifications to attendees- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, create_event)-- await _track_calendar_usage(node_id, 'create', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "event_id": result.get('id'),- "title": result.get('summary'),- "start": result.get('start', {}).get('dateTime'),- "end": result.get('end', {}).get('dateTime'),- "html_link": result.get('htmlLink'),- "status": result.get('status'),- "created": result.get('created'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Calendar create error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_calendar_list(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """List calendar events within a date range.-- Parameters:- start_date: Start date for query (ISO format or 'today', required)- end_date: End date for query (ISO format or 'today+7d', optional)- max_results: Maximum number of events to return (default: 10, max: 250)- calendar_id: Calendar ID (optional, default: 'primary')- single_events: Expand recurring events (default: True)- order_by: Sort order - 'startTime' or 'updated' (default: 'startTime')- """- start_time = time.time()-- try:- service = await _get_calendar_service(parameters, context)-- start_date = parameters.get('start_date', '')- end_date = parameters.get('end_date', '')- max_results = min(parameters.get('max_results', 10), 250)- calendar_id = parameters.get('calendar_id', 'primary')- single_events = parameters.get('single_events', True)- order_by = parameters.get('order_by', 'startTime')-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Parse date shortcuts- now = datetime.utcnow()- if start_date.lower() == 'today' or not start_date:- time_min = now.replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + 'Z'- else:- time_min = start_date if start_date.endswith('Z') else start_date + 'Z'-- if not end_date:- # Default to 7 days from now- time_max = (now + timedelta(days=7)).isoformat() + 'Z'- elif end_date.startswith('today+'):- days = int(end_date.replace('today+', '').replace('d', ''))- time_max = (now + timedelta(days=days)).isoformat() + 'Z'- else:- time_max = end_date if end_date.endswith('Z') else end_date + 'Z'-- def list_events():- return service.events().list(- calendarId=calendar_id,- timeMin=time_min,- timeMax=time_max,- maxResults=max_results,- singleEvents=single_events,- orderBy=order_by if single_events else None- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, list_events)-- events = result.get('items', [])- formatted_events = []- for event in events:- formatted_events.append({- "event_id": event.get('id'),- "title": event.get('summary', 'No Title'),- "start": event.get('start', {}).get('dateTime', event.get('start', {}).get('date')),- "end": event.get('end', {}).get('dateTime', event.get('end', {}).get('date')),- "description": event.get('description', ''),- "location": event.get('location', ''),- "status": event.get('status'),- "html_link": event.get('htmlLink'),- "attendees": [a.get('email') for a in event.get('attendees', [])],- })-- await _track_calendar_usage(node_id, 'list', len(formatted_events), workflow_id, session_id)-- return {- "success": True,- "result": {- "events": formatted_events,- "count": len(formatted_events),- "time_range": {"start": time_min, "end": time_max},- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Calendar list error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_calendar_update(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Update an existing calendar event.-- Parameters:- event_id: Event ID to update (required)- title: New event title (optional)- start_time: New start time (optional)- end_time: New end time (optional)- description: New description (optional)- location: New location (optional)- calendar_id: Calendar ID (optional, default: 'primary')- """- start_time = time.time()-- try:- service = await _get_calendar_service(parameters, context)-- event_id = parameters.get('event_id', '')- calendar_id = parameters.get('calendar_id', 'primary')-- if not event_id:- raise ValueError("Event ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # First, get the existing event- def get_event():- return service.events().get(- calendarId=calendar_id,- eventId=event_id- ).execute()-- loop = asyncio.get_event_loop()- event = await loop.run_in_executor(None, get_event)-- # Update fields- if parameters.get('title'):- event['summary'] = parameters['title']- if parameters.get('start_time'):- tz = event.get('start', {}).get('timeZone', 'UTC')- event['start'] = {'dateTime': parameters['start_time'], 'timeZone': tz}- if parameters.get('end_time'):- tz = event.get('end', {}).get('timeZone', 'UTC')- event['end'] = {'dateTime': parameters['end_time'], 'timeZone': tz}- if parameters.get('description') is not None:- event['description'] = parameters['description']- if parameters.get('location') is not None:- event['location'] = parameters['location']-- def update_event():- return service.events().update(- calendarId=calendar_id,- eventId=event_id,- body=event,- sendUpdates='all'- ).execute()-- result = await loop.run_in_executor(None, update_event)-- await _track_calendar_usage(node_id, 'update', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "event_id": result.get('id'),- "title": result.get('summary'),- "start": result.get('start', {}).get('dateTime'),- "end": result.get('end', {}).get('dateTime'),- "updated": result.get('updated'),- "html_link": result.get('htmlLink'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Calendar update error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_calendar_delete(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Delete a calendar event.-- Parameters:- event_id: Event ID to delete (required)- calendar_id: Calendar ID (optional, default: 'primary')- send_updates: Send cancellation emails ('all', 'none') (default: 'all')- """- start_time = time.time()-- try:- service = await _get_calendar_service(parameters, context)-- event_id = parameters.get('event_id', '')- calendar_id = parameters.get('calendar_id', 'primary')- send_updates = parameters.get('send_updates', 'all')-- if not event_id:- raise ValueError("Event ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def delete_event():- return service.events().delete(- calendarId=calendar_id,- eventId=event_id,- sendUpdates=send_updates- ).execute()-- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, delete_event)-- await _track_calendar_usage(node_id, 'delete', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "deleted": True,- "event_id": event_id,- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Calendar delete error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_calendar(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Calendar handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - create: Create calendar event- - list: List calendar events- - update: Update existing event- - delete: Delete event- """- operation = parameters.get('operation', 'create')-- # Map update_* parameters to standard names for update operation- if operation == 'update':- if parameters.get('update_title'):- parameters['title'] = parameters['update_title']- if parameters.get('update_start_time'):- parameters['start_time'] = parameters['update_start_time']- if parameters.get('update_end_time'):- parameters['end_time'] = parameters['update_end_time']- if parameters.get('update_description'):- parameters['description'] = parameters['update_description']- if parameters.get('update_location'):- parameters['location'] = parameters['update_location']-- if operation == 'create':- return await handle_calendar_create(node_id, node_type, parameters, context)- elif operation == 'list':- return await handle_calendar_list(node_id, node_type, parameters, context)- elif operation == 'update':- return await handle_calendar_update(node_id, node_type, parameters, context)- elif operation == 'delete':- return await handle_calendar_delete(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Calendar operation: {operation}. Supported: create, list, update, delete",- "execution_time": 0- }diff --git a/server/services/handlers/contacts.py b/server/services/handlers/contacts.pydeleted file mode 100644index e333fe78..00000000--- a/server/services/handlers/contacts.py+++ /dev/null@@ -1,537 +0,0 @@-"""Google Contacts (People API) node handlers using Google API Python client.--API Reference: https://developers.google.com/people/api/rest-"""--import asyncio-import time-from typing import Any, Dict--from googleapiclient.discovery import build--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_contacts_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Google Contacts (People API) usage for analytics.-- Note: People API is free but rate limited.- We track for analytics purposes with $0 cost.- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('google_contacts', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'google_contacts',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Contacts] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_people_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Google People (Contacts) service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("people", "v1", credentials=creds)-- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, build_service)---def _format_contact(person: Dict[str, Any]) -> Dict[str, Any]:- """Format a People API person resource to a simpler contact format."""- names = person.get('names', [{}])- emails = person.get('emailAddresses', [])- phones = person.get('phoneNumbers', [])- organizations = person.get('organizations', [])- person.get('addresses', [])- photos = person.get('photos', [])-- # Get primary values- primary_name = names[0] if names else {}- primary_email = next((e for e in emails if e.get('metadata', {}).get('primary')), emails[0] if emails else {})- primary_phone = next((p for p in phones if p.get('metadata', {}).get('primary')), phones[0] if phones else {})- primary_org = organizations[0] if organizations else {}- primary_photo = next((p for p in photos if p.get('metadata', {}).get('primary')), photos[0] if photos else {})-- return {- 'resource_name': person.get('resourceName'),- 'display_name': primary_name.get('displayName', ''),- 'given_name': primary_name.get('givenName', ''),- 'family_name': primary_name.get('familyName', ''),- 'email': primary_email.get('value', ''),- 'phone': primary_phone.get('value', ''),- 'company': primary_org.get('name', ''),- 'job_title': primary_org.get('title', ''),- 'photo_url': primary_photo.get('url', ''),- 'emails': [e.get('value') for e in emails],- 'phones': [p.get('value') for p in phones],- }---async def handle_contacts_create(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Create a new contact.-- Parameters:- first_name: First name (required)- last_name: Last name (optional)- email: Email address (optional)- phone: Phone number (optional)- company: Company/organization name (optional)- job_title: Job title (optional)- notes: Additional notes (optional)- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- first_name = parameters.get('first_name', '')- last_name = parameters.get('last_name', '')- email = parameters.get('email', '')- phone = parameters.get('phone', '')- company = parameters.get('company', '')- job_title = parameters.get('job_title', '')- notes = parameters.get('notes', '')-- if not first_name:- raise ValueError("First name is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Build contact body- contact_body = {- 'names': [{- 'givenName': first_name,- 'familyName': last_name,- }]- }-- if email:- contact_body['emailAddresses'] = [{'value': email}]-- if phone:- contact_body['phoneNumbers'] = [{'value': phone}]-- if company or job_title:- contact_body['organizations'] = [{- 'name': company,- 'title': job_title,- }]-- if notes:- contact_body['biographies'] = [{- 'value': notes,- 'contentType': 'TEXT_PLAIN',- }]-- def create_contact():- return service.people().createContact(body=contact_body).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, create_contact)-- await _track_contacts_usage(node_id, 'create', 1, workflow_id, session_id)-- return {- "success": True,- "result": _format_contact(result),- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts create error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_contacts_list(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """List contacts.-- Parameters:- page_size: Number of contacts to return (default: 100)- page_token: Token for pagination (optional)- sort_order: Sort order - 'LAST_MODIFIED_ASCENDING' or 'LAST_MODIFIED_DESCENDING' or 'FIRST_NAME_ASCENDING' or 'LAST_NAME_ASCENDING'- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- page_size = parameters.get('page_size', 100)- page_token = parameters.get('page_token', '')- sort_order = parameters.get('sort_order', 'LAST_MODIFIED_DESCENDING')-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def list_contacts():- request_params = {- 'resourceName': 'people/me',- 'pageSize': page_size,- 'personFields': 'names,emailAddresses,phoneNumbers,organizations,photos,biographies',- 'sortOrder': sort_order,- }- if page_token:- request_params['pageToken'] = page_token- return service.people().connections().list(**request_params).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, list_contacts)-- connections = result.get('connections', [])-- await _track_contacts_usage(node_id, 'list', len(connections), workflow_id, session_id)-- # Format contacts- contacts = [_format_contact(person) for person in connections]-- return {- "success": True,- "result": {- "contacts": contacts,- "count": len(contacts),- "total_people": result.get('totalPeople', 0),- "next_page_token": result.get('nextPageToken'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts list error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_contacts_search(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Search contacts by query.-- Parameters:- query: Search query (name, email, phone, etc.)- page_size: Number of results to return (default: 30)- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- query = parameters.get('query', '')- page_size = parameters.get('page_size', 30)-- if not query:- raise ValueError("Search query is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def search_contacts():- return service.people().searchContacts(- query=query,- pageSize=page_size,- readMask='names,emailAddresses,phoneNumbers,organizations,photos'- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, search_contacts)-- results = result.get('results', [])-- await _track_contacts_usage(node_id, 'search', len(results), workflow_id, session_id)-- # Format contacts from search results- contacts = []- for r in results:- person = r.get('person', {})- contacts.append(_format_contact(person))-- return {- "success": True,- "result": {- "contacts": contacts,- "count": len(contacts),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts search error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_contacts_get(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Get a specific contact by resource name.-- Parameters:- resource_name: Contact resource name (e.g., 'people/c12345678')- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- resource_name = parameters.get('resource_name', '')-- if not resource_name:- raise ValueError("Resource name is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def get_contact():- return service.people().get(- resourceName=resource_name,- personFields='names,emailAddresses,phoneNumbers,organizations,photos,biographies,addresses'- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, get_contact)-- await _track_contacts_usage(node_id, 'get', 1, workflow_id, session_id)-- return {- "success": True,- "result": _format_contact(result),- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts get error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_contacts_update(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Update an existing contact.-- Parameters:- resource_name: Contact resource name (required)- first_name: New first name (optional)- last_name: New last name (optional)- email: New email (optional)- phone: New phone (optional)- company: New company (optional)- job_title: New job title (optional)- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- resource_name = parameters.get('resource_name', '')-- if not resource_name:- raise ValueError("Resource name is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # First get the current contact to get etag- def get_contact():- return service.people().get(- resourceName=resource_name,- personFields='names,emailAddresses,phoneNumbers,organizations,metadata'- ).execute()-- loop = asyncio.get_event_loop()- current = await loop.run_in_executor(None, get_contact)-- # Build update body- update_body = {'etag': current.get('etag')}- update_person_fields = []-- if parameters.get('first_name') or parameters.get('last_name'):- update_body['names'] = [{- 'givenName': parameters.get('first_name', current.get('names', [{}])[0].get('givenName', '')),- 'familyName': parameters.get('last_name', current.get('names', [{}])[0].get('familyName', '')),- }]- update_person_fields.append('names')-- if parameters.get('email'):- update_body['emailAddresses'] = [{'value': parameters['email']}]- update_person_fields.append('emailAddresses')-- if parameters.get('phone'):- update_body['phoneNumbers'] = [{'value': parameters['phone']}]- update_person_fields.append('phoneNumbers')-- if parameters.get('company') or parameters.get('job_title'):- update_body['organizations'] = [{- 'name': parameters.get('company', ''),- 'title': parameters.get('job_title', ''),- }]- update_person_fields.append('organizations')-- if not update_person_fields:- raise ValueError("At least one field to update is required")-- def update_contact():- return service.people().updateContact(- resourceName=resource_name,- body=update_body,- updatePersonFields=','.join(update_person_fields)- ).execute()-- result = await loop.run_in_executor(None, update_contact)-- await _track_contacts_usage(node_id, 'update', 1, workflow_id, session_id)-- return {- "success": True,- "result": _format_contact(result),- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts update error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_contacts_delete(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Delete a contact.-- Parameters:- resource_name: Contact resource name (required)- """- start_time = time.time()-- try:- service = await _get_people_service(parameters, context)-- resource_name = parameters.get('resource_name', '')-- if not resource_name:- raise ValueError("Resource name is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def delete_contact():- return service.people().deleteContact(resourceName=resource_name).execute()-- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, delete_contact)-- await _track_contacts_usage(node_id, 'delete', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "deleted": True,- "resource_name": resource_name,- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Contacts delete error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_contacts(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Contacts handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - create: Create new contact- - list: List contacts- - search: Search contacts- - get: Get contact by resource name- - update: Update existing contact- - delete: Delete contact- """- operation = parameters.get('operation', 'create')-- # Map update_* parameters to standard names for update operation- if operation == 'update':- if parameters.get('update_first_name'):- parameters['first_name'] = parameters['update_first_name']- if parameters.get('update_last_name'):- parameters['last_name'] = parameters['update_last_name']- if parameters.get('update_email'):- parameters['email'] = parameters['update_email']- if parameters.get('update_phone'):- parameters['phone'] = parameters['update_phone']- if parameters.get('update_company'):- parameters['company'] = parameters['update_company']- if parameters.get('update_job_title'):- parameters['job_title'] = parameters['update_job_title']-- if operation == 'create':- return await handle_contacts_create(node_id, node_type, parameters, context)- elif operation == 'list':- return await handle_contacts_list(node_id, node_type, parameters, context)- elif operation == 'search':- return await handle_contacts_search(node_id, node_type, parameters, context)- elif operation == 'get':- return await handle_contacts_get(node_id, node_type, parameters, context)- elif operation == 'update':- return await handle_contacts_update(node_id, node_type, parameters, context)- elif operation == 'delete':- return await handle_contacts_delete(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Contacts operation: {operation}. Supported: create, list, search, get, update, delete",- "execution_time": 0- }diff --git a/server/services/handlers/drive.py b/server/services/handlers/drive.pydeleted file mode 100644index 1e12a1cf..00000000--- a/server/services/handlers/drive.py+++ /dev/null@@ -1,465 +0,0 @@-"""Google Drive node handlers using Google API Python client.--API Reference: https://developers.google.com/drive/api/v3/reference-"""--import asyncio-import io-import time-from typing import Any, Dict--import httpx-from googleapiclient.discovery import build-from googleapiclient.http import MediaIoBaseUpload, MediaIoBaseDownload--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_drive_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Google Drive API usage for analytics.-- Note: Drive API is free but rate limited (20K requests/100s).- We track for analytics purposes with $0 cost.- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('google_drive', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'google_drive',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Drive] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_drive_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Google Drive service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("drive", "v3", credentials=creds)-- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, build_service)---async def handle_drive_upload(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Upload a file to Google Drive.-- Parameters:- file_url: URL to download file from (for remote files)- file_content: Base64-encoded file content (for direct upload)- filename: Name for the uploaded file (required)- folder_id: Parent folder ID (optional, default: root)- mime_type: File MIME type (optional, auto-detected)- description: File description (optional)- """- start_time = time.time()-- try:- service = await _get_drive_service(parameters, context)-- file_url = parameters.get('file_url', '')- file_content = parameters.get('file_content', '')- filename = parameters.get('filename', '')- folder_id = parameters.get('folder_id', '')- mime_type = parameters.get('mime_type', 'application/octet-stream')- description = parameters.get('description', '')-- if not filename:- raise ValueError("Filename is required")- if not file_url and not file_content:- raise ValueError("Either file_url or file_content is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Build file metadata- file_metadata = {'name': filename}- if folder_id:- file_metadata['parents'] = [folder_id]- if description:- file_metadata['description'] = description-- # Get file content- if file_url:- # Download from URL- async with httpx.AsyncClient() as client:- response = await client.get(file_url, timeout=60.0)- response.raise_for_status()- file_bytes = response.content- # Try to detect mime type from response- if 'content-type' in response.headers and mime_type == 'application/octet-stream':- mime_type = response.headers['content-type'].split(';')[0]- else:- # Decode base64 content- import base64- file_bytes = base64.b64decode(file_content)-- # Create media upload- media = MediaIoBaseUpload(- io.BytesIO(file_bytes),- mimetype=mime_type,- resumable=True- )-- def upload_file():- return service.files().create(- body=file_metadata,- media_body=media,- fields='id, name, mimeType, size, webViewLink, webContentLink, createdTime'- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, upload_file)-- await _track_drive_usage(node_id, 'upload', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "file_id": result.get('id'),- "name": result.get('name'),- "mime_type": result.get('mimeType'),- "size": result.get('size'),- "web_link": result.get('webViewLink'),- "download_link": result.get('webContentLink'),- "created_time": result.get('createdTime'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Drive upload error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_drive_download(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Download a file from Google Drive.-- Parameters:- file_id: ID of the file to download (required)- output_format: 'base64' or 'url' (default: 'base64')- """- start_time = time.time()-- try:- service = await _get_drive_service(parameters, context)-- file_id = parameters.get('file_id', '')- output_format = parameters.get('output_format', 'base64')-- if not file_id:- raise ValueError("File ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Get file metadata first- def get_metadata():- return service.files().get(- fileId=file_id,- fields='id, name, mimeType, size, webViewLink, webContentLink'- ).execute()-- loop = asyncio.get_event_loop()- metadata = await loop.run_in_executor(None, get_metadata)-- if output_format == 'url':- # Just return the download link- await _track_drive_usage(node_id, 'download', 1, workflow_id, session_id)- return {- "success": True,- "result": {- "file_id": metadata.get('id'),- "name": metadata.get('name'),- "mime_type": metadata.get('mimeType'),- "size": metadata.get('size'),- "download_url": metadata.get('webContentLink'),- "web_link": metadata.get('webViewLink'),- },- "execution_time": time.time() - start_time- }-- # Download file content- def download_file():- request = service.files().get_media(fileId=file_id)- file_buffer = io.BytesIO()- downloader = MediaIoBaseDownload(file_buffer, request)- done = False- while not done:- _, done = downloader.next_chunk()- return file_buffer.getvalue()-- file_bytes = await loop.run_in_executor(None, download_file)-- # Encode as base64- import base64- file_base64 = base64.b64encode(file_bytes).decode('utf-8')-- await _track_drive_usage(node_id, 'download', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "file_id": metadata.get('id'),- "name": metadata.get('name'),- "mime_type": metadata.get('mimeType'),- "size": len(file_bytes),- "content_base64": file_base64,- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Drive download error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_drive_list(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """List files in Google Drive.-- Parameters:- folder_id: Folder ID to list (optional, default: root)- query: Search query using Drive query syntax (optional)- max_results: Maximum number of files (default: 20, max: 1000)- file_types: Filter by file type - 'all', 'folder', 'document', 'spreadsheet', 'image' (optional)- order_by: Sort order - 'name', 'modifiedTime', 'createdTime' (default: 'modifiedTime desc')- """- start_time = time.time()-- try:- service = await _get_drive_service(parameters, context)-- folder_id = parameters.get('folder_id', '')- query = parameters.get('query', '')- max_results = min(parameters.get('max_results', 20), 1000)- file_types = parameters.get('file_types', 'all')- order_by = parameters.get('order_by', 'modifiedTime desc')-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Build query- query_parts = []-- if folder_id:- query_parts.append(f"'{folder_id}' in parents")-- if query:- query_parts.append(query)-- # File type filters- if file_types == 'folder':- query_parts.append("mimeType = 'application/vnd.google-apps.folder'")- elif file_types == 'document':- query_parts.append("mimeType = 'application/vnd.google-apps.document'")- elif file_types == 'spreadsheet':- query_parts.append("mimeType = 'application/vnd.google-apps.spreadsheet'")- elif file_types == 'image':- query_parts.append("mimeType contains 'image/'")-- # Don't list trashed files- query_parts.append("trashed = false")-- full_query = ' and '.join(query_parts) if query_parts else None-- def list_files():- params = {- 'pageSize': max_results,- 'fields': 'nextPageToken, files(id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime, parents, owners)',- 'orderBy': order_by- }- if full_query:- params['q'] = full_query- return service.files().list(**params).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, list_files)-- files = result.get('files', [])- formatted_files = []- for f in files:- formatted_files.append({- "file_id": f.get('id'),- "name": f.get('name'),- "mime_type": f.get('mimeType'),- "size": f.get('size'),- "web_link": f.get('webViewLink'),- "download_link": f.get('webContentLink'),- "created_time": f.get('createdTime'),- "modified_time": f.get('modifiedTime'),- "parent_ids": f.get('parents', []),- "owner": f.get('owners', [{}])[0].get('emailAddress') if f.get('owners') else None,- })-- await _track_drive_usage(node_id, 'list', len(formatted_files), workflow_id, session_id)-- return {- "success": True,- "result": {- "files": formatted_files,- "count": len(formatted_files),- "next_page_token": result.get('nextPageToken'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Drive list error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_drive_share(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Share a file with another user.-- Parameters:- file_id: ID of the file to share (required)- email: Email address to share with (required)- role: Permission role - 'reader', 'writer', 'commenter' (default: 'reader')- send_notification: Send email notification (default: True)- message: Custom message for notification (optional)- """- start_time = time.time()-- try:- service = await _get_drive_service(parameters, context)-- file_id = parameters.get('file_id', '')- email = parameters.get('email', '')- role = parameters.get('role', 'reader')- send_notification = parameters.get('send_notification', True)- message = parameters.get('message', '')-- if not file_id:- raise ValueError("File ID is required")- if not email:- raise ValueError("Email address is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- permission = {- 'type': 'user',- 'role': role,- 'emailAddress': email- }-- def create_permission():- return service.permissions().create(- fileId=file_id,- body=permission,- sendNotificationEmail=send_notification,- emailMessage=message if message else None,- fields='id, type, role, emailAddress'- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, create_permission)-- # Get updated file info- def get_file():- return service.files().get(- fileId=file_id,- fields='id, name, webViewLink'- ).execute()-- file_info = await loop.run_in_executor(None, get_file)-- await _track_drive_usage(node_id, 'share', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "permission_id": result.get('id'),- "file_id": file_id,- "file_name": file_info.get('name'),- "shared_with": email,- "role": role,- "web_link": file_info.get('webViewLink'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Drive share error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_drive(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Drive handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - upload: Upload file to Drive- - download: Download file from Drive- - list: List files in Drive- - share: Share file with user- """- operation = parameters.get('operation', 'upload')-- if operation == 'upload':- return await handle_drive_upload(node_id, node_type, parameters, context)- elif operation == 'download':- return await handle_drive_download(node_id, node_type, parameters, context)- elif operation == 'list':- return await handle_drive_list(node_id, node_type, parameters, context)- elif operation == 'share':- return await handle_drive_share(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Drive operation: {operation}. Supported: upload, download, list, share",- "execution_time": 0- }diff --git a/server/services/handlers/gmail.py b/server/services/handlers/gmail.pydeleted file mode 100644index 9ba9755c..00000000--- a/server/services/handlers/gmail.py+++ /dev/null@@ -1,589 +0,0 @@-"""Gmail node handlers using Google API Python client."""--import asyncio-import base64-import time-from datetime import datetime-from email.mime.text import MIMEText-from email.mime.multipart import MIMEMultipart-from typing import Dict, Any, Set--from googleapiclient.discovery import build--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_gmail_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Gmail API usage for analytics.-- Note: Gmail API is free but rate limited (250 quota units/user/second).- We track for analytics purposes with $0 cost.-- Args:- node_id: The node executing the Gmail action- action: Action name matching operation_map keys (send, search, read, etc.)- resource_count: Number of resources processed- workflow_id: Optional workflow context- session_id: Session for aggregation-- Returns:- Cost breakdown dict (always 0 for Gmail)- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('gmail', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'gmail',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Gmail] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_gmail_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Gmail service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("gmail", "v1", credentials=creds)-- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, build_service)---async def handle_gmail_send(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Gmail send operations.-- Parameters:- to: Recipient email address(es), comma-separated- cc: CC recipients (optional)- bcc: BCC recipients (optional)- subject: Email subject- body: Email body content- body_type: 'text' or 'html' (default: 'text')- """- start_time = time.time()-- try:- service = await _get_gmail_service(parameters, context)-- to = parameters.get('to', '')- cc = parameters.get('cc', '')- bcc = parameters.get('bcc', '')- subject = parameters.get('subject', '')- body = parameters.get('body', '')- body_type = parameters.get('body_type', 'text')-- if not to:- raise ValueError("Recipient email address (to) is required")- if not subject:- raise ValueError("Email subject is required")- if not body:- raise ValueError("Email body is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- if body_type == 'html':- message = MIMEMultipart('alternative')- message.attach(MIMEText(body, 'html'))- else:- message = MIMEText(body, 'plain')-- message['to'] = to- message['subject'] = subject- if cc:- message['cc'] = cc- if bcc:- message['bcc'] = bcc-- raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')-- def send_message():- return service.users().messages().send(- userId='me',- body={'raw': raw_message}- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, send_message)-- await _track_gmail_usage(node_id, 'send', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "message_id": result.get('id'),- "thread_id": result.get('threadId'),- "label_ids": result.get('labelIds', []),- "to": to,- "subject": subject,- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Gmail send error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_gmail_search(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Gmail search operations.-- Parameters:- query: Gmail search query (same syntax as Gmail web)- max_results: Maximum number of messages to return (default: 10, max: 100)- include_body: Whether to fetch full message body (default: False)- """- start_time = time.time()-- try:- service = await _get_gmail_service(parameters, context)-- query = parameters.get('query', '')- max_results = min(parameters.get('max_results', 10), 100)- include_body = parameters.get('include_body', False)-- if not query:- raise ValueError("Search query is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def search_messages():- return service.users().messages().list(- userId='me',- q=query,- maxResults=max_results- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, search_messages)-- messages = result.get('messages', [])- formatted_messages = []-- for msg in messages:- msg_id = msg.get('id')-- def get_message(message_id):- format_type = 'full' if include_body else 'metadata'- return service.users().messages().get(- userId='me',- id=message_id,- format=format_type,- metadataHeaders=['From', 'To', 'Subject', 'Date']- ).execute()-- msg_detail = await loop.run_in_executor(None, lambda mid=msg_id: get_message(mid))- formatted_messages.append(_format_message(msg_detail, include_body))-- await _track_gmail_usage(node_id, 'search', len(formatted_messages), workflow_id, session_id)-- return {- "success": True,- "result": {- "messages": formatted_messages,- "count": len(formatted_messages),- "query": query,- "result_size_estimate": result.get('resultSizeEstimate', 0),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Gmail search error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_gmail_read(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Gmail read operations - read a specific message by ID.-- Parameters:- message_id: The Gmail message ID to read- format: 'full', 'minimal', 'raw', or 'metadata' (default: 'full')- """- start_time = time.time()-- try:- service = await _get_gmail_service(parameters, context)-- message_id = parameters.get('message_id', '')- format_type = parameters.get('format', 'full')-- if not message_id:- raise ValueError("message_id is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def get_message():- return service.users().messages().get(- userId='me',- id=message_id,- format=format_type- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, get_message)-- await _track_gmail_usage(node_id, 'read', 1, workflow_id, session_id)-- return {- "success": True,- "result": _format_message(result, include_body=(format_type == 'full')),- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Gmail read error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---def _format_message(message: Dict[str, Any], include_body: bool = False) -> Dict[str, Any]:- """Format Gmail message to a cleaner structure."""- headers = {}- payload = message.get('payload', {})-- for header in payload.get('headers', []):- name = header.get('name', '').lower()- value = header.get('value', '')- if name in ['from', 'to', 'subject', 'date', 'cc', 'bcc']:- headers[name] = value-- formatted = {- "message_id": message.get('id'),- "thread_id": message.get('threadId'),- "from": headers.get('from', ''),- "to": headers.get('to', ''),- "cc": headers.get('cc', ''),- "subject": headers.get('subject', ''),- "date": headers.get('date', ''),- "snippet": message.get('snippet', ''),- "labels": message.get('labelIds', []),- "size_estimate": message.get('sizeEstimate', 0),- }-- if include_body:- body = _extract_body(payload)- formatted['body'] = body-- attachments = _extract_attachments(payload)- if attachments:- formatted['attachments'] = attachments-- return formatted---def _extract_body(payload: Dict[str, Any]) -> str:- """Extract email body from payload, handling multipart messages."""- body = ""-- if 'body' in payload and payload['body'].get('data'):- body = base64.urlsafe_b64decode(payload['body']['data']).decode('utf-8', errors='ignore')- return body-- parts = payload.get('parts', [])- for part in parts:- mime_type = part.get('mimeType', '')-- if mime_type == 'text/plain':- if part.get('body', {}).get('data'):- body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8', errors='ignore')- break- elif mime_type == 'text/html' and not body:- if part.get('body', {}).get('data'):- body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8', errors='ignore')- elif mime_type.startswith('multipart/'):- nested_body = _extract_body(part)- if nested_body:- body = nested_body- break-- return body---def _extract_attachments(payload: Dict[str, Any]) -> list:- """Extract attachment information from payload."""- attachments = []- parts = payload.get('parts', [])-- for part in parts:- filename = part.get('filename', '')- if filename:- attachments.append({- "filename": filename,- "mime_type": part.get('mimeType', ''),- "size": part.get('body', {}).get('size', 0),- "attachment_id": part.get('body', {}).get('attachmentId', ''),- })-- if part.get('parts'):- nested = _extract_attachments(part)- attachments.extend(nested)-- return attachments---# ============================================================================-# GMAIL RECEIVE - Polling-based trigger-# ============================================================================--async def _poll_gmail_ids(service, query: str, max_results: int = 20) -> Set[str]:- """Poll Gmail API for message IDs matching query.-- Args:- service: Authenticated Gmail API service- query: Gmail search query string- max_results: Maximum messages to fetch-- Returns:- Set of message IDs- """- def list_messages():- return service.users().messages().list(- userId='me',- q=query,- maxResults=max_results- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, list_messages)- messages = result.get('messages', [])- return {m.get('id') for m in messages if m.get('id')}---async def _fetch_email_details(service, message_id: str) -> Dict[str, Any]:- """Fetch full email details for a message ID.-- Args:- service: Authenticated Gmail API service- message_id: Gmail message ID-- Returns:- Formatted email data dict- """- def get_message():- return service.users().messages().get(- userId='me',- id=message_id,- format='full',- metadataHeaders=['From', 'To', 'Subject', 'Date', 'Cc', 'Bcc']- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, get_message)- return _format_message(result, include_body=True)---async def _mark_email_as_read(service, message_id: str) -> None:- """Mark email as read by removing UNREAD label.-- Args:- service: Authenticated Gmail API service- message_id: Gmail message ID- """- def modify_message():- return service.users().messages().modify(- userId='me',- id=message_id,- body={'removeLabelIds': ['UNREAD']}- ).execute()-- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, modify_message)---async def handle_gmail_receive(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Gmail Receive trigger - polls Gmail API for new emails.-- Unlike push-based triggers (WhatsApp, Webhook), Gmail requires polling.- This handler:- 1. Authenticates with Gmail API using stored OAuth tokens- 2. Establishes a baseline of existing email IDs- 3. Polls at the configured interval for new emails- 4. Returns when a new email is found matching the filter- 5. Dispatches event via event_waiter for deployment mode listeners-- Parameters:- filter_query: Gmail search query (default: 'is:unread')- label_filter: Label to filter by (default: 'INBOX')- mark_as_read: Mark processed emails as read (default: False)- poll_interval: Seconds between polls (default: 60, range: 30-3600)- """- from services.status_broadcaster import get_status_broadcaster- start_time = time.time()-- try:- service = await _get_gmail_service(parameters, context)-- poll_interval = max(10, min(3600, parameters.get('poll_interval', 60)))- filter_query = parameters.get('filter_query', 'is:unread')- label_filter = parameters.get('label_filter', 'INBOX')- mark_as_read = parameters.get('mark_as_read', False)-- # Build Gmail query with label filter- query = filter_query- if label_filter and label_filter != 'all':- query = f"label:{label_filter} {query}"-- # Broadcast waiting status- broadcaster = get_status_broadcaster()- workflow_id = context.get('workflow_id')- await broadcaster.update_node_status(node_id, "waiting", {- "message": f"Waiting for Gmail email (polling every {poll_interval}s)...",- "event_type": "gmail_email_received",- }, workflow_id=workflow_id)-- # Get current email IDs to establish baseline (avoid triggering on existing emails)- seen_ids: Set[str] = set()- try:- baseline = await _poll_gmail_ids(service, query)- seen_ids.update(baseline)- logger.info(f"[GmailReceive] Baseline: {len(seen_ids)} existing emails for query '{query}'")- except Exception as e:- logger.warning(f"[GmailReceive] Baseline fetch failed (will treat all as new): {e}")-- # Poll loop - check for new emails at configured interval- while True:- await asyncio.sleep(poll_interval)-- try:- current_ids = await _poll_gmail_ids(service, query)- new_ids = current_ids - seen_ids-- if new_ids:- # Found new email(s) - process the first one- newest_id = next(iter(new_ids))- seen_ids.update(new_ids)-- # Fetch full message details- email_data = await _fetch_email_details(service, newest_id)-- # Mark as read if configured- if mark_as_read:- try:- await _mark_email_as_read(service, newest_id)- except Exception as e:- logger.warning(f"[GmailReceive] Failed to mark as read: {e}")-- # Track usage- session_id = context.get('session_id', 'default')- await _track_gmail_usage(node_id, 'receive', 1, workflow_id, session_id)-- # Also dispatch event for deployment mode listeners- from services import event_waiter- event_waiter.dispatch('gmail_email_received', email_data)-- logger.info(f"[GmailReceive] New email found: {email_data.get('subject', 'no subject')}")-- return {- "success": True,- "node_id": node_id,- "node_type": node_type,- "result": email_data,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except asyncio.CancelledError:- raise # Re-raise to outer handler- except Exception as e:- logger.error(f"[GmailReceive] Poll error (will retry): {e}")-- except asyncio.CancelledError:- logger.info(f"[GmailReceive] Cancelled by user: node_id={node_id}")- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "Cancelled by user",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- except Exception as e:- logger.error(f"[GmailReceive] Error: {e}")- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_gmail(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Gmail handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - send: Send email- - search: Search emails- - read: Read specific email by ID- """- operation = parameters.get('operation', 'send')-- if operation == 'send':- return await handle_gmail_send(node_id, node_type, parameters, context)- elif operation == 'search':- return await handle_gmail_search(node_id, node_type, parameters, context)- elif operation == 'read':- return await handle_gmail_read(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Gmail operation: {operation}. Supported: send, search, read",- "execution_time": 0- }diff --git a/server/services/handlers/sheets.py b/server/services/handlers/sheets.pydeleted file mode 100644index cb471bfe..00000000--- a/server/services/handlers/sheets.py+++ /dev/null@@ -1,314 +0,0 @@-"""Google Sheets node handlers using Google API Python client.--API Reference: https://developers.google.com/workspace/sheets/api/reference/rest-"""--import asyncio-import time-from typing import Any, Dict--from googleapiclient.discovery import build--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_sheets_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Google Sheets API usage for analytics.-- Note: Sheets API is free but rate limited (300 requests/min).- We track for analytics purposes with $0 cost.- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('google_sheets', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'google_sheets',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Sheets] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_sheets_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Google Sheets service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("sheets", "v4", credentials=creds)-- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, build_service)---async def handle_sheets_read(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Read data from a Google Sheets spreadsheet.-- Parameters:- spreadsheet_id: ID of the spreadsheet (required)- range: A1 notation range (e.g., "Sheet1!A1:D10") (required)- value_render_option: How values should be rendered ('FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA')- major_dimension: Rows or columns first ('ROWS', 'COLUMNS')- """- start_time = time.time()-- try:- service = await _get_sheets_service(parameters, context)-- spreadsheet_id = parameters.get('spreadsheet_id', '')- range_notation = parameters.get('range', '')- value_render = parameters.get('value_render_option', 'FORMATTED_VALUE')- major_dimension = parameters.get('major_dimension', 'ROWS')-- if not spreadsheet_id:- raise ValueError("Spreadsheet ID is required")- if not range_notation:- raise ValueError("Range is required (e.g., 'Sheet1!A1:D10')")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def read_values():- return service.spreadsheets().values().get(- spreadsheetId=spreadsheet_id,- range=range_notation,- valueRenderOption=value_render,- majorDimension=major_dimension- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, read_values)-- values = result.get('values', [])-- await _track_sheets_usage(node_id, 'read', len(values), workflow_id, session_id)-- return {- "success": True,- "result": {- "values": values,- "range": result.get('range'),- "rows": len(values),- "columns": len(values[0]) if values else 0,- "major_dimension": result.get('majorDimension'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Sheets read error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_sheets_write(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Write data to a Google Sheets spreadsheet.-- Parameters:- spreadsheet_id: ID of the spreadsheet (required)- range: A1 notation range (e.g., "Sheet1!A1") (required)- values: 2D array of values to write (required)- value_input_option: How input values should be interpreted ('RAW', 'USER_ENTERED')- """- start_time = time.time()-- try:- service = await _get_sheets_service(parameters, context)-- spreadsheet_id = parameters.get('spreadsheet_id', '')- range_notation = parameters.get('range', '')- values = parameters.get('values', [])- value_input = parameters.get('value_input_option', 'USER_ENTERED')-- if not spreadsheet_id:- raise ValueError("Spreadsheet ID is required")- if not range_notation:- raise ValueError("Range is required (e.g., 'Sheet1!A1')")- if not values:- raise ValueError("Values are required")-- # Parse values if string (JSON format)- if isinstance(values, str):- import json- values = json.loads(values)-- # Ensure values is a 2D array- if values and not isinstance(values[0], list):- values = [values]-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- body = {'values': values}-- def write_values():- return service.spreadsheets().values().update(- spreadsheetId=spreadsheet_id,- range=range_notation,- valueInputOption=value_input,- body=body- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, write_values)-- await _track_sheets_usage(node_id, 'write', result.get('updatedCells', 0), workflow_id, session_id)-- return {- "success": True,- "result": {- "updated_range": result.get('updatedRange'),- "updated_rows": result.get('updatedRows'),- "updated_columns": result.get('updatedColumns'),- "updated_cells": result.get('updatedCells'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Sheets write error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_sheets_append(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Append rows to a Google Sheets spreadsheet.-- Parameters:- spreadsheet_id: ID of the spreadsheet (required)- range: A1 notation range (e.g., "Sheet1!A:D") (required)- values: 2D array of values to append (required)- value_input_option: How input values should be interpreted ('RAW', 'USER_ENTERED')- insert_data_option: How the input data should be inserted ('OVERWRITE', 'INSERT_ROWS')- """- start_time = time.time()-- try:- service = await _get_sheets_service(parameters, context)-- spreadsheet_id = parameters.get('spreadsheet_id', '')- range_notation = parameters.get('range', '')- values = parameters.get('values', [])- value_input = parameters.get('value_input_option', 'USER_ENTERED')- insert_option = parameters.get('insert_data_option', 'INSERT_ROWS')-- if not spreadsheet_id:- raise ValueError("Spreadsheet ID is required")- if not range_notation:- raise ValueError("Range is required (e.g., 'Sheet1!A:D')")- if not values:- raise ValueError("Values are required")-- # Parse values if string (JSON format)- if isinstance(values, str):- import json- values = json.loads(values)-- # Ensure values is a 2D array- if values and not isinstance(values[0], list):- values = [values]-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- body = {'values': values}-- def append_values():- return service.spreadsheets().values().append(- spreadsheetId=spreadsheet_id,- range=range_notation,- valueInputOption=value_input,- insertDataOption=insert_option,- body=body- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, append_values)-- updates = result.get('updates', {})-- await _track_sheets_usage(node_id, 'append', updates.get('updatedCells', 0), workflow_id, session_id)-- return {- "success": True,- "result": {- "updated_range": updates.get('updatedRange'),- "updated_rows": updates.get('updatedRows'),- "updated_columns": updates.get('updatedColumns'),- "updated_cells": updates.get('updatedCells'),- "table_range": result.get('tableRange'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Sheets append error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_sheets(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Sheets handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - read: Read data from spreadsheet- - write: Write data to spreadsheet- - append: Append rows to spreadsheet- """- operation = parameters.get('operation', 'read')-- if operation == 'read':- return await handle_sheets_read(node_id, node_type, parameters, context)- elif operation == 'write':- return await handle_sheets_write(node_id, node_type, parameters, context)- elif operation == 'append':- return await handle_sheets_append(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Sheets operation: {operation}. Supported: read, write, append",- "execution_time": 0- }diff --git a/server/services/handlers/tasks.py b/server/services/handlers/tasks.pydeleted file mode 100644index 2de94a35..00000000--- a/server/services/handlers/tasks.py+++ /dev/null@@ -1,452 +0,0 @@-"""Google Tasks node handlers using Google API Python client.--API Reference: https://developers.google.com/workspace/tasks/reference/rest-"""--import asyncio-import time-from typing import Any, Dict--from googleapiclient.discovery import build--from core.logging import get_logger-from services.handlers.google_auth import get_google_credentials-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_tasks_usage(- node_id: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track Google Tasks API usage for analytics.-- Note: Tasks API is free but rate limited.- We track for analytics purposes with $0 cost.- """- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost('google_tasks', action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': 'google_tasks',- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Tasks] Tracked usage: {action} x{resource_count}")- return cost_data---async def _get_tasks_service(- parameters: Dict[str, Any],- context: Dict[str, Any]-):- """Get authenticated Google Tasks service."""- creds = await get_google_credentials(parameters, context)-- def build_service():- return build("tasks", "v1", credentials=creds)-- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, build_service)---async def handle_tasks_create(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Create a new task.-- Parameters:- title: Task title (required)- notes: Task notes/description (optional)- due_date: Due date in RFC 3339 format (optional)- tasklist_id: Task list ID (default: @default)- """- start_time = time.time()-- try:- service = await _get_tasks_service(parameters, context)-- title = parameters.get('title', '')- notes = parameters.get('notes', '')- due_date = parameters.get('due_date', '')- tasklist_id = parameters.get('tasklist_id', '@default')-- if not title:- raise ValueError("Task title is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- task_body = {- 'title': title,- }-- if notes:- task_body['notes'] = notes-- if due_date:- # Ensure RFC 3339 format (add time if only date provided)- if 'T' not in due_date:- due_date = f"{due_date}T00:00:00.000Z"- task_body['due'] = due_date-- def create_task():- return service.tasks().insert(- tasklist=tasklist_id,- body=task_body- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, create_task)-- await _track_tasks_usage(node_id, 'create', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "task_id": result.get('id'),- "title": result.get('title'),- "notes": result.get('notes'),- "due": result.get('due'),- "status": result.get('status'),- "self_link": result.get('selfLink'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Tasks create error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_tasks_list(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """List tasks from a task list.-- Parameters:- tasklist_id: Task list ID (default: @default)- show_completed: Include completed tasks (default: false)- show_hidden: Include hidden tasks (default: false)- max_results: Maximum number of tasks (default: 100)- """- start_time = time.time()-- try:- service = await _get_tasks_service(parameters, context)-- tasklist_id = parameters.get('tasklist_id', '@default')- show_completed = parameters.get('show_completed', False)- show_hidden = parameters.get('show_hidden', False)- max_results = parameters.get('max_results', 100)-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def list_tasks():- return service.tasks().list(- tasklist=tasklist_id,- showCompleted=show_completed,- showHidden=show_hidden,- maxResults=max_results- ).execute()-- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, list_tasks)-- tasks = result.get('items', [])-- await _track_tasks_usage(node_id, 'list', len(tasks), workflow_id, session_id)-- # Format tasks for output- formatted_tasks = []- for task in tasks:- formatted_tasks.append({- 'task_id': task.get('id'),- 'title': task.get('title'),- 'notes': task.get('notes'),- 'due': task.get('due'),- 'status': task.get('status'),- 'completed': task.get('completed'),- 'position': task.get('position'),- })-- return {- "success": True,- "result": {- "tasks": formatted_tasks,- "count": len(formatted_tasks),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Tasks list error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_tasks_complete(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Mark a task as completed.-- Parameters:- task_id: Task ID (required)- tasklist_id: Task list ID (default: @default)- """- start_time = time.time()-- try:- service = await _get_tasks_service(parameters, context)-- task_id = parameters.get('task_id', '')- tasklist_id = parameters.get('tasklist_id', '@default')-- if not task_id:- raise ValueError("Task ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # First get the task to preserve its data- def get_task():- return service.tasks().get(- tasklist=tasklist_id,- task=task_id- ).execute()-- loop = asyncio.get_event_loop()- task = await loop.run_in_executor(None, get_task)-- # Mark as completed- task['status'] = 'completed'-- def update_task():- return service.tasks().update(- tasklist=tasklist_id,- task=task_id,- body=task- ).execute()-- result = await loop.run_in_executor(None, update_task)-- await _track_tasks_usage(node_id, 'complete', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "task_id": result.get('id'),- "title": result.get('title'),- "status": result.get('status'),- "completed": result.get('completed'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Tasks complete error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_tasks_update(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Update an existing task.-- Parameters:- task_id: Task ID (required)- tasklist_id: Task list ID (default: @default)- title: New title (optional)- notes: New notes (optional)- due_date: New due date (optional)- status: New status - 'needsAction' or 'completed' (optional)- """- start_time = time.time()-- try:- service = await _get_tasks_service(parameters, context)-- task_id = parameters.get('task_id', '')- tasklist_id = parameters.get('tasklist_id', '@default')-- if not task_id:- raise ValueError("Task ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- # Get current task- def get_task():- return service.tasks().get(- tasklist=tasklist_id,- task=task_id- ).execute()-- loop = asyncio.get_event_loop()- task = await loop.run_in_executor(None, get_task)-- # Update fields if provided- if parameters.get('title'):- task['title'] = parameters['title']- if parameters.get('notes'):- task['notes'] = parameters['notes']- if parameters.get('due_date'):- due_date = parameters['due_date']- if 'T' not in due_date:- due_date = f"{due_date}T00:00:00.000Z"- task['due'] = due_date- if parameters.get('status'):- task['status'] = parameters['status']-- def update_task():- return service.tasks().update(- tasklist=tasklist_id,- task=task_id,- body=task- ).execute()-- result = await loop.run_in_executor(None, update_task)-- await _track_tasks_usage(node_id, 'update', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "task_id": result.get('id'),- "title": result.get('title'),- "notes": result.get('notes'),- "due": result.get('due'),- "status": result.get('status'),- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Tasks update error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---async def handle_tasks_delete(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Delete a task.-- Parameters:- task_id: Task ID (required)- tasklist_id: Task list ID (default: @default)- """- start_time = time.time()-- try:- service = await _get_tasks_service(parameters, context)-- task_id = parameters.get('task_id', '')- tasklist_id = parameters.get('tasklist_id', '@default')-- if not task_id:- raise ValueError("Task ID is required")-- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')-- def delete_task():- return service.tasks().delete(- tasklist=tasklist_id,- task=task_id- ).execute()-- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, delete_task)-- await _track_tasks_usage(node_id, 'delete', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "deleted": True,- "task_id": task_id,- },- "execution_time": time.time() - start_time- }-- except Exception as e:- logger.error(f"Tasks delete error: {e}")- return {"success": False, "error": str(e), "execution_time": time.time() - start_time}---# ============================================================================-# CONSOLIDATED DISPATCHER-# ============================================================================--async def handle_google_tasks(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Consolidated Tasks handler with operation dispatcher.-- Routes to appropriate handler based on 'operation' parameter:- - create: Create new task- - list: List tasks- - complete: Mark task as complete- - update: Update existing task- - delete: Delete task- """- operation = parameters.get('operation', 'create')-- # Map update_* parameters to standard names for update operation- if operation == 'update':- if parameters.get('update_title'):- parameters['title'] = parameters['update_title']- if parameters.get('update_notes'):- parameters['notes'] = parameters['update_notes']- if parameters.get('update_due_date'):- parameters['due_date'] = parameters['update_due_date']- if parameters.get('update_status'):- parameters['status'] = parameters['update_status']-- if operation == 'create':- return await handle_tasks_create(node_id, node_type, parameters, context)- elif operation == 'list':- return await handle_tasks_list(node_id, node_type, parameters, context)- elif operation == 'complete':- return await handle_tasks_complete(node_id, node_type, parameters, context)- elif operation == 'update':- return await handle_tasks_update(node_id, node_type, parameters, context)- elif operation == 'delete':- return await handle_tasks_delete(node_id, node_type, parameters, context)- else:- return {- "success": False,- "error": f"Unknown Tasks operation: {operation}. Supported: create, list, complete, update, delete",- "execution_time": 0- }diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 94df0095..9779d52d 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -1269,78 +1269,9 @@ async def _execute_twitter_user(args: Dict[str, Any],# through the plugin fast-path (nodes/google/gmail.py).-# ============================================================================-# GOOGLE WORKSPACE CONSOLIDATED TOOL HANDLERS-# ============================================================================--async def _execute_google_calendar(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Calendar operations via consolidated dispatcher."""- from services.handlers.calendar import handle_google_calendar-- parameters = {**node_params, **args}- return await handle_google_calendar(- node_id="tool_google_calendar",- node_type="calendar",- parameters=parameters,- context={}- )---async def _execute_google_drive(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Drive operations via consolidated dispatcher."""- from services.handlers.drive import handle_google_drive-- parameters = {**node_params, **args}- return await handle_google_drive(- node_id="tool_google_drive",- node_type="drive",- parameters=parameters,- context={}- )---async def _execute_google_sheets(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Sheets operations via consolidated dispatcher."""- from services.handlers.sheets import handle_google_sheets-- parameters = {**node_params, **args}- return await handle_google_sheets(- node_id="tool_google_sheets",- node_type="sheets",- parameters=parameters,- context={}- )---async def _execute_google_tasks(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Tasks operations via consolidated dispatcher."""- from services.handlers.tasks import handle_google_tasks-- parameters = {**node_params, **args}- return await handle_google_tasks(- node_id="tool_google_tasks",- node_type="tasks",- parameters=parameters,- context={}- )---async def _execute_google_contacts(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Contacts operations via consolidated dispatcher."""- from services.handlers.contacts import handle_google_contacts-- parameters = {**node_params, **args}- return await handle_google_contacts(- node_id="tool_google_contacts",- node_type="contacts",- parameters=parameters,- context={}- )+# Wave 11.D.4: _execute_google_{calendar,drive,sheets,tasks,contacts} deleted.+# Google Workspace tool execution now routes through the plugin fast-path+# (nodes/google/*.py). These functions were defined but unreferenced.async def _execute_apify_actor(args: Dict[str, Any],