Skip to content

Self-improving AI Employees for everyone

feat: Add full Google Workspace integration (Gmail, Calendar, Drive, Sheets, Tasks, Contacts)

trohitgcd899000c46d
diff --git a/CLAUDE.md b/CLAUDE.md
index 27dcb944..da87aec1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,6 +26,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Scripts Reference](./docs-internal/SCRIPTS.md)** | Available npm/shell scripts and their usage |
| **[Server Documentation](./docs-internal/server-readme.md)** | Python backend architecture and API documentation |
| **[Skill Creation Guide](./server/skills/GUIDE.md)** | How to create new skills (folder structure, SKILL.md format, metadata, supporting files) |
+| **[New Service Integration](./docs-internal/new_service_integration.md)** | Complete guide for integrating external services (OAuth, database, handlers, nodes, AI tools) - use Google Workspace as reference |
| **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |
## Design Principles & Standards
@@ -359,7 +360,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **84 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 11 skills + 3 dedicated tools + 6 dual-purpose tools + 16 Android + 3 WhatsApp + 4 Twitter + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow)
+- **104 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 11 skills + 3 dedicated tools + 6 dual-purpose tools + 16 Android + 3 WhatsApp + 4 Twitter + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow + 26 Google Workspace)
- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (87 message handlers)
- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated
@@ -388,6 +389,12 @@ The project was completely refactored from schema-based node definitions to expl
- `src/nodeDefinitions/toolNodes.ts` - AI Agent tool nodes (calculatorTool, currentTimeTool, webSearchTool)
- `src/nodeDefinitions/androidServiceNodes.ts` - 16 Android service nodes (monitoring, apps, automation, sensors, media)
- `src/nodeDefinitions/locationNodes.ts` - Google Maps and location services
+- `src/nodeDefinitions/gmailNodes.ts` - Gmail integration (4 nodes)
+- `src/nodeDefinitions/calendarNodes.ts` - Google Calendar integration (4 nodes)
+- `src/nodeDefinitions/driveNodes.ts` - Google Drive integration (4 nodes)
+- `src/nodeDefinitions/sheetsNodes.ts` - Google Sheets integration (3 nodes)
+- `src/nodeDefinitions/tasksNodes.ts` - Google Tasks integration (5 nodes)
+- `src/nodeDefinitions/contactsNodes.ts` - Google Contacts integration (6 nodes)
- `src/nodeDefinitions/whatsappNodes.ts` - WhatsApp messaging integration (3 nodes)
- `src/nodeDefinitions/twitterNodes.ts` - Twitter/X integration (4 nodes: send, search, user, receive)
- `src/nodeDefinitions/socialNodes.ts` - Unified social messaging nodes (socialReceive, socialSend)
@@ -400,6 +407,9 @@ The project was completely refactored from schema-based node definitions to expl
- `src/factories/baseChatModelFactory.ts` - Factory for creating standardized chat models
- `src/services/executionService.ts` - Node execution engine with routing to Python backend
+### Assets
+- `src/assets/icons/google/` - Official Google service SVG icons (Gmail, Calendar, Drive, Sheets, Tasks, Contacts) using n8n pattern with data URI exports
+
### UI Components
- `src/components/ParameterRenderer.tsx` - Universal parameter renderer (dual interface support)
- `src/components/parameterPanel/MiddleSection.tsx` - Parameter panel middle section with conditional display logic
@@ -511,7 +521,7 @@ The project uses WebSocket as the primary communication method between frontend
- `server/services/status_broadcaster.py` - Connection management and broadcasting
## Implemented Node Types
-The following 79 nodes are currently implemented and functional:
+The following 104 nodes are currently implemented and functional:
### AI Chat Models (6 nodes)
- **openaiChatModel**: OpenAI GPT models with response format options. O-series models (o1, o3, o4) support reasoning effort parameter.
@@ -539,27 +549,47 @@ server/skills/
├── GUIDE.md # Skill creation guide
├── assistant/ # General-purpose assistant skills
│ ├── assistant-personality/SKILL.md
-│ ├── code-skill/SKILL.md
-│ ├── http-skill/SKILL.md
-│ ├── maps-skill/SKILL.md
+│ ├── compaction-skill/SKILL.md
+│ ├── humanify-skill/SKILL.md
│ ├── memory-skill/SKILL.md
-│ ├── scheduler-skill/SKILL.md
-│ ├── web-search-skill/SKILL.md
-│ └── whatsapp-skill/SKILL.md
-├── android/ # Android device control skills
+│ └── subagent-skill/SKILL.md
+├── android_agent/ # Android device control skills
│ ├── personality/SKILL.md
-│ └── skill/SKILL.md
+│ ├── battery-skill/SKILL.md
+│ ├── wifi-skill/SKILL.md
+│ └── ... (12 skills total)
+├── autonomous/ # Autonomous agent patterns
+│ ├── code-mode-skill/SKILL.md
+│ ├── agentic-loop-skill/SKILL.md
+│ ├── progressive-discovery-skill/SKILL.md
+│ ├── error-recovery-skill/SKILL.md
+│ └── multi-tool-orchestration-skill/SKILL.md
+├── coding_agent/ # Code execution skills
+│ ├── python-skill/SKILL.md
+│ └── javascript-skill/SKILL.md
+├── productivity_agent/ # Google Workspace skills
+│ ├── gmail-skill/SKILL.md # Send, search, read emails
+│ ├── calendar-skill/SKILL.md # Create, list, update, delete events
+│ ├── drive-skill/SKILL.md # Upload, download, list, share files
+│ ├── sheets-skill/SKILL.md # Read, write, append spreadsheet data
+│ ├── tasks-skill/SKILL.md # Create, list, complete tasks
+│ └── contacts-skill/SKILL.md # Create, list, search contacts
├── social_agent/ # Social media platform skills
-│ ├── twitter-send-skill/SKILL.md # Post tweets, reply, retweet, like/unlike, delete
-│ ├── twitter-search-skill/SKILL.md # Search tweets with query operators
-│ ├── twitter-user-skill/SKILL.md # User profile and followers/following lookup
-│ └── whatsapp-send-skill/SKILL.md # WhatsApp messaging skill
-└── autonomous/ # Autonomous agent patterns (Code Mode research)
- ├── code-mode-skill/SKILL.md # Generate code instead of tool calls (81-98% token savings)
- ├── agentic-loop-skill/SKILL.md # OBSERVE-THINK-ACT-REFLECT-DECIDE pattern
- ├── progressive-discovery-skill/SKILL.md # Load tools on-demand (98.7% token savings)
- ├── error-recovery-skill/SKILL.md # Retry strategies, graceful degradation
- └── multi-tool-orchestration-skill/SKILL.md # Coordinate multiple tools for complex tasks
+│ ├── twitter-send-skill/SKILL.md
+│ ├── twitter-search-skill/SKILL.md
+│ ├── twitter-user-skill/SKILL.md
+│ ├── whatsapp-send-skill/SKILL.md
+│ └── whatsapp-db-skill/SKILL.md
+├── task_agent/ # Task management skills
+│ ├── timer-skill/SKILL.md
+│ ├── cron-scheduler-skill/SKILL.md
+│ └── task-manager-skill/SKILL.md
+├── travel_agent/ # Location and maps skills
+│ ├── geocoding-skill/SKILL.md
+│ └── nearby-places-skill/SKILL.md
+└── web_agent/ # Web automation skills
+ ├── web-search-skill/SKILL.md
+ └── http-request-skill/SKILL.md
```
**SKILL.md Format:**
@@ -903,6 +933,133 @@ TWITTER_CLIENT_SECRET=your_client_secret
TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback
```
+### Google Workspace Nodes (26 nodes)
+Unified Google Workspace integration supporting Gmail, Calendar, Drive, Sheets, Tasks, and Contacts. All services share a single OAuth connection with combined scopes. All nodes are execution-ready with Run button in parameter panel.
+
+#### Gmail Nodes (4 nodes)
+- **gmailSend**: **Dual-purpose node** - Send emails with attachments. Works as workflow node OR AI Agent tool.
+- **gmailSearch**: **Dual-purpose node** - Search emails using Gmail query syntax.
+- **gmailRead**: **Dual-purpose node** - Read email content by message ID.
+- **gmailReceive**: Event-driven trigger for incoming emails.
+
+#### Calendar Nodes (4 nodes)
+- **calendarCreate**: **Dual-purpose node** - Create calendar events with title, time, description, attendees, location.
+- **calendarList**: **Dual-purpose node** - List events in date range with filtering.
+- **calendarUpdate**: **Dual-purpose node** - Update existing events.
+- **calendarDelete**: **Dual-purpose node** - Delete events by ID.
+
+#### Drive Nodes (4 nodes)
+- **driveUpload**: **Dual-purpose node** - Upload files from URL or path.
+- **driveDownload**: **Dual-purpose node** - Download files by ID.
+- **driveList**: **Dual-purpose node** - List files in folder with query.
+- **driveShare**: **Dual-purpose node** - Share files with users.
+
+#### Sheets Nodes (3 nodes)
+- **sheetsRead**: **Dual-purpose node** - Read data from spreadsheet range.
+- **sheetsWrite**: **Dual-purpose node** - Write data to specific range.
+- **sheetsAppend**: **Dual-purpose node** - Append rows to sheet.
+
+#### Tasks Nodes (5 nodes)
+- **tasksCreate**: **Dual-purpose node** - Create tasks with title, notes, due date.
+- **tasksList**: **Dual-purpose node** - List tasks with filters.
+- **tasksComplete**: **Dual-purpose node** - Mark task as complete.
+- **tasksUpdate**: **Dual-purpose node** - Update existing task.
+- **tasksDelete**: **Dual-purpose node** - Delete task by ID.
+
+#### Contacts Nodes (6 nodes)
+- **contactsCreate**: **Dual-purpose node** - Create contact with name, email, phone.
+- **contactsList**: **Dual-purpose node** - List contacts with pagination.
+- **contactsSearch**: **Dual-purpose node** - Search contacts by query.
+- **contactsGet**: **Dual-purpose node** - Get contact details by resource name.
+- **contactsUpdate**: **Dual-purpose node** - Update existing contact.
+- **contactsDelete**: **Dual-purpose node** - Delete contact.
+
+#### Google Workspace OAuth 2.0 Authentication
+Authentication is handled via OAuth 2.0 flow in the Credentials Modal:
+1. User enters Google Cloud Client ID and Secret (OAuth 2.0 credentials)
+2. User clicks "Login with Google"
+3. Consent screen shows all requested scopes (Gmail, Calendar, Drive, etc.)
+4. User grants permission, Google redirects with auth code
+5. Backend exchanges code for access_token + refresh_token
+6. Tokens stored via auth_service (owner mode) or google_connections table (customer mode)
+
+**Combined OAuth Scopes:**
+```python
+GOOGLE_WORKSPACE_SCOPES = [
+ # User Info
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile",
+ # Gmail
+ "https://www.googleapis.com/auth/gmail.send",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/gmail.modify",
+ # Calendar
+ "https://www.googleapis.com/auth/calendar",
+ "https://www.googleapis.com/auth/calendar.events",
+ # Drive
+ "https://www.googleapis.com/auth/drive",
+ "https://www.googleapis.com/auth/drive.file",
+ # Sheets
+ "https://www.googleapis.com/auth/spreadsheets",
+ # Tasks
+ "https://www.googleapis.com/auth/tasks",
+ # Contacts
+ "https://www.googleapis.com/auth/contacts",
+ "https://www.googleapis.com/auth/contacts.readonly",
+]
+```
+
+**Key Files:**
+| File | Description |
+|------|-------------|
+| `server/services/google_oauth.py` | Unified OAuth 2.0 implementation |
+| `server/config/google_apis.json` | API endpoints and scopes config |
+| `server/routers/google.py` | OAuth callback and status endpoints |
+| `server/services/handlers/gmail.py` | Gmail handlers |
+| `server/services/handlers/calendar.py` | Calendar handlers |
+| `server/services/handlers/drive.py` | Drive handlers |
+| `server/services/handlers/sheets.py` | Sheets handlers |
+| `server/services/handlers/tasks.py` | Tasks handlers |
+| `server/services/handlers/contacts.py` | Contacts handlers |
+| `server/models/database.py` | `GoogleConnection` model |
+| `server/skills/productivity_agent/` | Google Workspace skills for AI agents |
+| `client/src/nodeDefinitions/gmailNodes.ts` | Gmail node definitions |
+| `client/src/nodeDefinitions/calendarNodes.ts` | Calendar node definitions |
+| `client/src/nodeDefinitions/driveNodes.ts` | Drive node definitions |
+| `client/src/nodeDefinitions/sheetsNodes.ts` | Sheets node definitions |
+| `client/src/nodeDefinitions/tasksNodes.ts` | Tasks node definitions |
+| `client/src/nodeDefinitions/contactsNodes.ts` | Contacts node definitions |
+| `client/src/assets/icons/google/` | Official Google service SVG icons (n8n pattern) |
+| `client/src/components/CredentialsModal.tsx` | Google Workspace panel |
+
+**Token Storage (Unified `google_*` prefix):**
+| Token Key | Description |
+|-----------|-------------|
+| `google_client_id` | OAuth 2.0 Client ID |
+| `google_client_secret` | OAuth 2.0 Client Secret |
+| `google_access_token` | Access token for API calls |
+| `google_refresh_token` | Refresh token for token renewal |
+| `google_user_info` | Connected user email and name |
+
+**AI Agent Skills (productivity_agent folder):**
+| Skill | Tools | Description |
+|-------|-------|-------------|
+| `gmail-skill` | `gmail_send`, `gmail_search`, `gmail_read` | Send, search, read emails |
+| `calendar-skill` | `calendar_create`, `calendar_list`, `calendar_update`, `calendar_delete` | Manage calendar events |
+| `drive-skill` | `drive_upload`, `drive_download`, `drive_list`, `drive_share` | Manage Drive files |
+| `sheets-skill` | `sheets_read`, `sheets_write`, `sheets_append` | Read/write spreadsheet data |
+| `tasks-skill` | `tasks_create`, `tasks_list`, `tasks_complete` | Manage Google Tasks |
+| `contacts-skill` | `contacts_create`, `contacts_list`, `contacts_search` | Manage contacts |
+
+**Environment Variables:**
+```bash
+# OAuth redirect (optional, defaults to localhost:3010)
+GOOGLE_REDIRECT_URI=http://localhost:3010/api/google/callback
+```
+
+**Google API Pricing:** All Google Workspace APIs are free with rate limits. See `server/config/pricing.json` for configured limits.
+
### Workflow Nodes (2 nodes)
- **start**: Manual workflow trigger to start workflow execution
- **taskTrigger**: Event-driven trigger that fires when a delegated child agent completes its task (success or error). Filters by task_id, agent_name, status (all/completed/error), and parent_node_id. Output includes task_id, status, agent_name, result/error, workflow_id.
@@ -1540,11 +1697,12 @@ def create_model(self, provider: str, api_key: str, model: str,
- **Models**: Automatic discovery and caching of available models per provider
- **Expiration**: 30-day validation period with automatic cleanup
-### Execution Flow (`src/services/executionService.ts:387`)
+### Execution Flow (`src/services/executionService.ts`)
- **Detection**: `isAIModelNode()` identifies AI chat models for Python routing
- **Enhancement**: `injectStoredApiKeys()` auto-injects stored credentials and models
- **Routing**: AI nodes → Python Flask backend, other nodes → Node.js backend
- **Logging**: Comprehensive debug output for API key injection and model selection
+- **Supported Types**: `isNodeTypeSupported()` controls which nodes show Run button - includes AI models, agents, Android, WhatsApp, Twitter, Google Workspace, code executors, schedulers, utilities, and document processing nodes
### Parameter System Integration
- **Template Variables**: Support for `{{nodeId.output}}` syntax in all text parameters
diff --git a/README.md b/README.md
index 4904db6d..2b6b4706 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ Open-source platform to build your own personal AI assistant. A mashup of clawdb
<img width="1280" height="671" alt="func_img" src="https://github.com/user-attachments/assets/2f14b6c8-3995-4ccc-b076-e40749a83df2" />
-**83 nodes** | **6 AI providers** | **13 specialized agents** | **Agent Teams** | **WebSocket-first** | **Self-hosted**
+**109 nodes** | **6 AI providers** | **13 specialized agents** | **Agent Teams** | **WebSocket-first** | **Self-hosted**
## Prerequisites
@@ -76,6 +76,7 @@ npm run start
### Platform Integrations
+- **Google Workspace** - Gmail, Calendar, Drive, Sheets, Tasks, Contacts with unified OAuth
- **WhatsApp** - Send/receive messages with QR pairing, filters, group support
- **Twitter/X** - Send tweets, search, user lookup with OAuth 2.0 authentication
- **Android** - 16 service nodes for device control (battery, WiFi, Bluetooth, apps, camera, sensors)
@@ -122,15 +123,16 @@ Build teams of specialized agents that work together on complex tasks:
| Specialized Agents | 13 | Android, Coding, Web, Task, Social, Travel, Orchestrator, etc. |
| AI Skills | 11 | WhatsApp, Maps, HTTP, Scheduler, Android, Code, etc. |
| AI Tools | 9 | Calculator, Time, Search, Android Toolkit, Code Executors |
+| Google Workspace | 26 | Gmail, Calendar, Drive, Sheets, Tasks, Contacts |
| WhatsApp | 3 | Send, Receive, Database |
-| Twitter | 3 | Send, Search, User |
+| Twitter | 4 | Send, Search, User, Receive |
| Android | 16 | Device control and monitoring |
| Documents | 6 | RAG pipeline nodes |
| Utilities | 6 | HTTP, Webhooks, Chat Trigger, Console, Team Monitor |
| Location | 3 | Google Maps integration |
-| Workflow | 3 | Start, Timer, Cron Scheduler |
+| Workflow | 2 | Start, Task Trigger |
-**Total: 83 nodes**
+**Total: 109 nodes**
## CLI Commands
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index f97c39b8..57417022 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -97,6 +97,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (type === 'gmailSend' || type === 'gmailSearch' || type === 'gmailRead') {
// Gmail action nodes use SquareNode (gmailReceive is a trigger)
types[type] = SquareNode;
+ } else if (type.startsWith('calendar') || type.startsWith('drive') || type.startsWith('sheets') || type.startsWith('tasks') || type.startsWith('contacts')) {
+ // Google Workspace nodes (Calendar, Drive, Sheets, Tasks, Contacts) use SquareNode
+ types[type] = SquareNode;
} else if (ANDROID_SERVICE_NODE_TYPES.includes(type)) {
// Android service nodes use SquareNode component
types[type] = SquareNode;
diff --git a/client/src/assets/icons/google/calendar.svg b/client/src/assets/icons/google/calendar.svg
new file mode 100644
index 00000000..7e01c404
--- /dev/null
+++ b/client/src/assets/icons/google/calendar.svg
@@ -0,0 +1,12 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" fill="none">
+ <g fill-rule="nonzero">
+ <path fill="#fff" d="M61.052 18.947H18.947v42.105h42.105z"/>
+ <path fill="#EA4335" d="M61.053 80 80 61.053H61.053z"/>
+ <path fill="#FBBC04" d="M80 18.947H61.053v42.105H80z"/>
+ <path fill="#34A853" d="M61.052 61.053H18.947V80h42.105z"/>
+ <path fill="#188038" d="M0 61.053v12.632A6.314 6.314 0 0 0 6.316 80h12.632V61.053z"/>
+ <path fill="#1967D2" d="M80 18.947V6.316A6.314 6.314 0 0 0 73.685 0H61.053v18.947z"/>
+ <path fill="#4285F4" d="M61.053 0H6.316A6.314 6.314 0 0 0 0 6.316v54.737h18.947V18.947h42.105V0z"/>
+ <path fill="#4285F4" d="M27.584 51.611c-1.574-1.063-2.663-2.616-3.258-4.668l3.653-1.505c.332 1.263.913 2.263 1.737 2.937 1.239 1.043 1.821 1.037 2.989 1.037 1.195 0 2.195-.363 3.079-1.089 1.287-1.089 1.29-1.653 1.29-2.774a3.44 3.44 0 0 0-1.358-2.811c-.905-.727-2.042-1.089-3.4-1.089h-2.111v-3.616H32.1c1.168 0 2.168-.316 2.953-.947 1.201-.947 1.2-1.495 1.2-2.595 0-.978-.358-1.79-1.074-2.342-1.074-.875-1.621-.879-2.721-.879-1.074-.001-1.932.286-2.558.858-.948.86-1.106 1.301-1.379 2.111l-3.616-1.505c.479-1.358 1.358-2.558 2.647-3.595s2.937-1.558 4.937-1.558c1.48-.001 2.816.286 3.989.858 1.769.86 2.105 1.368 2.774 2.379s1 2.153 1 3.416c0 1.288-.311 2.384-.932 3.274-.932 1.342-1.384 1.579-2.289 2.058v.216a6.95 6.95 0 0 1 2.937 2.289c.764 1.025 1.147 2.296 1.147 3.684.001 2.146-.363 2.711-1.089 3.832s-1.732 2.005-3.005 2.647c-1.279.642-2.716.968-4.311.968-1.847.005-3.553-.526-5.126-1.589zm22.437-18.126-4.01 2.9-2.005-3.042 7.195-5.189h2.758v24.479h-3.937V33.484z"/>
+ </g>
+</svg>
diff --git a/client/src/assets/icons/google/contacts.svg b/client/src/assets/icons/google/contacts.svg
new file mode 100644
index 00000000..0e5ca0cf
--- /dev/null
+++ b/client/src/assets/icons/google/contacts.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192" fill="none">
+ <rect width="192" height="192" fill="#4285F4" rx="40"/>
+ <circle cx="96" cy="72" r="28" fill="#fff"/>
+ <path fill="#fff" d="M96 108c-30.928 0-56 18.804-56 42v6h112v-6c0-23.196-25.072-42-56-42z"/>
+</svg>
diff --git a/client/src/assets/icons/google/drive.svg b/client/src/assets/icons/google/drive.svg
new file mode 100644
index 00000000..6df1e4db
--- /dev/null
+++ b/client/src/assets/icons/google/drive.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 72" fill="none">
+ <g fill-rule="nonzero">
+ <path fill="#0066DA" d="m6.048 61.26 3.528 6.094c.733 1.283 1.787 2.291 3.024 3.024l12.6-21.81H0a8.3 8.3 0 0 0 1.1 4.124z"/>
+ <path fill="#00AC47" d="M40 22.91 27.4 1.1c-1.237.733-2.291 1.741-3.024 3.024L1.1 44.445A8.3 8.3 0 0 0 0 48.568h25.2z"/>
+ <path fill="#EA4335" d="M67.4 70.378c1.237-.733 2.291-1.741 3.024-3.024l1.466-2.52 7.01-12.142a8.3 8.3 0 0 0 1.1-4.124H54.798l5.363 10.538z"/>
+ <path fill="#00832D" d="M40 22.91 52.6 1.1C51.363.367 49.943 0 48.477 0H31.524c-1.466 0-2.887.412-4.124 1.1z"/>
+ <path fill="#2684FC" d="M54.799 48.568H25.2l-12.6 21.81c1.237.733 2.657 1.1 4.124 1.1h46.552c1.466 0 2.887-.412 4.124-1.1z"/>
+ <path fill="#FFBA00" d="M67.262 24.284 55.624 4.124C54.891 2.841 53.837 1.833 52.6 1.1L40 22.91l14.8 25.659h25.155a8.3 8.3 0 0 0-1.1-4.124z"/>
+ </g>
+</svg>
diff --git a/client/src/assets/icons/google/gmail.svg b/client/src/assets/icons/google/gmail.svg
new file mode 100644
index 00000000..bf1fca19
--- /dev/null
+++ b/client/src/assets/icons/google/gmail.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="193" viewBox="0 0 256 193" preserveAspectRatio="xMidYMid">
+ <path fill="#4285F4" d="M58.182 192.05V93.14L27.507 65.077 0 49.504v125.091c0 9.658 7.825 17.455 17.455 17.455z"/>
+ <path fill="#34A853" d="M197.818 192.05h40.727c9.659 0 17.455-7.826 17.455-17.455V49.505l-31.156 17.837-27.026 25.798z"/>
+ <path fill="#EA4335" d="m58.182 93.14-4.174-38.647 4.174-36.989L128 69.868l69.818-52.364 4.67 34.992-4.67 40.644L128 145.504z"/>
+ <path fill="#FBBC04" d="M197.818 17.504V93.14L256 49.504V26.231c0-21.585-24.64-33.89-41.89-20.945z"/>
+ <path fill="#C5221F" d="m0 49.504 26.759 20.07L58.182 93.14V17.504L41.89 5.286C24.61-7.66 0 4.646 0 26.23z"/>
+</svg>
diff --git a/client/src/assets/icons/google/index.ts b/client/src/assets/icons/google/index.ts
new file mode 100644
index 00000000..1556a480
--- /dev/null
+++ b/client/src/assets/icons/google/index.ts
@@ -0,0 +1,34 @@
+// Official Google Workspace service icons
+// Based on n8n's implementation using SVG files
+
+import gmailSvg from './gmail.svg?raw';
+import calendarSvg from './calendar.svg?raw';
+import driveSvg from './drive.svg?raw';
+import sheetsSvg from './sheets.svg?raw';
+import tasksSvg from './tasks.svg?raw';
+import contactsSvg from './contacts.svg?raw';
+
+// Convert SVG to data URI for use in node definitions
+const svgToDataUri = (svg: string): string => {
+ const encoded = encodeURIComponent(svg)
+ .replace(/'/g, '%27')
+ .replace(/"/g, '%22');
+ return `data:image/svg+xml,${encoded}`;
+};
+
+export const GMAIL_ICON = svgToDataUri(gmailSvg);
+export const CALENDAR_ICON = svgToDataUri(calendarSvg);
+export const DRIVE_ICON = svgToDataUri(driveSvg);
+export const SHEETS_ICON = svgToDataUri(sheetsSvg);
+export const TASKS_ICON = svgToDataUri(tasksSvg);
+export const CONTACTS_ICON = svgToDataUri(contactsSvg);
+
+// Export raw SVGs for React component usage
+export const GoogleIcons = {
+ gmail: gmailSvg,
+ calendar: calendarSvg,
+ drive: driveSvg,
+ sheets: sheetsSvg,
+ tasks: tasksSvg,
+ contacts: contactsSvg,
+};
diff --git a/client/src/assets/icons/google/sheets.svg b/client/src/assets/icons/google/sheets.svg
new file mode 100644
index 00000000..402005f3
--- /dev/null
+++ b/client/src/assets/icons/google/sheets.svg
@@ -0,0 +1,8 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 51 59" fill="none">
+ <g fill-rule="evenodd">
+ <path fill="#28B446" d="M34.69 0 51 16.225v39.087a3.67 3.67 0 0 1-1.084 2.61A3.7 3.7 0 0 1 47.293 59H11.707a3.7 3.7 0 0 1-2.623-1.078A3.67 3.67 0 0 1 8 55.312V3.688a3.67 3.67 0 0 1 1.084-2.61A3.7 3.7 0 0 1 11.707 0z"/>
+ <path fill="#6ACE7C" d="M34.69 0 51 16.225H38.397c-2.054 0-3.707-1.829-3.707-3.872z"/>
+ <path fill="#219B38" d="M38.211 16.225 51 21.48v-5.255z"/>
+ <path fill="#FFF" d="M19.12 30.975c0-.817.662-1.475 1.483-1.475h17.794c.821 0 1.482.658 1.482 1.475v15.487c0 .818-.661 1.475-1.482 1.475H20.603a1.476 1.476 0 0 1-1.482-1.474V30.974zm2.225 1.475h6.672v2.212h-6.672zm0 5.162h6.672v2.213h-6.672zm0 5.163h6.672v2.212h-6.672zm9.638-10.325h6.672v2.212h-6.672zm0 5.162h6.672v2.213h-6.672zm0 5.163h6.672v2.212h-6.672z"/>
+ </g>
+</svg>
diff --git a/client/src/assets/icons/google/tasks.svg b/client/src/assets/icons/google/tasks.svg
new file mode 100644
index 00000000..02a325c7
--- /dev/null
+++ b/client/src/assets/icons/google/tasks.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192" fill="none">
+ <rect width="192" height="192" fill="#4285F4" rx="40"/>
+ <path fill="#fff" d="M144 64H80a8 8 0 0 0 0 16h64a8 8 0 0 0 0-16zM144 88H80a8 8 0 0 0 0 16h64a8 8 0 0 0 0-16zM144 112H80a8 8 0 0 0 0 16h64a8 8 0 0 0 0-16z"/>
+ <circle cx="56" cy="72" r="8" fill="#fff"/>
+ <circle cx="56" cy="96" r="8" fill="#fff"/>
+ <circle cx="56" cy="120" r="8" fill="#fff"/>
+</svg>
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index 38a1b439..ad5c1978 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -52,8 +52,8 @@ const XIcon = () => (
<TwitterOutlined style={{ fontSize: 20, color: '#000000' }} />
);
-const GmailIcon = () => (
- <GoogleOutlined style={{ fontSize: 20, color: '#EA4335' }} />
+const GoogleWorkspaceIcon = () => (
+ <GoogleOutlined style={{ fontSize: 20, color: '#4285F4' }} />
);
// ============================================================================
@@ -97,7 +97,7 @@ const CATEGORIES: Category[] = [
items: [
{ id: 'whatsapp_personal', name: 'WhatsApp Personal', placeholder: '', color: '#25D366', desc: 'Connect via QR code pairing', CustomIcon: WhatsAppIcon, isSpecial: true, panelType: 'whatsapp' },
{ id: 'twitter', name: 'Twitter/X', placeholder: '', color: '#000000', desc: 'Post tweets, search, user lookup', CustomIcon: XIcon, isSpecial: true, panelType: 'twitter' },
- { id: 'gmail', name: 'Gmail', placeholder: '', color: '#EA4335', desc: 'Send, search, read emails', CustomIcon: GmailIcon, isSpecial: true, panelType: 'gmail' },
+ { id: 'gmail', name: 'Google Workspace', placeholder: '', color: '#4285F4', desc: 'Gmail, Calendar, Drive, Sheets, Tasks, Contacts', CustomIcon: GoogleWorkspaceIcon, isSpecial: true, panelType: 'gmail' },
],
},
{
@@ -502,14 +502,14 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [visible, hasStoredKey, getStoredApiKey]);
- // Load Gmail credentials on mount
+ // Load Google Workspace credentials on mount
useEffect(() => {
if (visible) {
- hasStoredKey('gmail_client_id').then(async (has) => {
+ hasStoredKey('google_client_id').then(async (has) => {
setGmailCredentialsStored(has);
if (has) {
- const clientId = await getStoredApiKey('gmail_client_id');
- const clientSecret = await getStoredApiKey('gmail_client_secret');
+ const clientId = await getStoredApiKey('google_client_id');
+ const clientSecret = await getStoredApiKey('google_client_secret');
if (clientId) setGmailClientId(clientId);
if (clientSecret) setGmailClientSecret(clientSecret);
}
@@ -593,8 +593,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
setGmailLoading('save');
setGmailError(null);
try {
- await saveApiKey('gmail_client_id', gmailClientId.trim());
- await saveApiKey('gmail_client_secret', gmailClientSecret.trim());
+ // Save with google_ prefix (new standard)
+ await saveApiKey('google_client_id', gmailClientId.trim());
+ await saveApiKey('google_client_secret', gmailClientSecret.trim());
setGmailCredentialsStored(true);
} catch (err: any) {
setGmailError(err.message || 'Failed to save credentials');
@@ -607,7 +608,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
setGmailLoading('login');
setGmailError(null);
try {
- const response = await sendRequest('gmail_oauth_login', {});
+ const response = await sendRequest('google_oauth_login', {});
if (!response.success) {
setGmailError(response.error || 'Failed to start OAuth');
}
@@ -622,7 +623,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
setGmailLoading('logout');
setGmailError(null);
try {
- const response = await sendRequest('gmail_logout', {});
+ const response = await sendRequest('google_logout', {});
if (!response.success) {
setGmailError(response.error || 'Failed to disconnect');
}
@@ -637,7 +638,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
setGmailLoading('refresh');
setGmailError(null);
try {
- await sendRequest('gmail_oauth_status', {});
+ await sendRequest('google_oauth_status', {});
} catch (err: any) {
setGmailError(err.message || 'Failed to refresh status');
} finally {
@@ -1633,12 +1634,12 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
);
}
- // Gmail panel
+ // Google Workspace panel (Gmail, Calendar, Drive, Sheets, Tasks, Contacts)
if (selectedItem.panelType === 'gmail') {
return (
<div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
<Descriptions
- title={<Space><GmailIcon /> Gmail</Space>}
+ title={<Space><GoogleWorkspaceIcon /> Google Workspace</Space>}
bordered
column={1}
size="small"
@@ -1683,6 +1684,18 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
</Space>
</Descriptions.Item>
)}
+ {gmailStatus.connected && (
+ <Descriptions.Item label="Services">
+ <Space wrap size={[4, 4]}>
+ <Tag style={{ backgroundColor: `${theme.dracula.green}15`, borderColor: `${theme.dracula.green}40`, color: theme.dracula.green }}>Gmail</Tag>
+ <Tag style={{ backgroundColor: `${theme.dracula.cyan}15`, borderColor: `${theme.dracula.cyan}40`, color: theme.dracula.cyan }}>Calendar</Tag>
+ <Tag style={{ backgroundColor: `${theme.dracula.purple}15`, borderColor: `${theme.dracula.purple}40`, color: theme.dracula.purple }}>Drive</Tag>
+ <Tag style={{ backgroundColor: `${theme.dracula.orange}15`, borderColor: `${theme.dracula.orange}40`, color: theme.dracula.orange }}>Sheets</Tag>
+ <Tag style={{ backgroundColor: `${theme.dracula.pink}15`, borderColor: `${theme.dracula.pink}40`, color: theme.dracula.pink }}>Tasks</Tag>
+ <Tag style={{ backgroundColor: `${theme.dracula.yellow}15`, borderColor: `${theme.dracula.yellow}40`, color: theme.dracula.yellow }}>Contacts</Tag>
+ </Space>
+ </Descriptions.Item>
+ )}
</Descriptions>
{/* API Credentials Input - Only show if not connected */}
@@ -1695,7 +1708,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
color: theme.colors.text,
marginBottom: theme.spacing.sm,
}}>
- Gmail API Credentials
+ Google Workspace API Credentials
</label>
<div style={{ marginBottom: theme.spacing.md }}>
<Input
@@ -1742,9 +1755,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
marginTop: theme.spacing.sm,
lineHeight: 1.5,
}}>
- Get credentials from Google Cloud Console. Enable the Gmail API and create OAuth 2.0 credentials.
+ Get credentials from Google Cloud Console. Enable Gmail, Calendar, Drive, Sheets, Tasks, and People APIs.
<br />
- Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/gmail/callback</code>
+ Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/google/callback</code>
</div>
</div>
)}
@@ -1754,7 +1767,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
)}
{/* API Usage Stats */}
- {renderApiUsagePanel('gmail', 'Gmail')}
+ {renderApiUsagePanel('google_workspace', 'Google Workspace')}
{/* Info box */}
<div style={{
@@ -1771,11 +1784,11 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
lineHeight: 1.5,
}}>
{gmailStatus.connected ? (
- <>Your Gmail account is connected. You can now use Gmail nodes in your workflows.</>
+ <>Your Google Workspace account is connected. You can now use Gmail, Calendar, Drive, Sheets, Tasks, and Contacts nodes in your workflows.</>
) : gmailCredentialsStored ? (
<>Click Login with Google to authorize. A browser window will open for authentication.</>
) : (
- <>Enter your Gmail API credentials above to get started.</>
+ <>Enter your Google Workspace API credentials above to get started.</>
)}
</div>
</div>
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsx
index 1e2d6ede..245c1647 100644
--- a/client/src/components/SquareNode.tsx
+++ b/client/src/components/SquareNode.tsx
@@ -9,7 +9,6 @@ import { useWebSocket, useWhatsAppStatus } from '../contexts/WebSocketContext';
import { useApiKeys } from '../hooks/useApiKeys';
import { getAIProviderIcon } from './icons/AIProviderIcons';
import { PlayCircleFilled, ScheduleOutlined } from '@ant-design/icons';
-import { Google } from '@lobehub/icons';
// Android service nodes that can connect to Android Toolkit as tools
const ANDROID_TOOL_CAPABLE_NODES = ANDROID_SERVICE_NODE_TYPES;
@@ -458,19 +457,9 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
return emojiRegex.test(str);
};
- // Helper to render icon (handles URLs, emojis, component markers, and icon names)
+ // Helper to render icon (handles URLs, emojis, and icon names)
const renderIcon = (icon: string) => {
- // Handle component markers (e.g., 'component:Gmail')
- if (icon.startsWith('component:')) {
- const componentName = icon.replace('component:', '');
- if (componentName === 'Gmail') {
- return <Google.Color size={28} />;
- }
- // Fallback for unknown component markers
- return '📦';
- }
-
- // Handle image URLs
+ // Handle image URLs and data URIs (including SVG data URIs for Google icons)
if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {
return (
<img
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index ab29cd59..dd2a51ca 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -313,6 +313,147 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
labels: 'array',
attachments: 'array'
},
+ // Google Calendar
+ calendarCreate: {
+ event_id: 'string',
+ title: 'string',
+ start: 'string',
+ end: 'string',
+ description: 'string',
+ location: 'string',
+ html_link: 'string',
+ status: 'string'
+ },
+ calendarList: {
+ events: 'array',
+ count: 'number'
+ },
+ calendarUpdate: {
+ event_id: 'string',
+ title: 'string',
+ start: 'string',
+ end: 'string',
+ updated: 'string'
+ },
+ calendarDelete: {
+ deleted: 'boolean',
+ event_id: 'string'
+ },
+ // Google Drive
+ driveUpload: {
+ file_id: 'string',
+ name: 'string',
+ mime_type: 'string',
+ web_view_link: 'string',
+ web_content_link: 'string',
+ size: 'number'
+ },
+ driveDownload: {
+ file_id: 'string',
+ name: 'string',
+ content: 'string',
+ mime_type: 'string',
+ size: 'number'
+ },
+ driveList: {
+ files: 'array',
+ count: 'number',
+ next_page_token: 'string'
+ },
+ driveShare: {
+ file_id: 'string',
+ permission_id: 'string',
+ role: 'string',
+ email: 'string'
+ },
+ // Google Sheets
+ sheetsRead: {
+ values: 'array',
+ range: 'string',
+ rows: 'number',
+ columns: 'number',
+ major_dimension: 'string'
+ },
+ sheetsWrite: {
+ updated_range: 'string',
+ updated_rows: 'number',
+ updated_columns: 'number',
+ updated_cells: 'number'
+ },
+ sheetsAppend: {
+ updated_range: 'string',
+ updated_rows: 'number',
+ updated_columns: 'number',
+ updated_cells: 'number',
+ table_range: 'string'
+ },
+ // Google Tasks
+ tasksCreate: {
+ task_id: 'string',
+ title: 'string',
+ notes: 'string',
+ due: 'string',
+ status: 'string'
+ },
+ tasksList: {
+ tasks: 'array',
+ count: 'number'
+ },
+ tasksComplete: {
+ task_id: 'string',
+ title: 'string',
+ status: 'string',
+ completed: 'string'
+ },
+ tasksUpdate: {
+ task_id: 'string',
+ title: 'string',
+ notes: 'string',
+ due: 'string',
+ status: 'string'
+ },
+ tasksDelete: {
+ deleted: 'boolean',
+ task_id: 'string'
+ },
+ // Google Contacts (People API)
+ contactsCreate: {
+ resource_name: 'string',
+ display_name: 'string',
+ email: 'string',
+ phone: 'string',
+ company: 'string'
+ },
+ contactsList: {
+ contacts: 'array',
+ count: 'number',
+ total_people: 'number',
+ next_page_token: 'string'
+ },
+ contactsSearch: {
+ contacts: 'array',
+ count: 'number'
+ },
+ contactsGet: {
+ resource_name: 'string',
+ display_name: 'string',
+ given_name: 'string',
+ family_name: 'string',
+ email: 'string',
+ phone: 'string',
+ company: 'string',
+ job_title: 'string'
+ },
+ contactsUpdate: {
+ resource_name: 'string',
+ display_name: 'string',
+ email: 'string',
+ phone: 'string'
+ },
+ contactsDelete: {
+ deleted: 'boolean',
+ resource_name: 'string'
+ },
httpRequest: {
status: 'number',
data: 'any',
@@ -567,6 +708,16 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const isGmailSearch = nodeType === 'gmailSearch';
const isGmailRead = nodeType === 'gmailRead';
+ // Google Workspace nodes detection
+ const googleWorkspaceNodeTypes = [
+ 'calendarCreate', 'calendarList', 'calendarUpdate', 'calendarDelete',
+ 'driveUpload', 'driveDownload', 'driveList', 'driveShare',
+ 'sheetsRead', 'sheetsWrite', 'sheetsAppend',
+ 'tasksCreate', 'tasksList', 'tasksComplete', 'tasksUpdate', 'tasksDelete',
+ 'contactsCreate', 'contactsList', 'contactsSearch', 'contactsGet', 'contactsUpdate', 'contactsDelete'
+ ];
+ const isGoogleWorkspaceNode = googleWorkspaceNodeTypes.includes(nodeType);
+
// Document processing node detection
const documentNodeTypes = ['httpScraper', 'fileDownloader', 'documentParser', 'textChunker', 'embeddingGenerator', 'vectorStore'];
const isDocumentNode = documentNodeTypes.includes(nodeType);
@@ -593,6 +744,8 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
outputSchema = sampleSchemas[nodeType as keyof typeof sampleSchemas];
} else if (isDocumentNode && sampleSchemas[nodeType as keyof typeof sampleSchemas]) {
outputSchema = sampleSchemas[nodeType as keyof typeof sampleSchemas];
+ } else if (isGoogleWorkspaceNode && sampleSchemas[nodeType as keyof typeof sampleSchemas]) {
+ outputSchema = sampleSchemas[nodeType as keyof typeof sampleSchemas];
} else {
outputSchema = isLocationNode || isGoogleMaps ? sampleSchemas.location :
isMemory ? sampleSchemas.memory :
diff --git a/client/src/components/ui/ComponentItem.tsx b/client/src/components/ui/ComponentItem.tsx
index 8d2cc7d8..c904283a 100644
--- a/client/src/components/ui/ComponentItem.tsx
+++ b/client/src/components/ui/ComponentItem.tsx
@@ -11,9 +11,11 @@ const ComponentItem: React.FC<ComponentItemProps> = ({ definition, onDragStart }
const theme = useAppTheme();
const [isDragging, setIsDragging] = useState(false);
const [isHovered, setIsHovered] = useState(false);
-
+
// Helper to get colors from new interface format
const getNodeColor = () => definition.defaults.color || '#9E9E9E';
+
+ // Check if icon is an image URL or data URI (including SVG data URIs for Google icons)
const isImageIcon = () => {
const icon = definition.icon;
return icon && (icon.startsWith('data:') || icon.startsWith('http') || icon.startsWith('/'));
@@ -81,7 +83,7 @@ const ComponentItem: React.FC<ComponentItemProps> = ({ definition, onDragStart }
transition: `opacity ${theme.transitions.fast}`,
pointerEvents: 'none',
}} />
-
+
{/* Icon */}
<div
style={{
@@ -99,16 +101,16 @@ const ComponentItem: React.FC<ComponentItemProps> = ({ definition, onDragStart }
zIndex: 1,
}}
>
- {definition.icon && (definition.icon.startsWith('data:') || definition.icon.startsWith('http') || definition.icon.startsWith('/')) ? (
+ {isImageIcon() ? (
<img src={definition.icon} alt="" style={{ width: '20px', height: '20px', objectFit: 'contain' }} />
) : (
definition.icon || '📦'
)}
</div>
-
+
{/* Content */}
- <div style={{
- flex: 1,
+ <div style={{
+ flex: 1,
overflow: 'hidden',
position: 'relative',
zIndex: 1,
@@ -151,4 +153,4 @@ const ComponentItem: React.FC<ComponentItemProps> = ({ definition, onDragStart }
);
};
-export default ComponentItem;
\ No newline at end of file
+export default ComponentItem;
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 9b0c6230..791fbec9 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -569,8 +569,8 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
- case 'gmail_oauth_complete':
- // Handle Gmail OAuth completion broadcast from backend
+ case 'google_oauth_complete':
+ // Handle Google Workspace OAuth completion broadcast from backend
if (data?.success) {
setGmailStatus({
connected: true,
diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.ts
index c73843e9..d9bb9385 100644
--- a/client/src/nodeDefinitions.ts
+++ b/client/src/nodeDefinitions.ts
@@ -19,6 +19,11 @@ import { documentNodes, DOCUMENT_NODE_TYPES } from './nodeDefinitions/documentNo
import { socialNodes, SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';
import { twitterNodes, TWITTER_NODE_TYPES } from './nodeDefinitions/twitterNodes';
import { gmailNodes, GMAIL_NODE_TYPES } from './nodeDefinitions/gmailNodes';
+import { calendarNodes, CALENDAR_NODE_TYPES } from './nodeDefinitions/calendarNodes';
+import { driveNodes, DRIVE_NODE_TYPES } from './nodeDefinitions/driveNodes';
+import { sheetsNodes, SHEETS_NODE_TYPES } from './nodeDefinitions/sheetsNodes';
+import { tasksNodes, TASKS_NODE_TYPES } from './nodeDefinitions/tasksNodes';
+import { contactsNodes, CONTACTS_NODE_TYPES } from './nodeDefinitions/contactsNodes';
// ============================================================================
// MAIN NODE REGISTRY - Combining all modular definitions
@@ -42,7 +47,12 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {
...documentNodes,
...socialNodes,
...twitterNodes,
- ...gmailNodes
+ ...gmailNodes,
+ ...calendarNodes,
+ ...driveNodes,
+ ...sheetsNodes,
+ ...tasksNodes,
+ ...contactsNodes
};
// ============================================================================
@@ -122,5 +132,25 @@ export const GMAIL_NODES = [
...GMAIL_NODE_TYPES
];
+export const CALENDAR_NODES = [
+ ...CALENDAR_NODE_TYPES
+];
+
+export const DRIVE_NODES = [
+ ...DRIVE_NODE_TYPES
+];
+
+export const SHEETS_NODES = [
+ ...SHEETS_NODE_TYPES
+];
+
+export const TASKS_NODES = [
+ ...TASKS_NODE_TYPES
+];
+
+export const CONTACTS_NODES = [
+ ...CONTACTS_NODE_TYPES
+];
+
// Re-export types and utilities from modular files for external access
export { createBaseChatModel } from './nodeDefinitions/aiModelNodes';
\ No newline at end of file
diff --git a/client/src/nodeDefinitions/calendarNodes.ts b/client/src/nodeDefinitions/calendarNodes.ts
new file mode 100644
index 00000000..5a8ecebd
--- /dev/null
+++ b/client/src/nodeDefinitions/calendarNodes.ts
@@ -0,0 +1,393 @@
+// Google Calendar Node Definitions - Google Calendar API integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+import { CALENDAR_ICON } from '../assets/icons/google';
+
+// ============================================================================
+// SHARED PROPERTIES
+// ============================================================================
+
+const ACCOUNT_MODE_PROPERTY = {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options' as const,
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Google account to use'
+};
+
+const CUSTOMER_ID_PROPERTY = {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Google connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+};
+
+const CALENDAR_ID_PROPERTY = {
+ displayName: 'Calendar ID',
+ name: 'calendar_id',
+ type: 'string' as const,
+ default: 'primary',
+ placeholder: 'primary or [email protected]',
+ description: 'Calendar ID (use "primary" for main calendar)'
+};
+
+// ============================================================================
+// CALENDAR NODES
+// ============================================================================
+
+export const calendarNodes: Record<string, INodeTypeDescription> = {
+ // Calendar Create - Create events
+ calendarCreate: {
+ displayName: 'Calendar Create',
+ name: 'calendarCreate',
+ icon: CALENDAR_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Create Event',
+ description: 'Create a calendar event via Google Calendar API',
+ defaults: { name: 'Calendar Create', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Event input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Created event (event_id, title, start, end, html_link)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== EVENT DETAILS =====
+ {
+ displayName: 'Title',
+ name: 'title',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Meeting with Team',
+ description: 'Event title/summary'
+ },
+ {
+ displayName: 'Start Time',
+ name: 'start_time',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '2026-02-22T14:00:00',
+ description: 'Start time in ISO format (e.g., 2026-02-22T14:00:00)'
+ },
+ {
+ displayName: 'End Time',
+ name: 'end_time',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '2026-02-22T15:00:00',
+ description: 'End time in ISO format'
+ },
+ {
+ displayName: 'Description',
+ name: 'description',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'Meeting agenda and notes...',
+ description: 'Event description (optional)'
+ },
+ {
+ displayName: 'Location',
+ name: 'location',
+ type: 'string',
+ default: '',
+ placeholder: 'Conference Room A or https://meet.google.com/...',
+ description: 'Event location (optional)'
+ },
+ {
+ displayName: 'Attendees',
+ name: 'attendees',
+ type: 'string',
+ default: '',
+ description: 'Attendee email addresses (comma-separated)'
+ },
+ {
+ displayName: 'Timezone',
+ name: 'timezone',
+ type: 'string',
+ default: 'UTC',
+ placeholder: 'America/New_York',
+ description: 'Timezone for the event (e.g., America/New_York, Europe/London)'
+ },
+ {
+ displayName: 'Reminder (minutes)',
+ name: 'reminder_minutes',
+ type: 'number',
+ default: 30,
+ typeOptions: { minValue: 0, maxValue: 40320 },
+ description: 'Minutes before event for popup reminder'
+ },
+ CALENDAR_ID_PROPERTY
+ ]
+ },
+
+ // Calendar List - List events
+ calendarList: {
+ displayName: 'Calendar List',
+ name: 'calendarList',
+ icon: CALENDAR_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'List Events',
+ description: 'List calendar events within a date range',
+ defaults: { name: 'Calendar List', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Query input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Events array with count'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== DATE RANGE =====
+ {
+ displayName: 'Start Date',
+ name: 'start_date',
+ type: 'string',
+ default: 'today',
+ placeholder: 'today or 2026-02-22T00:00:00Z',
+ description: 'Start date for query ("today" or ISO format)'
+ },
+ {
+ displayName: 'End Date',
+ name: 'end_date',
+ type: 'string',
+ default: 'today+7d',
+ placeholder: 'today+7d or 2026-02-29T23:59:59Z',
+ description: 'End date ("today+Nd" for N days from now, or ISO format)'
+ },
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 10,
+ typeOptions: { minValue: 1, maxValue: 250 },
+ description: 'Maximum number of events to return'
+ },
+ {
+ displayName: 'Expand Recurring',
+ name: 'single_events',
+ type: 'boolean',
+ default: true,
+ description: 'Expand recurring events into individual instances'
+ },
+ {
+ displayName: 'Order By',
+ name: 'order_by',
+ type: 'options',
+ options: [
+ { name: 'Start Time', value: 'startTime' },
+ { name: 'Last Updated', value: 'updated' }
+ ],
+ default: 'startTime',
+ description: 'Sort order for events'
+ },
+ CALENDAR_ID_PROPERTY
+ ]
+ },
+
+ // Calendar Update - Update events
+ calendarUpdate: {
+ displayName: 'Calendar Update',
+ name: 'calendarUpdate',
+ icon: CALENDAR_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Update Event',
+ description: 'Update an existing calendar event',
+ defaults: { name: 'Calendar Update', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Update input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Updated event details'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== EVENT IDENTIFICATION =====
+ {
+ displayName: 'Event ID',
+ name: 'event_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'abc123xyz',
+ description: 'ID of the event to update'
+ },
+
+ // ===== FIELDS TO UPDATE =====
+ {
+ displayName: 'Title',
+ name: 'title',
+ type: 'string',
+ default: '',
+ placeholder: 'New meeting title',
+ description: 'New event title (leave empty to keep current)'
+ },
+ {
+ displayName: 'Start Time',
+ name: 'start_time',
+ type: 'string',
+ default: '',
+ placeholder: '2026-02-22T14:00:00',
+ description: 'New start time (leave empty to keep current)'
+ },
+ {
+ displayName: 'End Time',
+ name: 'end_time',
+ type: 'string',
+ default: '',
+ placeholder: '2026-02-22T15:00:00',
+ description: 'New end time (leave empty to keep current)'
+ },
+ {
+ displayName: 'Description',
+ name: 'description',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'Updated description...',
+ description: 'New description (leave empty to keep current)'
+ },
+ {
+ displayName: 'Location',
+ name: 'location',
+ type: 'string',
+ default: '',
+ placeholder: 'New location',
+ description: 'New location (leave empty to keep current)'
+ },
+ CALENDAR_ID_PROPERTY
+ ]
+ },
+
+ // Calendar Delete - Delete events
+ calendarDelete: {
+ displayName: 'Calendar Delete',
+ name: 'calendarDelete',
+ icon: CALENDAR_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Delete Event',
+ description: 'Delete a calendar event',
+ defaults: { name: 'Calendar Delete', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Delete input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Deletion confirmation'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== EVENT IDENTIFICATION =====
+ {
+ displayName: 'Event ID',
+ name: 'event_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'abc123xyz',
+ description: 'ID of the event to delete'
+ },
+ {
+ displayName: 'Send Cancellation',
+ name: 'send_updates',
+ type: 'options',
+ options: [
+ { name: 'Send to All Attendees', value: 'all' },
+ { name: 'Do Not Send', value: 'none' }
+ ],
+ default: 'all',
+ description: 'Send cancellation emails to attendees'
+ },
+ CALENDAR_ID_PROPERTY
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const CALENDAR_NODE_TYPES = ['calendarCreate', 'calendarList', 'calendarUpdate', 'calendarDelete'];
diff --git a/client/src/nodeDefinitions/contactsNodes.ts b/client/src/nodeDefinitions/contactsNodes.ts
new file mode 100644
index 00000000..4d2436fa
--- /dev/null
+++ b/client/src/nodeDefinitions/contactsNodes.ts
@@ -0,0 +1,455 @@
+// Google Contacts Node Definitions - Google People API integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+import { CONTACTS_ICON } from '../assets/icons/google';
+
+// ============================================================================
+// SHARED PROPERTIES
+// ============================================================================
+
+const ACCOUNT_MODE_PROPERTY = {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options' as const,
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Google account to use'
+};
+
+const CUSTOMER_ID_PROPERTY = {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Google connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+};
+
+// ============================================================================
+// CONTACTS NODES
+// ============================================================================
+
+export const contactsNodes: Record<string, INodeTypeDescription> = {
+ // Contacts Create - Create a new contact
+ contactsCreate: {
+ displayName: 'Contacts Create',
+ name: 'contactsCreate',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Create Contact',
+ description: 'Create a new contact in Google Contacts',
+ defaults: { name: 'Contacts Create', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Contact input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Created contact (resource_name, display_name, email, phone)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== CONTACT DETAILS =====
+ {
+ displayName: 'First Name',
+ name: 'first_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'John',
+ description: 'First name (required)'
+ },
+ {
+ displayName: 'Last Name',
+ name: 'last_name',
+ type: 'string',
+ default: '',
+ placeholder: 'Doe',
+ description: 'Last name (optional)'
+ },
+ {
+ displayName: 'Email',
+ name: 'email',
+ type: 'string',
+ default: '',
+ placeholder: '[email protected]',
+ description: 'Email address (optional)'
+ },
+ {
+ displayName: 'Phone',
+ name: 'phone',
+ type: 'string',
+ default: '',
+ placeholder: '+1 555-123-4567',
+ description: 'Phone number (optional)'
+ },
+ {
+ displayName: 'Company',
+ name: 'company',
+ type: 'string',
+ default: '',
+ placeholder: 'Acme Inc.',
+ description: 'Company/organization name (optional)'
+ },
+ {
+ displayName: 'Job Title',
+ name: 'job_title',
+ type: 'string',
+ default: '',
+ placeholder: 'Software Engineer',
+ description: 'Job title (optional)'
+ },
+ {
+ displayName: 'Notes',
+ name: 'notes',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'Additional notes about this contact...',
+ description: 'Notes/biography (optional)'
+ }
+ ]
+ },
+
+ // Contacts List - List contacts
+ contactsList: {
+ displayName: 'Contacts List',
+ name: 'contactsList',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'List Contacts',
+ description: 'List contacts from Google Contacts',
+ defaults: { name: 'Contacts List', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Query input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Contacts array with count'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== LIST OPTIONS =====
+ {
+ displayName: 'Page Size',
+ name: 'page_size',
+ type: 'number',
+ default: 100,
+ typeOptions: { minValue: 1, maxValue: 1000 },
+ description: 'Number of contacts to return'
+ },
+ {
+ displayName: 'Sort Order',
+ name: 'sort_order',
+ type: 'options',
+ options: [
+ { name: 'Last Modified (Newest)', value: 'LAST_MODIFIED_DESCENDING' },
+ { name: 'Last Modified (Oldest)', value: 'LAST_MODIFIED_ASCENDING' },
+ { name: 'First Name (A-Z)', value: 'FIRST_NAME_ASCENDING' },
+ { name: 'Last Name (A-Z)', value: 'LAST_NAME_ASCENDING' }
+ ],
+ default: 'LAST_MODIFIED_DESCENDING',
+ description: 'Sort order for contacts'
+ },
+ {
+ displayName: 'Page Token',
+ name: 'page_token',
+ type: 'string',
+ default: '',
+ placeholder: 'Next page token from previous request',
+ description: 'Token for pagination (from previous request)'
+ }
+ ]
+ },
+
+ // Contacts Search - Search contacts
+ contactsSearch: {
+ displayName: 'Contacts Search',
+ name: 'contactsSearch',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Search Contacts',
+ description: 'Search contacts by name, email, or phone',
+ defaults: { name: 'Contacts Search', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Search input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Matching contacts array'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== SEARCH PARAMETERS =====
+ {
+ displayName: 'Query',
+ name: 'query',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'John or [email protected]',
+ description: 'Search query (name, email, phone)'
+ },
+ {
+ displayName: 'Max Results',
+ name: 'page_size',
+ type: 'number',
+ default: 30,
+ typeOptions: { minValue: 1, maxValue: 100 },
+ description: 'Maximum number of results'
+ }
+ ]
+ },
+
+ // Contacts Get - Get a specific contact
+ contactsGet: {
+ displayName: 'Contacts Get',
+ name: 'contactsGet',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Get Contact',
+ description: 'Get a specific contact by resource name',
+ defaults: { name: 'Contacts Get', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Contact input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Contact details'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== CONTACT IDENTIFICATION =====
+ {
+ displayName: 'Resource Name',
+ name: 'resource_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'people/c12345678',
+ description: 'Contact resource name (from list or search results)'
+ }
+ ]
+ },
+
+ // Contacts Update - Update an existing contact
+ contactsUpdate: {
+ displayName: 'Contacts Update',
+ name: 'contactsUpdate',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Update Contact',
+ description: 'Update an existing contact',
+ defaults: { name: 'Contacts Update', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Update input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Updated contact details'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== CONTACT IDENTIFICATION =====
+ {
+ displayName: 'Resource Name',
+ name: 'resource_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'people/c12345678',
+ description: 'Contact resource name to update'
+ },
+
+ // ===== FIELDS TO UPDATE =====
+ {
+ displayName: 'First Name',
+ name: 'first_name',
+ type: 'string',
+ default: '',
+ placeholder: 'John',
+ description: 'New first name (leave empty to keep current)'
+ },
+ {
+ displayName: 'Last Name',
+ name: 'last_name',
+ type: 'string',
+ default: '',
+ placeholder: 'Doe',
+ description: 'New last name (leave empty to keep current)'
+ },
+ {
+ displayName: 'Email',
+ name: 'email',
+ type: 'string',
+ default: '',
+ placeholder: '[email protected]',
+ description: 'New email (leave empty to keep current)'
+ },
+ {
+ displayName: 'Phone',
+ name: 'phone',
+ type: 'string',
+ default: '',
+ placeholder: '+1 555-123-4567',
+ description: 'New phone (leave empty to keep current)'
+ },
+ {
+ displayName: 'Company',
+ name: 'company',
+ type: 'string',
+ default: '',
+ placeholder: 'Acme Inc.',
+ description: 'New company (leave empty to keep current)'
+ },
+ {
+ displayName: 'Job Title',
+ name: 'job_title',
+ type: 'string',
+ default: '',
+ placeholder: 'Software Engineer',
+ description: 'New job title (leave empty to keep current)'
+ }
+ ]
+ },
+
+ // Contacts Delete - Delete a contact
+ contactsDelete: {
+ displayName: 'Contacts Delete',
+ name: 'contactsDelete',
+ icon: CONTACTS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Delete Contact',
+ description: 'Delete a contact from Google Contacts',
+ defaults: { name: 'Contacts Delete', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Delete input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Deletion confirmation'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== CONTACT IDENTIFICATION =====
+ {
+ displayName: 'Resource Name',
+ name: 'resource_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'people/c12345678',
+ description: 'Contact resource name to delete'
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const CONTACTS_NODE_TYPES = ['contactsCreate', 'contactsList', 'contactsSearch', 'contactsGet', 'contactsUpdate', 'contactsDelete'];
diff --git a/client/src/nodeDefinitions/driveNodes.ts b/client/src/nodeDefinitions/driveNodes.ts
new file mode 100644
index 00000000..5d6a9326
--- /dev/null
+++ b/client/src/nodeDefinitions/driveNodes.ts
@@ -0,0 +1,372 @@
+// Google Drive Node Definitions - Google Drive API integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+import { DRIVE_ICON } from '../assets/icons/google';
+
+// ============================================================================
+// SHARED PROPERTIES
+// ============================================================================
+
+const ACCOUNT_MODE_PROPERTY = {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options' as const,
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Google account to use'
+};
+
+const CUSTOMER_ID_PROPERTY = {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Google connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+};
+
+// ============================================================================
+// DRIVE NODES
+// ============================================================================
+
+export const driveNodes: Record<string, INodeTypeDescription> = {
+ // Drive Upload - Upload files
+ driveUpload: {
+ displayName: 'Drive Upload',
+ name: 'driveUpload',
+ icon: DRIVE_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Upload File',
+ description: 'Upload a file to Google Drive',
+ defaults: { name: 'Drive Upload', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'File input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Uploaded file (file_id, name, web_link)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== FILE SOURCE =====
+ {
+ displayName: 'File URL',
+ name: 'file_url',
+ type: 'string',
+ default: '',
+ placeholder: 'https://example.com/document.pdf',
+ description: 'URL to download file from (for remote files)'
+ },
+ {
+ displayName: 'File Content (Base64)',
+ name: 'file_content',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'SGVsbG8gV29ybGQh...',
+ description: 'Base64-encoded file content (alternative to URL)'
+ },
+ {
+ displayName: 'Filename',
+ name: 'filename',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'document.pdf',
+ description: 'Name for the uploaded file'
+ },
+ {
+ displayName: 'MIME Type',
+ name: 'mime_type',
+ type: 'string',
+ default: '',
+ placeholder: 'application/pdf',
+ description: 'File MIME type (auto-detected if empty)'
+ },
+
+ // ===== DESTINATION =====
+ {
+ displayName: 'Folder ID',
+ name: 'folder_id',
+ type: 'string',
+ default: '',
+ placeholder: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs',
+ description: 'Parent folder ID (leave empty for root)'
+ },
+ {
+ displayName: 'Description',
+ name: 'description',
+ type: 'string',
+ default: '',
+ placeholder: 'File description...',
+ description: 'File description (optional)'
+ }
+ ]
+ },
+
+ // Drive Download - Download files
+ driveDownload: {
+ displayName: 'Drive Download',
+ name: 'driveDownload',
+ icon: DRIVE_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Download File',
+ description: 'Download a file from Google Drive',
+ defaults: { name: 'Drive Download', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'File ID input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'File content (base64 or download URL)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== FILE IDENTIFICATION =====
+ {
+ displayName: 'File ID',
+ name: 'file_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs',
+ description: 'ID of the file to download'
+ },
+ {
+ displayName: 'Output Format',
+ name: 'output_format',
+ type: 'options',
+ options: [
+ { name: 'Base64 Content', value: 'base64' },
+ { name: 'Download URL', value: 'url' }
+ ],
+ default: 'base64',
+ description: 'How to return the file content'
+ }
+ ]
+ },
+
+ // Drive List - List files
+ driveList: {
+ displayName: 'Drive List',
+ name: 'driveList',
+ icon: DRIVE_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'List Files',
+ description: 'List files in Google Drive',
+ defaults: { name: 'Drive List', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Query input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Files array with metadata'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== SEARCH OPTIONS =====
+ {
+ displayName: 'Folder ID',
+ name: 'folder_id',
+ type: 'string',
+ default: '',
+ placeholder: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs',
+ description: 'List files in this folder (leave empty for all files)'
+ },
+ {
+ displayName: 'Search Query',
+ name: 'query',
+ type: 'string',
+ default: '',
+ placeholder: "name contains 'report'",
+ description: 'Drive search query (see Google Drive query syntax)'
+ },
+ {
+ displayName: 'File Type',
+ name: 'file_types',
+ type: 'options',
+ options: [
+ { name: 'All Files', value: 'all' },
+ { name: 'Folders Only', value: 'folder' },
+ { name: 'Documents', value: 'document' },
+ { name: 'Spreadsheets', value: 'spreadsheet' },
+ { name: 'Images', value: 'image' }
+ ],
+ default: 'all',
+ description: 'Filter by file type'
+ },
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 20,
+ typeOptions: { minValue: 1, maxValue: 1000 },
+ description: 'Maximum number of files to return'
+ },
+ {
+ displayName: 'Order By',
+ name: 'order_by',
+ type: 'options',
+ options: [
+ { name: 'Last Modified (Newest)', value: 'modifiedTime desc' },
+ { name: 'Last Modified (Oldest)', value: 'modifiedTime' },
+ { name: 'Created (Newest)', value: 'createdTime desc' },
+ { name: 'Created (Oldest)', value: 'createdTime' },
+ { name: 'Name (A-Z)', value: 'name' },
+ { name: 'Name (Z-A)', value: 'name desc' }
+ ],
+ default: 'modifiedTime desc',
+ description: 'Sort order for files'
+ }
+ ]
+ },
+
+ // Drive Share - Share files
+ driveShare: {
+ displayName: 'Drive Share',
+ name: 'driveShare',
+ icon: DRIVE_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Share File',
+ description: 'Share a file with another user',
+ defaults: { name: 'Drive Share', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Share input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Share result with permission details'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== FILE & RECIPIENT =====
+ {
+ displayName: 'File ID',
+ name: 'file_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs',
+ description: 'ID of the file to share'
+ },
+ {
+ displayName: 'Email',
+ name: 'email',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '[email protected]',
+ description: 'Email address to share with'
+ },
+ {
+ displayName: 'Role',
+ name: 'role',
+ type: 'options',
+ options: [
+ { name: 'Viewer (read-only)', value: 'reader' },
+ { name: 'Commenter (view + comment)', value: 'commenter' },
+ { name: 'Editor (full access)', value: 'writer' }
+ ],
+ default: 'reader',
+ description: 'Permission level for the user'
+ },
+ {
+ displayName: 'Send Notification',
+ name: 'send_notification',
+ type: 'boolean',
+ default: true,
+ description: 'Send email notification to the user'
+ },
+ {
+ displayName: 'Message',
+ name: 'message',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 2 },
+ placeholder: 'Here is the file you requested...',
+ description: 'Custom message for the notification email',
+ displayOptions: {
+ show: { send_notification: [true] }
+ }
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const DRIVE_NODE_TYPES = ['driveUpload', 'driveDownload', 'driveList', 'driveShare'];
diff --git a/client/src/nodeDefinitions/gmailNodes.ts b/client/src/nodeDefinitions/gmailNodes.ts
index 53e275d8..85620b15 100644
--- a/client/src/nodeDefinitions/gmailNodes.ts
+++ b/client/src/nodeDefinitions/gmailNodes.ts
@@ -3,20 +3,7 @@ import {
INodeTypeDescription,
NodeConnectionType
} from '../types/INodeProperties';
-import { Google } from '@lobehub/icons';
-import React from 'react';
-
-// ============================================================================
-// GMAIL ICON - Using @lobehub/icons Google brand icon
-// ============================================================================
-
-// Gmail uses Google brand icon from @lobehub/icons (Color variant)
-export const GmailIconComponent: React.FC<{ size?: number }> = ({ size = 28 }) => (
- React.createElement(Google.Color, { size })
-);
-
-// For node definitions, we use 'component:Gmail' as marker, resolved in SquareNode
-export const GMAIL_ICON = 'component:Gmail';
+import { GMAIL_ICON } from '../assets/icons/google';
// ============================================================================
// GMAIL NODES
diff --git a/client/src/nodeDefinitions/sheetsNodes.ts b/client/src/nodeDefinitions/sheetsNodes.ts
new file mode 100644
index 00000000..ed3d0809
--- /dev/null
+++ b/client/src/nodeDefinitions/sheetsNodes.ts
@@ -0,0 +1,276 @@
+// Google Sheets Node Definitions - Google Sheets API integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+import { SHEETS_ICON } from '../assets/icons/google';
+
+// ============================================================================
+// SHARED PROPERTIES
+// ============================================================================
+
+const ACCOUNT_MODE_PROPERTY = {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options' as const,
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Google account to use'
+};
+
+const CUSTOMER_ID_PROPERTY = {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Google connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+};
+
+const SPREADSHEET_ID_PROPERTY = {
+ displayName: 'Spreadsheet ID',
+ name: 'spreadsheet_id',
+ type: 'string' as const,
+ default: '',
+ required: true,
+ placeholder: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
+ description: 'ID from the spreadsheet URL (between /d/ and /edit)'
+};
+
+// ============================================================================
+// SHEETS NODES
+// ============================================================================
+
+export const sheetsNodes: Record<string, INodeTypeDescription> = {
+ // Sheets Read - Read data from spreadsheet
+ sheetsRead: {
+ displayName: 'Sheets Read',
+ name: 'sheetsRead',
+ icon: SHEETS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Read Data',
+ description: 'Read data from a Google Sheets spreadsheet',
+ defaults: { name: 'Sheets Read', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Query input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Values array with row/column count'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+ SPREADSHEET_ID_PROPERTY,
+
+ // ===== RANGE SELECTION =====
+ {
+ displayName: 'Range',
+ name: 'range',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Sheet1!A1:D10',
+ description: 'A1 notation range (e.g., "Sheet1!A1:D10" or "A:D")'
+ },
+ {
+ displayName: 'Value Render Option',
+ name: 'value_render_option',
+ type: 'options',
+ options: [
+ { name: 'Formatted Value', value: 'FORMATTED_VALUE' },
+ { name: 'Unformatted Value', value: 'UNFORMATTED_VALUE' },
+ { name: 'Formula', value: 'FORMULA' }
+ ],
+ default: 'FORMATTED_VALUE',
+ description: 'How values should be rendered in the output'
+ },
+ {
+ displayName: 'Major Dimension',
+ name: 'major_dimension',
+ type: 'options',
+ options: [
+ { name: 'Rows', value: 'ROWS' },
+ { name: 'Columns', value: 'COLUMNS' }
+ ],
+ default: 'ROWS',
+ description: 'Whether to return rows or columns first'
+ }
+ ]
+ },
+
+ // Sheets Write - Write data to spreadsheet
+ sheetsWrite: {
+ displayName: 'Sheets Write',
+ name: 'sheetsWrite',
+ icon: SHEETS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Write Data',
+ description: 'Write data to a Google Sheets spreadsheet',
+ defaults: { name: 'Sheets Write', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Data input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Update confirmation with cell count'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+ SPREADSHEET_ID_PROPERTY,
+
+ // ===== WRITE PARAMETERS =====
+ {
+ displayName: 'Range',
+ name: 'range',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Sheet1!A1',
+ description: 'Starting cell in A1 notation (e.g., "Sheet1!A1")'
+ },
+ {
+ displayName: 'Values',
+ name: 'values',
+ type: 'string',
+ default: '',
+ required: true,
+ typeOptions: { rows: 4 },
+ placeholder: '[["Name", "Age"], ["Alice", 25], ["Bob", 30]]',
+ description: '2D array of values in JSON format or {{input.data}}'
+ },
+ {
+ displayName: 'Value Input Option',
+ name: 'value_input_option',
+ type: 'options',
+ options: [
+ { name: 'User Entered', value: 'USER_ENTERED' },
+ { name: 'Raw', value: 'RAW' }
+ ],
+ default: 'USER_ENTERED',
+ description: 'How input values should be interpreted (USER_ENTERED parses formulas)'
+ }
+ ]
+ },
+
+ // Sheets Append - Append rows to spreadsheet
+ sheetsAppend: {
+ displayName: 'Sheets Append',
+ name: 'sheetsAppend',
+ icon: SHEETS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Append Rows',
+ description: 'Append rows to the end of a Google Sheets spreadsheet',
+ defaults: { name: 'Sheets Append', color: '#0F9D58' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Data input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Append confirmation with updated range'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+ SPREADSHEET_ID_PROPERTY,
+
+ // ===== APPEND PARAMETERS =====
+ {
+ displayName: 'Range',
+ name: 'range',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Sheet1!A:D',
+ description: 'Table range in A1 notation (e.g., "Sheet1!A:D")'
+ },
+ {
+ displayName: 'Values',
+ name: 'values',
+ type: 'string',
+ default: '',
+ required: true,
+ typeOptions: { rows: 4 },
+ placeholder: '[["Alice", 25, "[email protected]"]]',
+ description: '2D array of rows to append in JSON format'
+ },
+ {
+ displayName: 'Value Input Option',
+ name: 'value_input_option',
+ type: 'options',
+ options: [
+ { name: 'User Entered', value: 'USER_ENTERED' },
+ { name: 'Raw', value: 'RAW' }
+ ],
+ default: 'USER_ENTERED',
+ description: 'How input values should be interpreted'
+ },
+ {
+ displayName: 'Insert Data Option',
+ name: 'insert_data_option',
+ type: 'options',
+ options: [
+ { name: 'Insert Rows', value: 'INSERT_ROWS' },
+ { name: 'Overwrite', value: 'OVERWRITE' }
+ ],
+ default: 'INSERT_ROWS',
+ description: 'How the input data should be inserted'
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const SHEETS_NODE_TYPES = ['sheetsRead', 'sheetsWrite', 'sheetsAppend'];
diff --git a/client/src/nodeDefinitions/tasksNodes.ts b/client/src/nodeDefinitions/tasksNodes.ts
new file mode 100644
index 00000000..b4ed302e
--- /dev/null
+++ b/client/src/nodeDefinitions/tasksNodes.ts
@@ -0,0 +1,364 @@
+// Google Tasks Node Definitions - Google Tasks API integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+import { TASKS_ICON } from '../assets/icons/google';
+
+// ============================================================================
+// SHARED PROPERTIES
+// ============================================================================
+
+const ACCOUNT_MODE_PROPERTY = {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options' as const,
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Google account to use'
+};
+
+const CUSTOMER_ID_PROPERTY = {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Google connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+};
+
+const TASKLIST_ID_PROPERTY = {
+ displayName: 'Task List ID',
+ name: 'tasklist_id',
+ type: 'string' as const,
+ default: '@default',
+ placeholder: '@default or specific list ID',
+ description: 'Task list ID (use "@default" for primary list)'
+};
+
+// ============================================================================
+// TASKS NODES
+// ============================================================================
+
+export const tasksNodes: Record<string, INodeTypeDescription> = {
+ // Tasks Create - Create a new task
+ tasksCreate: {
+ displayName: 'Tasks Create',
+ name: 'tasksCreate',
+ icon: TASKS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Create Task',
+ description: 'Create a new task in Google Tasks',
+ defaults: { name: 'Tasks Create', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Task input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Created task (task_id, title, status)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== TASK DETAILS =====
+ {
+ displayName: 'Title',
+ name: 'title',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Buy groceries',
+ description: 'Task title'
+ },
+ {
+ displayName: 'Notes',
+ name: 'notes',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'Remember to check the shopping list...',
+ description: 'Task notes/description (optional)'
+ },
+ {
+ displayName: 'Due Date',
+ name: 'due_date',
+ type: 'string',
+ default: '',
+ placeholder: '2026-02-25 or 2026-02-25T10:00:00Z',
+ description: 'Due date (YYYY-MM-DD or RFC 3339 format)'
+ },
+ TASKLIST_ID_PROPERTY
+ ]
+ },
+
+ // Tasks List - List tasks
+ tasksList: {
+ displayName: 'Tasks List',
+ name: 'tasksList',
+ icon: TASKS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'List Tasks',
+ description: 'List tasks from a Google Tasks list',
+ defaults: { name: 'Tasks List', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Query input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Tasks array with count'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+ TASKLIST_ID_PROPERTY,
+
+ // ===== LIST OPTIONS =====
+ {
+ displayName: 'Show Completed',
+ name: 'show_completed',
+ type: 'boolean',
+ default: false,
+ description: 'Include completed tasks in the list'
+ },
+ {
+ displayName: 'Show Hidden',
+ name: 'show_hidden',
+ type: 'boolean',
+ default: false,
+ description: 'Include hidden tasks in the list'
+ },
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 100,
+ typeOptions: { minValue: 1, maxValue: 100 },
+ description: 'Maximum number of tasks to return'
+ }
+ ]
+ },
+
+ // Tasks Complete - Mark task as completed
+ tasksComplete: {
+ displayName: 'Tasks Complete',
+ name: 'tasksComplete',
+ icon: TASKS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Complete Task',
+ description: 'Mark a task as completed',
+ defaults: { name: 'Tasks Complete', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Task input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Completed task confirmation'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== TASK IDENTIFICATION =====
+ {
+ displayName: 'Task ID',
+ name: 'task_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'abc123xyz',
+ description: 'ID of the task to mark as completed'
+ },
+ TASKLIST_ID_PROPERTY
+ ]
+ },
+
+ // Tasks Update - Update an existing task
+ tasksUpdate: {
+ displayName: 'Tasks Update',
+ name: 'tasksUpdate',
+ icon: TASKS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Update Task',
+ description: 'Update an existing task',
+ defaults: { name: 'Tasks Update', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Update input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Updated task details'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== TASK IDENTIFICATION =====
+ {
+ displayName: 'Task ID',
+ name: 'task_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'abc123xyz',
+ description: 'ID of the task to update'
+ },
+
+ // ===== FIELDS TO UPDATE =====
+ {
+ displayName: 'Title',
+ name: 'title',
+ type: 'string',
+ default: '',
+ placeholder: 'New task title',
+ description: 'New title (leave empty to keep current)'
+ },
+ {
+ displayName: 'Notes',
+ name: 'notes',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'Updated notes...',
+ description: 'New notes (leave empty to keep current)'
+ },
+ {
+ displayName: 'Due Date',
+ name: 'due_date',
+ type: 'string',
+ default: '',
+ placeholder: '2026-02-25',
+ description: 'New due date (leave empty to keep current)'
+ },
+ {
+ displayName: 'Status',
+ name: 'status',
+ type: 'options',
+ options: [
+ { name: 'Keep Current', value: '' },
+ { name: 'Needs Action', value: 'needsAction' },
+ { name: 'Completed', value: 'completed' }
+ ],
+ default: '',
+ description: 'New status'
+ },
+ TASKLIST_ID_PROPERTY
+ ]
+ },
+
+ // Tasks Delete - Delete a task
+ tasksDelete: {
+ displayName: 'Tasks Delete',
+ name: 'tasksDelete',
+ icon: TASKS_ICON,
+ group: ['google', 'tool'],
+ version: 1,
+ subtitle: 'Delete Task',
+ description: 'Delete a task from Google Tasks',
+ defaults: { name: 'Tasks Delete', color: '#4285F4' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Delete input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Deletion confirmation'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ ACCOUNT_MODE_PROPERTY,
+ CUSTOMER_ID_PROPERTY,
+
+ // ===== TASK IDENTIFICATION =====
+ {
+ displayName: 'Task ID',
+ name: 'task_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'abc123xyz',
+ description: 'ID of the task to delete'
+ },
+ TASKLIST_ID_PROPERTY
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const TASKS_NODE_TYPES = ['tasksCreate', 'tasksList', 'tasksComplete', 'tasksUpdate', 'tasksDelete'];
diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.ts
index bf1c6ba4..e9a1f71a 100644
--- a/client/src/services/executionService.ts
+++ b/client/src/services/executionService.ts
@@ -6,6 +6,12 @@ import { UTILITY_NODE_TYPES } from '../nodeDefinitions/utilityNodes';
import { DOCUMENT_NODE_TYPES } from '../nodeDefinitions/documentNodes';
import { SPECIALIZED_AGENT_TYPES } from '../nodeDefinitions/specializedAgentNodes';
import { TWITTER_NODE_TYPES } from '../nodeDefinitions/twitterNodes';
+import { GMAIL_NODE_TYPES } from '../nodeDefinitions/gmailNodes';
+import { CALENDAR_NODE_TYPES } from '../nodeDefinitions/calendarNodes';
+import { DRIVE_NODE_TYPES } from '../nodeDefinitions/driveNodes';
+import { SHEETS_NODE_TYPES } from '../nodeDefinitions/sheetsNodes';
+import { TASKS_NODE_TYPES } from '../nodeDefinitions/tasksNodes';
+import { CONTACTS_NODE_TYPES } from '../nodeDefinitions/contactsNodes';
import { Node, Edge } from 'reactflow';
import { INodeExecutionData } from '../types/INodeProperties';
import { API_CONFIG } from '../config/api';
@@ -226,7 +232,14 @@ export class ExecutionService {
// Document Processing Nodes
...DOCUMENT_NODE_TYPES,
// Twitter/X Nodes
- ...TWITTER_NODE_TYPES
+ ...TWITTER_NODE_TYPES,
+ // Google Workspace Nodes
+ ...GMAIL_NODE_TYPES,
+ ...CALENDAR_NODE_TYPES,
+ ...DRIVE_NODE_TYPES,
+ ...SHEETS_NODE_TYPES,
+ ...TASKS_NODE_TYPES,
+ ...CONTACTS_NODE_TYPES
];
return supportedTypes.includes(nodeType);
diff --git a/client/src/vite-env.d.ts b/client/src/vite-env.d.ts
index 72ed8d4b..b32f5221 100644
--- a/client/src/vite-env.d.ts
+++ b/client/src/vite-env.d.ts
@@ -10,3 +10,9 @@ interface ImportMetaEnv {
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+
+// Allow importing SVG files as raw strings
+declare module '*.svg?raw' {
+ const content: string;
+ export default content;
+}
diff --git a/docs-internal/new_service_integration.md b/docs-internal/new_service_integration.md
new file mode 100644
index 00000000..49888d73
--- /dev/null
+++ b/docs-internal/new_service_integration.md
@@ -0,0 +1,1047 @@
+# New Service Integration Guide
+
+This guide provides a comprehensive walkthrough for integrating new external services (like Google Workspace, Slack, Notion, etc.) into MachinaOs. It covers OAuth authentication, database models, API handlers, frontend nodes, and AI Agent tool integration.
+
+## Overview
+
+A complete service integration includes:
+
+1. **OAuth Service** - Handle authentication with the external provider
+2. **Database Models** - Store OAuth tokens and connection state
+3. **API Handlers** - Execute service operations (CRUD)
+4. **Frontend Node Definitions** - Visual workflow nodes
+5. **AI Tool Schemas** - Enable LLM tool calling
+6. **Credentials Modal** - UI for managing connections
+7. **Pricing Configuration** - Cost tracking for API usage
+
+## Architecture Pattern
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Frontend │
+│ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ CredentialsModal│ │ Node Definitions │ │
+│ │ (OAuth UI) │ │ (calendarNodes) │ │
+│ └────────┬────────┘ └────────┬────────┘ │
+│ │ │ │
+└───────────│────────────────────│─────────────────────────────┘
+ │ WebSocket │ WebSocket
+ ▼ ▼
+┌───────────────────────────────────────────────────────────────┐
+│ Backend │
+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
+│ │ OAuth Router │ │ Node Executor│ │ WebSocket Handlers │ │
+│ │ (google.py) │ │ (registry) │ │ (oauth_login/status) │ │
+│ └──────┬───────┘ └──────┬───────┘ └──────────┬───────────┘ │
+│ │ │ │ │
+│ ▼ ▼ │ │
+│ ┌──────────────┐ ┌──────────────┐ │ │
+│ │ OAuth Service│ │ Handlers │ │ │
+│ │ (google_oauth│ │ (calendar.py)│◄────────────┘ │
+│ └──────┬───────┘ └──────┬───────┘ │
+│ │ │ │
+│ ▼ ▼ │
+│ ┌──────────────────────────────────┐ │
+│ │ Database (SQLModel) │ │
+│ │ - GoogleConnection │ │
+│ │ - Token storage via auth_service │ │
+│ └──────────────────────────────────┘ │
+└───────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌───────────────────────────────────────────────────────────────┐
+│ External Service API │
+│ (Google Calendar API, Slack API, Notion API, etc.) │
+└───────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## Step 1: OAuth Service
+
+Create `server/services/{service}_oauth.py`:
+
+```python
+"""
+{Service} OAuth 2.0 using appropriate library.
+
+Two access modes:
+1. Owner Mode - Your own account (Credentials Modal)
+2. Customer Mode - Customer's account (database storage)
+"""
+
+import time
+from typing import Any, Dict, List, Optional
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# Define scopes for all service capabilities
+SERVICE_SCOPES = [
+ "scope1",
+ "scope2",
+ # Add all scopes needed for your service
+]
+
+# In-memory state store (use Redis in production)
+_oauth_states: Dict[str, Dict[str, Any]] = {}
+
+
+class ServiceOAuth:
+ """OAuth 2.0 handler for {Service}."""
+
+ def __init__(
+ self,
+ client_id: str,
+ client_secret: str,
+ redirect_uri: str = "http://localhost:3010/api/{service}/callback",
+ scopes: Optional[List[str]] = None,
+ ):
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.redirect_uri = redirect_uri
+ self.scopes = scopes or SERVICE_SCOPES
+
+ def generate_authorization_url(
+ self,
+ state_data: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, str]:
+ """Generate OAuth authorization URL."""
+ # Generate unique state for CSRF protection
+ state = secrets.token_urlsafe(32)
+
+ # Store state data for callback verification
+ _oauth_states[state] = {
+ "created_at": time.time(),
+ "data": state_data or {"mode": "owner"},
+ }
+
+ # Build authorization URL
+ auth_url = f"https://provider.com/oauth/authorize?..."
+
+ return {"url": auth_url, "state": state}
+
+ def exchange_code(self, code: str, state: str) -> Dict[str, Any]:
+ """Exchange authorization code for tokens."""
+ # Verify state
+ oauth_state = _oauth_states.pop(state, None)
+ if not oauth_state:
+ return {"success": False, "error": "Invalid or expired state"}
+
+ try:
+ # Exchange code for tokens
+ # Get user info
+
+ return {
+ "success": True,
+ "access_token": "...",
+ "refresh_token": "...",
+ "email": "[email protected]",
+ "name": "User Name",
+ }
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+ @staticmethod
+ def refresh_credentials(
+ refresh_token: str,
+ client_id: str,
+ client_secret: str,
+ ) -> Dict[str, Any]:
+ """Refresh expired credentials."""
+ try:
+ # Refresh token
+ return {"success": True, "access_token": "..."}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
+def get_pending_state(state: str) -> Optional[Dict[str, Any]]:
+ """Get pending state without removing it."""
+ return _oauth_states.get(state)
+```
+
+**Key Points:**
+- Use in-memory state store for CSRF protection
+- Support both owner mode (single account) and customer mode (multi-tenant)
+- Implement token refresh for long-running connections
+- Log operations at appropriate levels
+
+---
+
+## Step 2: Database Models
+
+### 2.1 Connection Model (`server/models/database.py`)
+
+```python
+class ServiceConnection(SQLModel, table=True):
+ """OAuth connections for customer access mode."""
+
+ __tablename__ = "service_connections"
+
+ id: Optional[int] = Field(default=None, primary_key=True)
+ customer_id: str = Field(index=True, max_length=255)
+ email: str = Field(max_length=255)
+ name: Optional[str] = Field(default=None, max_length=255)
+ access_token: str = Field(max_length=2000)
+ refresh_token: str = Field(max_length=2000)
+ token_expiry: Optional[datetime] = Field(default=None)
+ scopes: str = Field(max_length=1000)
+ is_active: bool = Field(default=True)
+ last_used_at: Optional[datetime] = Field(default=None)
+ connected_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+ updated_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())
+ )
+```
+
+### 2.2 Database CRUD Methods (`server/core/database.py`)
+
+```python
+# Add import
+from models.database import ServiceConnection
+
+# Add CRUD methods
+async def save_service_connection(
+ self,
+ customer_id: str,
+ email: str,
+ access_token: str,
+ refresh_token: str,
+ scopes: str,
+ name: Optional[str] = None,
+) -> bool:
+ """Save or update a service connection for a customer."""
+ # Implementation...
+
+async def get_service_connection(self, customer_id: str) -> Optional[ServiceConnection]:
+ """Get service connection for a customer."""
+ # Implementation...
+
+async def delete_service_connection(self, customer_id: str) -> bool:
+ """Delete service connection for a customer."""
+ # Implementation...
+
+async def update_service_last_used(self, customer_id: str) -> bool:
+ """Update last_used_at timestamp."""
+ # Implementation...
+```
+
+### 2.3 Database Migration
+
+Add migration logic in `_migrate_user_settings()`:
+
+```python
+# In server/core/database.py - _migrate_user_settings()
+
+# Check if old table exists and migrate
+result = await conn.execute(text(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='old_table_name'"
+))
+old_exists = result.fetchone() is not None
+
+if old_exists:
+ await conn.execute(text("ALTER TABLE old_table_name RENAME TO new_table_name"))
+ logger.info("Migrated old_table_name to new_table_name")
+```
+
+---
+
+## Step 3: API Router
+
+Create `server/routers/{service}.py`:
+
+```python
+"""
+{Service} OAuth 2.0 callback and API routes.
+"""
+
+from typing import Optional
+from fastapi import APIRouter, Query
+from fastapi.responses import HTMLResponse, RedirectResponse
+
+from core.container import container
+from core.logging import get_logger
+from services.{service}_oauth import ServiceOAuth, get_pending_state
+
+logger = get_logger(__name__)
+router = APIRouter(prefix="/api/{service}", tags=["{service}"])
+
+
[email protected]("/callback")
+async def oauth_callback(
+ code: Optional[str] = Query(None),
+ state: Optional[str] = Query(None),
+ error: Optional[str] = Query(None),
+ error_description: Optional[str] = Query(None),
+):
+ """Handle OAuth callback from provider."""
+ # Handle errors
+ if error:
+ return HTMLResponse(content=_callback_html(success=False, error=error_description or error))
+
+ # Verify state
+ pending_state = get_pending_state(state)
+ if not pending_state:
+ return HTMLResponse(content=_callback_html(success=False, error="Invalid state"))
+
+ # Exchange code for tokens
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("{service}_client_id")
+ client_secret = await auth_service.get_api_key("{service}_client_secret")
+
+ oauth = ServiceOAuth(client_id=client_id, client_secret=client_secret)
+ result = oauth.exchange_code(code=code, state=state)
+
+ if not result.get("success"):
+ return HTMLResponse(content=_callback_html(success=False, error=result.get("error")))
+
+ # Store tokens
+ mode = pending_state.get("data", {}).get("mode", "owner")
+ if mode == "customer":
+ database = container.database()
+ await database.save_service_connection(...)
+ else:
+ await auth_service.store_api_key(provider="{service}_access_token", api_key=result["access_token"], models=[], session_id="default")
+ if result.get("refresh_token"):
+ await auth_service.store_api_key(provider="{service}_refresh_token", api_key=result["refresh_token"], models=[], session_id="default")
+
+ # Broadcast completion
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+ await broadcaster.broadcast({
+ "type": "{service}_oauth_complete",
+ "data": {"success": True, "email": result["email"]},
+ })
+
+ return HTMLResponse(content=_callback_html(success=True, email=result["email"]))
+
+
+async def get_status():
+ """Get connection status."""
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("{service}_access_token")
+
+ if not access_token:
+ return {"connected": False}
+
+ return {"connected": True, "email": "..."}
+
+
+async def logout():
+ """Disconnect service."""
+ auth_service = container.auth_service()
+ await auth_service.remove_api_key("{service}_access_token")
+ await auth_service.remove_api_key("{service}_refresh_token")
+ return {"success": True}
+
+
+def _callback_html(success: bool, email: str = None, error: str = None) -> str:
+ """Generate OAuth callback HTML page."""
+ # Return success/error HTML with auto-close script
+ ...
+```
+
+### Register Router
+
+In `server/main.py`:
+
+```python
+# Add to router imports
+from routers.{service} import router as {service}_router
+
+# Add to app
+app.include_router({service}_router)
+
+# Add to container wiring
+container.wire(modules=[
+ # ... existing modules
+ "routers.{service}",
+])
+```
+
+---
+
+## Step 4: WebSocket Handlers
+
+Add handlers in `server/routers/websocket.py`:
+
+```python
+@ws_handler()
+async def handle_{service}_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Initiate OAuth flow."""
+ import webbrowser
+ from services.{service}_oauth import ServiceOAuth
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("{service}_client_id")
+ client_secret = await auth_service.get_api_key("{service}_client_secret")
+
+ if not client_id or not client_secret:
+ return {"success": False, "error": "Service not configured"}
+
+ oauth = ServiceOAuth(client_id=client_id, client_secret=client_secret)
+ auth_data = oauth.generate_authorization_url()
+ webbrowser.open(auth_data["url"])
+
+ return {"success": True, "state": auth_data["state"]}
+
+
+@ws_handler()
+async def handle_{service}_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Check connection status."""
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("{service}_access_token")
+
+ if not access_token:
+ return {"connected": False}
+
+ return {"connected": True, "email": "..."}
+
+
+# Add to MESSAGE_HANDLERS dict
+MESSAGE_HANDLERS = {
+ # ... existing handlers
+ "{service}_oauth_login": handle_{service}_oauth_login,
+ "{service}_oauth_status": handle_{service}_oauth_status,
+}
+```
+
+---
+
+## Step 5: Service Handlers
+
+Create `server/services/handlers/{service}.py`:
+
+```python
+"""
+{Service} node handlers.
+
+Provides handlers for all {service} operations:
+- Operation 1
+- Operation 2
+- etc.
+"""
+
+import asyncio
+from typing import Any, Dict
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+async def _get_service(parameters: Dict[str, Any], context: Dict[str, Any]):
+ """Get authenticated service client."""
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ db = container.database()
+ connection = await db.get_service_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No connection for customer: {customer_id}")
+ access_token = connection.access_token
+ await db.update_service_last_used(customer_id)
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("{service}_access_token")
+ if not access_token:
+ raise ValueError("Service not connected. Please authenticate via Credentials.")
+
+ # Build and return service client
+ return build_client(access_token)
+
+
+async def handle_{operation1}(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle {operation1}."""
+ try:
+ service = await _get_service(parameters, context)
+
+ # Execute operation
+ result = await asyncio.get_event_loop().run_in_executor(
+ None, lambda: service.operation1().execute()
+ )
+
+ return {
+ "success": True,
+ "result": {...},
+ "node_id": node_id,
+ }
+ except Exception as e:
+ logger.error(f"{operation1} failed: {e}")
+ return {"success": False, "error": str(e), "node_id": node_id}
+
+
+# Add more handlers for each operation...
+```
+
+### Register Handlers
+
+In `server/services/node_executor.py`:
+
+```python
+# Add imports
+from services.handlers.{service} import (
+ handle_{operation1},
+ handle_{operation2},
+ # etc.
+)
+
+# Add to handler registry in _build_handler_registry()
+'{operation1}Node': handle_{operation1},
+'{operation2}Node': handle_{operation2},
+```
+
+---
+
+## Step 6: Frontend Node Definitions
+
+Create `client/src/nodeDefinitions/{service}Nodes.ts`:
+
+```typescript
+import { NodeDefinition, INodeProperties, NodeConnectionType } from '../types/INodeProperties';
+
+// Service icon (SVG or emoji)
+const SERVICE_ICON = `<svg>...</svg>`;
+
+// Service color
+const SERVICE_COLOR = '#4285F4';
+
+// Common service properties
+const SERVICE_COMMON_PROPS: INodeProperties[] = [
+ {
+ displayName: 'Account Mode',
+ name: 'account_mode',
+ type: 'options',
+ options: [
+ { name: 'Owner (My Account)', value: 'owner' },
+ { name: 'Customer', value: 'customer' },
+ ],
+ default: 'owner',
+ description: 'Whose account to use',
+ },
+ {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string',
+ default: '',
+ displayOptions: { show: { account_mode: ['customer'] } },
+ description: 'Customer identifier for multi-tenant mode',
+ },
+];
+
+export const {service}Nodes: Record<string, NodeDefinition> = {
+ {operation1}Node: {
+ displayName: '{Operation 1}',
+ name: '{operation1}Node',
+ icon: SERVICE_ICON,
+ group: ['{service}', 'tool'],
+ description: 'Description of operation 1',
+ defaults: {
+ name: '{Operation 1}',
+ color: SERVICE_COLOR,
+ },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType }],
+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType }],
+ properties: [
+ ...SERVICE_COMMON_PROPS,
+ // Operation-specific properties
+ {
+ displayName: 'Parameter 1',
+ name: 'param1',
+ type: 'string',
+ default: '',
+ required: true,
+ description: 'Description of parameter 1',
+ },
+ ],
+ },
+
+ // Add more operations...
+};
+
+// Export node type array for constants
+export const {SERVICE}_NODE_TYPES = Object.keys({service}Nodes);
+```
+
+### Register in nodeDefinitions.ts
+
+```typescript
+// client/src/nodeDefinitions.ts
+
+import { {service}Nodes, {SERVICE}_NODE_TYPES } from './nodeDefinitions/{service}Nodes';
+
+export const nodeDefinitions: NodeDefinitionRegistry = {
+ // ... existing nodes
+ ...{service}Nodes,
+};
+```
+
+### Add to Dashboard.tsx
+
+```typescript
+// In getNodeTypes()
+} else if (type.startsWith('{service}') || {SERVICE}_NODE_TYPES.includes(type)) {
+ types[type] = SquareNode;
+}
+```
+
+### Add to executionService.ts (Enable Run Button)
+
+```typescript
+// client/src/services/executionService.ts
+
+// Import node types
+import { {SERVICE}_NODE_TYPES } from '../nodeDefinitions/{service}Nodes';
+
+// Add to isNodeTypeSupported() supportedTypes array
+static isNodeTypeSupported(nodeType: string): boolean {
+ const supportedTypes = [
+ // ... existing types
+ // {Service} Nodes
+ ...{SERVICE}_NODE_TYPES,
+ ];
+ return supportedTypes.includes(nodeType);
+}
+```
+
+**Important:** Without this step, the Run button will not appear in the parameter panel for your new nodes.
+
+---
+
+## Step 7: AI Tool Schemas
+
+Add Pydantic schemas in `server/services/ai.py`:
+
+```python
+def _get_tool_schema(self, node_type: str, parameters: Dict[str, Any] = None):
+ """Get Pydantic schema for tool node."""
+
+ # ... existing schemas
+
+ # {Service} schemas
+ elif node_type == '{operation1}Node':
+ class Operation1Schema(BaseModel):
+ param1: str = Field(description="Description of param1")
+ param2: Optional[str] = Field(default=None, description="Optional param2")
+ return Operation1Schema
+```
+
+### Add Tool Dispatchers
+
+In `server/services/handlers/tools.py`:
+
+```python
+async def execute_tool(...):
+ # ... existing dispatchers
+
+ elif node_type == '{operation1}Node':
+ return await _execute_{operation1}(args, node_params)
+
+
+async def _execute_{operation1}(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute {operation1} via service handler."""
+ from services.handlers.{service} import handle_{operation1}
+
+ parameters = {**node_params, **args}
+ return await handle_{operation1}(
+ node_id="tool_{operation1}",
+ node_type="{operation1}Node",
+ parameters=parameters,
+ context={}
+ )
+```
+
+---
+
+## Step 8: Output Schemas
+
+Add output schemas in `client/src/components/parameterPanel/InputSection.tsx`:
+
+```typescript
+const sampleSchemas: Record<string, Record<string, string>> = {
+ // ... existing schemas
+
+ {service}: {
+ result_id: 'string',
+ field1: 'string',
+ field2: 'array',
+ timestamp: 'string',
+ },
+};
+
+// Add node type detection
+const {service}Types = ['{operation1}Node', '{operation2}Node'];
+const is{Service} = {service}Types.includes(nodeType);
+if (is{Service}) {
+ schema = sampleSchemas.{service};
+}
+```
+
+---
+
+## Step 9: Credentials Modal
+
+Update `client/src/components/CredentialsModal.tsx`:
+
+### Add to CATEGORIES
+
+```typescript
+const CATEGORIES = [
+ // ... existing categories
+ {
+ id: '{service}',
+ name: '{Service Name}',
+ placeholder: '',
+ color: '#4285F4',
+ desc: 'Service description',
+ CustomIcon: ServiceIcon,
+ isSpecial: true,
+ panelType: '{service}',
+ },
+];
+```
+
+### Add Icon Component
+
+```typescript
+const ServiceIcon = () => (
+ <svg viewBox="0 0 24 24" style={{ width: 20, height: 20 }}>
+ {/* SVG path */}
+ </svg>
+);
+```
+
+### Add OAuth Panel
+
+```typescript
+const render{Service}Panel = () => (
+ <div style={panelStyle}>
+ <div style={headerStyle}>
+ <ServiceIcon />
+ <span>{Service Name}</span>
+ {isConnected && <Tag color="green">Connected as {email}</Tag>}
+ </div>
+
+ {!isConnected ? (
+ <>
+ <Input
+ placeholder="Client ID"
+ value={clientId}
+ onChange={(e) => setClientId(e.target.value)}
+ />
+ <Input.Password
+ placeholder="Client Secret"
+ value={clientSecret}
+ onChange={(e) => setClientSecret(e.target.value)}
+ />
+ <Button onClick={handleSaveCredentials}>Save</Button>
+ <Button onClick={handleLogin} disabled={!clientId || !clientSecret}>
+ Login with {Service}
+ </Button>
+ </>
+ ) : (
+ <Button onClick={handleLogout}>Disconnect</Button>
+ )}
+ </div>
+);
+```
+
+---
+
+## Step 10: Pricing Configuration
+
+Add to `server/config/pricing.json`:
+
+```json
+{
+ "api": {
+ "{service}": {
+ "_description": "{Service} API pricing",
+ "_source": "https://provider.com/pricing",
+ "operation1": 0.001,
+ "operation2": 0.002
+ }
+ },
+ "operation_map": {
+ "{service}": {
+ "create": "operation1",
+ "list": "operation2"
+ }
+ }
+}
+```
+
+### Add Usage Tracking
+
+```python
+# In handler
+async def _track_{service}_usage(node_id: str, operation: str, count: int, ...):
+ """Track API usage for cost calculation."""
+ from services.pricing import get_pricing_service
+
+ pricing = get_pricing_service()
+ cost = pricing.calculate_api_cost("{service}", operation, count)
+
+ # Store to database
+ ...
+```
+
+---
+
+## Step 11: WebSocket Context Updates
+
+Update `client/src/contexts/WebSocketContext.tsx`:
+
+```typescript
+// Add state
+const [{service}Status, set{Service}Status] = useState<ServiceStatus>({
+ connected: false,
+ email: null,
+});
+
+// Add message handler
+case '{service}_oauth_complete':
+ if (data?.success) {
+ set{Service}Status({
+ connected: true,
+ email: data.email,
+ });
+ }
+ break;
+
+// Export in context value
+{service}Status,
+```
+
+---
+
+## Example: Google Workspace Integration
+
+The Google Workspace integration demonstrates this pattern with:
+
+### Files Created
+
+| File | Purpose |
+|------|---------|
+| `server/services/google_oauth.py` | OAuth 2.0 with google-auth-oauthlib |
+| `server/services/handlers/calendar.py` | Calendar CRUD handlers |
+| `server/services/handlers/drive.py` | Drive file handlers |
+| `server/services/handlers/sheets.py` | Sheets data handlers |
+| `server/services/handlers/tasks.py` | Tasks CRUD handlers |
+| `server/services/handlers/contacts.py` | Contacts handlers |
+| `server/config/google_apis.json` | API endpoints and scopes |
+| `client/src/nodeDefinitions/calendarNodes.ts` | Calendar node definitions |
+| `client/src/nodeDefinitions/driveNodes.ts` | Drive node definitions |
+| `client/src/nodeDefinitions/sheetsNodes.ts` | Sheets node definitions |
+| `client/src/nodeDefinitions/tasksNodes.ts` | Tasks node definitions |
+| `client/src/nodeDefinitions/contactsNodes.ts` | Contacts node definitions |
+
+### Files Modified
+
+| File | Changes |
+|------|---------|
+| `server/models/database.py` | Added `GoogleConnection` model |
+| `server/core/database.py` | Added CRUD methods, migration logic |
+| `server/services/node_executor.py` | Added handler registry entries |
+| `server/services/ai.py` | Added Pydantic schemas for AI tools |
+| `server/services/handlers/tools.py` | Added tool dispatchers |
+| `server/config/pricing.json` | Added Google API pricing |
+| `client/src/nodeDefinitions.ts` | Imported all Google node definitions |
+| `client/src/components/CredentialsModal.tsx` | Added Google Workspace panel |
+| `client/src/components/parameterPanel/InputSection.tsx` | Added output schemas |
+| `client/src/Dashboard.tsx` | Added node type mappings |
+| `client/src/contexts/WebSocketContext.tsx` | Added OAuth complete handler |
+
+### Combined OAuth Scopes
+
+```python
+GOOGLE_WORKSPACE_SCOPES = [
+ # User Info
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile",
+ # Gmail
+ "https://www.googleapis.com/auth/gmail.send",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/gmail.modify",
+ # Calendar
+ "https://www.googleapis.com/auth/calendar",
+ "https://www.googleapis.com/auth/calendar.events",
+ # Drive
+ "https://www.googleapis.com/auth/drive",
+ "https://www.googleapis.com/auth/drive.file",
+ # Sheets
+ "https://www.googleapis.com/auth/spreadsheets",
+ # Tasks
+ "https://www.googleapis.com/auth/tasks",
+ # Contacts
+ "https://www.googleapis.com/auth/contacts",
+ "https://www.googleapis.com/auth/contacts.readonly",
+]
+```
+
+---
+
+## Checklist
+
+Use this checklist when adding a new service:
+
+- [ ] **OAuth Service** (`server/services/{service}_oauth.py`)
+ - [ ] Define scopes
+ - [ ] Implement `generate_authorization_url()`
+ - [ ] Implement `exchange_code()`
+ - [ ] Implement `refresh_credentials()`
+ - [ ] Add `get_pending_state()` helper
+
+- [ ] **Database** (`server/models/database.py`, `server/core/database.py`)
+ - [ ] Add `ServiceConnection` model
+ - [ ] Add import to `core/database.py`
+ - [ ] Add CRUD methods (save, get, delete, update_last_used)
+ - [ ] Add migration for table rename if needed
+
+- [ ] **API Router** (`server/routers/{service}.py`)
+ - [ ] Add callback endpoint
+ - [ ] Add status endpoint
+ - [ ] Add logout endpoint
+ - [ ] Add customer endpoints if needed
+ - [ ] Register in `main.py`
+ - [ ] Add to container wiring
+
+- [ ] **WebSocket Handlers** (`server/routers/websocket.py`)
+ - [ ] Add `handle_{service}_oauth_login`
+ - [ ] Add `handle_{service}_oauth_status`
+ - [ ] Add to MESSAGE_HANDLERS dict
+
+- [ ] **Service Handlers** (`server/services/handlers/{service}.py`)
+ - [ ] Add `_get_service()` helper
+ - [ ] Add handler for each operation
+ - [ ] Register in node_executor.py
+
+- [ ] **Frontend Nodes** (`client/src/nodeDefinitions/{service}Nodes.ts`)
+ - [ ] Define common properties
+ - [ ] Add node definition for each operation
+ - [ ] Export node types array
+ - [ ] Import in `nodeDefinitions.ts`
+ - [ ] Add to Dashboard.tsx
+ - [ ] Add to `executionService.ts` `isNodeTypeSupported()` (enables Run button)
+
+- [ ] **AI Tool Integration** (`server/services/ai.py`, `server/services/handlers/tools.py`)
+ - [ ] Add Pydantic schemas in `_get_tool_schema()`
+ - [ ] Add dispatchers in `execute_tool()`
+ - [ ] Add handler functions
+
+- [ ] **Output Schemas** (`client/src/components/parameterPanel/InputSection.tsx`)
+ - [ ] Add output schema for drag-and-drop variables
+
+- [ ] **Credentials Modal** (`client/src/components/CredentialsModal.tsx`)
+ - [ ] Add to CATEGORIES
+ - [ ] Add icon component
+ - [ ] Add OAuth panel rendering
+
+- [ ] **WebSocket Context** (`client/src/contexts/WebSocketContext.tsx`)
+ - [ ] Add OAuth complete handler
+ - [ ] Add state if needed
+
+- [ ] **Pricing** (`server/config/pricing.json`)
+ - [ ] Add service pricing
+ - [ ] Add operation map
+ - [ ] Add URL patterns if using tracked HTTP
+
+- [ ] **Skills** (`server/skills/{agent_type}/`)
+ - [ ] Create skill folder (e.g., `productivity_agent/`)
+ - [ ] Add SKILL.md for each service capability
+ - [ ] Define allowed-tools in frontmatter
+ - [ ] Update GUIDE.md folder structure
+
+---
+
+## Best Practices
+
+1. **Use Existing Patterns** - Follow the Google Workspace implementation as a template
+2. **Unified OAuth** - If a provider has multiple services, use combined scopes
+3. **Dual-Purpose Nodes** - Add `group: ['{service}', 'tool']` for AI Agent integration
+4. **Error Handling** - Always catch and log errors, return proper error responses
+5. **Token Refresh** - Implement automatic token refresh for long-running workflows
+6. **Cost Tracking** - Add pricing config and track usage for billing
+7. **Documentation** - Update CLAUDE.md with the new service section
+8. **Skills** - Create skills for AI agents to use service operations with proper instructions
+
+---
+
+## Step 12: AI Agent Skills (Optional but Recommended)
+
+Create skills for AI agents to use the service operations.
+
+### Skill Folder Structure
+
+```
+server/skills/{agent_type}/
+├── {service}-skill/
+│ └── SKILL.md
+```
+
+For Google Workspace, the skills are in `server/skills/productivity_agent/`:
+- `gmail-skill/SKILL.md`
+- `calendar-skill/SKILL.md`
+- `drive-skill/SKILL.md`
+- `sheets-skill/SKILL.md`
+- `tasks-skill/SKILL.md`
+- `contacts-skill/SKILL.md`
+
+### Skill File Format
+
+```markdown
+---
+name: {service}-skill
+description: Brief description of capabilities
+allowed-tools: tool1 tool2 tool3
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "icon"
+ color: "#HEXCOLOR"
+---
+
+# {Service} Skill
+
+Description of what the skill provides.
+
+## Available Tools
+
+### tool_name
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| param1 | string | Yes | Description |
+
+**Example:**
+```json
+{
+ "param1": "value"
+}
+```
+
+## Setup Requirements
+
+1. Connect nodes to AI Agent's `input-tools` handle
+2. Authenticate in Credentials Modal
+```
+
+See `server/skills/GUIDE.md` for full documentation on skill creation.
diff --git a/docs-internal/server-readme.md b/docs-internal/server-readme.md
index bf4e4ef2..e65feed3 100644
--- a/docs-internal/server-readme.md
+++ b/docs-internal/server-readme.md
@@ -71,3 +71,46 @@ All API keys should be:
- `.env.example` - Full example with all options (committed to git)
- `.env.development` - Development environment (git-ignored)
- `.env.production` - Production environment (git-ignored)
+
+## Google Workspace Integration
+
+Google Workspace services (Gmail, Calendar, Drive, Sheets, Tasks, Contacts) share a single OAuth connection.
+
+### Setup
+
+1. Create a Google Cloud project and enable the required APIs
+2. Create OAuth 2.0 credentials (Web Application type)
+3. Add credentials via the Credentials Modal in the UI
+4. Click "Login with Google" to authenticate
+
+### Environment Variables (Optional)
+
+```bash
+# Custom OAuth redirect URI (defaults to localhost:3010)
+GOOGLE_REDIRECT_URI=http://localhost:3010/api/google/callback
+```
+
+### Token Storage
+
+All Google tokens use the `google_*` prefix:
+- `google_client_id` - OAuth Client ID
+- `google_client_secret` - OAuth Client Secret
+- `google_access_token` - Access token for API calls
+- `google_refresh_token` - Refresh token for renewal
+- `google_user_info` - Connected user email and name
+
+### API Handlers
+
+| Service | Handler File | Node Types |
+|---------|-------------|------------|
+| Gmail | `handlers/gmail.py` | gmailSend, gmailSearch, gmailRead, gmailReceive |
+| Calendar | `handlers/calendar.py` | calendarCreate, calendarList, calendarUpdate, calendarDelete |
+| Drive | `handlers/drive.py` | driveUpload, driveDownload, driveList, driveShare |
+| Sheets | `handlers/sheets.py` | sheetsRead, sheetsWrite, sheetsAppend |
+| Tasks | `handlers/tasks.py` | tasksCreate, tasksList, tasksComplete |
+| Contacts | `handlers/contacts.py` | contactsCreate, contactsList, contactsSearch |
+
+### AI Agent Skills
+
+Skills for AI agents are in `server/skills/productivity_agent/`:
+- gmail-skill, calendar-skill, drive-skill, sheets-skill, tasks-skill, contacts-skill
diff --git a/server/config/google_apis.json b/server/config/google_apis.json
new file mode 100644
index 00000000..0f2302f2
--- /dev/null
+++ b/server/config/google_apis.json
@@ -0,0 +1,116 @@
+{
+ "version": "2026.02",
+ "last_updated": "2026-02-22",
+ "_source": "https://developers.google.com/workspace",
+
+ "oauth": {
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "revoke_uri": "https://oauth2.googleapis.com/revoke",
+ "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo"
+ },
+
+ "services": {
+ "gmail": {
+ "name": "Gmail API",
+ "version": "v1",
+ "base_url": "https://gmail.googleapis.com",
+ "discovery_url": "https://gmail.googleapis.com/$discovery/rest?version=v1",
+ "documentation": "https://developers.google.com/gmail/api/reference/rest"
+ },
+ "calendar": {
+ "name": "Google Calendar API",
+ "version": "v3",
+ "base_url": "https://www.googleapis.com/calendar/v3",
+ "discovery_url": "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
+ "documentation": "https://developers.google.com/workspace/calendar/api/v3/reference"
+ },
+ "drive": {
+ "name": "Google Drive API",
+ "version": "v3",
+ "base_url": "https://www.googleapis.com/drive/v3",
+ "discovery_url": "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest",
+ "documentation": "https://developers.google.com/drive/api/v3/reference"
+ },
+ "sheets": {
+ "name": "Google Sheets API",
+ "version": "v4",
+ "base_url": "https://sheets.googleapis.com/v4",
+ "discovery_url": "https://sheets.googleapis.com/$discovery/rest?version=v4",
+ "documentation": "https://developers.google.com/workspace/sheets/api/reference/rest"
+ },
+ "tasks": {
+ "name": "Google Tasks API",
+ "version": "v1",
+ "base_url": "https://tasks.googleapis.com/tasks/v1",
+ "discovery_url": "https://www.googleapis.com/discovery/v1/apis/tasks/v1/rest",
+ "documentation": "https://developers.google.com/workspace/tasks/reference/rest"
+ },
+ "people": {
+ "name": "Google People API (Contacts)",
+ "version": "v1",
+ "base_url": "https://people.googleapis.com/v1",
+ "discovery_url": "https://people.googleapis.com/$discovery/rest?version=v1",
+ "documentation": "https://developers.google.com/people/api/rest"
+ }
+ },
+
+ "scopes": {
+ "userinfo": [
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile"
+ ],
+ "gmail": [
+ "https://www.googleapis.com/auth/gmail.send",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/gmail.modify"
+ ],
+ "calendar": [
+ "https://www.googleapis.com/auth/calendar",
+ "https://www.googleapis.com/auth/calendar.events"
+ ],
+ "drive": [
+ "https://www.googleapis.com/auth/drive",
+ "https://www.googleapis.com/auth/drive.file"
+ ],
+ "sheets": [
+ "https://www.googleapis.com/auth/spreadsheets"
+ ],
+ "tasks": [
+ "https://www.googleapis.com/auth/tasks"
+ ],
+ "contacts": [
+ "https://www.googleapis.com/auth/contacts",
+ "https://www.googleapis.com/auth/contacts.readonly"
+ ]
+ },
+
+ "rate_limits": {
+ "_note": "All Google Workspace APIs are free with rate limits",
+ "gmail": {
+ "quota_units_per_second": 250,
+ "daily_limit": "Unlimited (within quota)"
+ },
+ "calendar": {
+ "requests_per_minute": 1000000,
+ "requests_per_day": "Unlimited"
+ },
+ "drive": {
+ "requests_per_100_seconds": 20000,
+ "requests_per_day": 1000000000
+ },
+ "sheets": {
+ "read_requests_per_minute": 300,
+ "write_requests_per_minute": 300
+ },
+ "tasks": {
+ "requests_per_minute": 150000,
+ "requests_per_day": 50000
+ },
+ "people": {
+ "requests_per_minute": 90,
+ "contacts_per_page": 1000
+ }
+ }
+}
diff --git a/server/config/pricing.json b/server/config/pricing.json
index 65d021c7..3a8d9210 100644
--- a/server/config/pricing.json
+++ b/server/config/pricing.json
@@ -121,6 +121,70 @@
"attachment_read": 0.0,
"_default": 0.0
},
+ "google_calendar": {
+ "_description": "Google Calendar API (free tier)",
+ "_source": "https://developers.google.com/workspace/calendar/api/guides/quota",
+ "_note": "Free API - costs are $0. Rate limit: 1M requests/min",
+ "event_create": 0.0,
+ "event_read": 0.0,
+ "event_update": 0.0,
+ "event_delete": 0.0,
+ "event_list": 0.0,
+ "calendar_list": 0.0,
+ "freebusy_query": 0.0,
+ "_default": 0.0
+ },
+ "google_drive": {
+ "_description": "Google Drive API (free tier)",
+ "_source": "https://developers.google.com/drive/api/guides/limits",
+ "_note": "Free API - costs are $0. Rate limit: 20K requests/100s",
+ "file_upload": 0.0,
+ "file_download": 0.0,
+ "file_list": 0.0,
+ "file_share": 0.0,
+ "file_copy": 0.0,
+ "file_delete": 0.0,
+ "file_metadata": 0.0,
+ "permission_create": 0.0,
+ "_default": 0.0
+ },
+ "google_sheets": {
+ "_description": "Google Sheets API (free tier)",
+ "_source": "https://developers.google.com/workspace/sheets/api/limits",
+ "_note": "Free API - costs are $0. Rate limit: 300 requests/min",
+ "values_read": 0.0,
+ "values_write": 0.0,
+ "values_append": 0.0,
+ "spreadsheet_create": 0.0,
+ "spreadsheet_get": 0.0,
+ "sheet_add": 0.0,
+ "_default": 0.0
+ },
+ "google_tasks": {
+ "_description": "Google Tasks API (free tier)",
+ "_source": "https://developers.google.com/workspace/tasks/reference/rest",
+ "_note": "Free API - costs are $0. Rate limit: 150K requests/min",
+ "task_create": 0.0,
+ "task_read": 0.0,
+ "task_update": 0.0,
+ "task_delete": 0.0,
+ "task_list": 0.0,
+ "tasklist_create": 0.0,
+ "tasklist_list": 0.0,
+ "_default": 0.0
+ },
+ "google_contacts": {
+ "_description": "Google People API for Contacts (free tier)",
+ "_source": "https://developers.google.com/people/api/rest",
+ "_note": "Free API - costs are $0. Rate limit: 90 requests/min",
+ "contact_create": 0.0,
+ "contact_read": 0.0,
+ "contact_update": 0.0,
+ "contact_delete": 0.0,
+ "contact_list": 0.0,
+ "contact_search": 0.0,
+ "_default": 0.0
+ },
"twitter": {
"_description": "X/Twitter Pay-Per-Use API pricing (per resource/request)",
"_source": "https://developer.x.com/#pricing",
@@ -191,6 +255,51 @@
"threads": "thread_list",
"draft": "draft_create",
"attachment": "attachment_read"
+ },
+ "google_calendar": {
+ "create": "event_create",
+ "read": "event_read",
+ "update": "event_update",
+ "delete": "event_delete",
+ "list": "event_list",
+ "calendars": "calendar_list",
+ "freebusy": "freebusy_query"
+ },
+ "google_drive": {
+ "upload": "file_upload",
+ "download": "file_download",
+ "list": "file_list",
+ "share": "file_share",
+ "copy": "file_copy",
+ "delete": "file_delete",
+ "metadata": "file_metadata",
+ "permission": "permission_create"
+ },
+ "google_sheets": {
+ "read": "values_read",
+ "write": "values_write",
+ "append": "values_append",
+ "create": "spreadsheet_create",
+ "get": "spreadsheet_get",
+ "add_sheet": "sheet_add"
+ },
+ "google_tasks": {
+ "create": "task_create",
+ "read": "task_read",
+ "update": "task_update",
+ "delete": "task_delete",
+ "list": "task_list",
+ "create_list": "tasklist_create",
+ "list_tasklists": "tasklist_list",
+ "complete": "task_update"
+ },
+ "google_contacts": {
+ "create": "contact_create",
+ "read": "contact_read",
+ "update": "contact_update",
+ "delete": "contact_delete",
+ "list": "contact_list",
+ "search": "contact_search"
}
},
diff --git a/server/core/config.py b/server/core/config.py
index c718ee70..da2fbc8a 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -74,7 +74,8 @@ class Settings(BaseSettings):
websocket_api_key: Optional[str] = Field(default=None, env="WEBSOCKET_API_KEY")
# OAuth Redirect URIs
- gmail_redirect_uri: str = Field(default="http://localhost:3010/api/gmail/callback", env="GMAIL_REDIRECT_URI")
+ google_redirect_uri: str = Field(default="http://localhost:3010/api/google/callback", env="GOOGLE_REDIRECT_URI")
+ gmail_redirect_uri: str = Field(default="http://localhost:3010/api/gmail/callback", env="GMAIL_REDIRECT_URI") # Deprecated: use google_redirect_uri
twitter_redirect_uri: str = Field(default="http://localhost:3010/api/twitter/callback", env="TWITTER_REDIRECT_URI")
# Android Relay Configuration (passed to Vite frontend)
diff --git a/server/core/database.py b/server/core/database.py
index b4c9bcf7..db3f4964 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -13,7 +13,7 @@ from models.database import (
NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput,
ConversationMessage, ToolSchema, UserSkill, ChatMessage, UserSettings,
TokenUsageMetric, CompactionEvent, SessionTokenState, ProviderDefaults,
- AgentTeam, TeamMember, TeamTask, AgentMessage, GmailConnection
+ AgentTeam, TeamMember, TeamTask, AgentMessage, GoogleConnection
)
from models.cache import CacheEntry # SQLite-backed cache for Redis alternative
from models.auth import User # Import User model to ensure table creation
@@ -134,6 +134,24 @@ class Database:
))
logger.info("Ensured api_usage_metrics table exists")
+ # Migrate gmail_connections to google_connections
+ # Check if old table exists and new table doesn't
+ result = await conn.execute(text(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='gmail_connections'"
+ ))
+ old_table_exists = result.fetchone() is not None
+
+ result = await conn.execute(text(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='google_connections'"
+ ))
+ new_table_exists = result.fetchone() is not None
+
+ if old_table_exists and not new_table_exists:
+ await conn.execute(text(
+ "ALTER TABLE gmail_connections RENAME TO google_connections"
+ ))
+ logger.info("Migrated gmail_connections table to google_connections")
+
except Exception as e:
logger.warning(f"Migration check failed (table may not exist yet): {e}")
@@ -2352,10 +2370,10 @@ class Database:
return {"error": str(e)}
# ============================================================================
- # Gmail Connections - Customer Mode OAuth Storage
+ # Google Connections - Customer Mode OAuth Storage
# ============================================================================
- async def save_gmail_connection(
+ async def save_google_connection(
self,
customer_id: str,
email: str,
@@ -2364,12 +2382,12 @@ class Database:
scopes: str,
name: Optional[str] = None,
) -> bool:
- """Save or update a Gmail connection for a customer."""
+ """Save or update a Google Workspace connection for a customer."""
try:
async with self.get_session() as session:
# Check if connection exists
result = await session.execute(
- select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ select(GoogleConnection).where(GoogleConnection.customer_id == customer_id)
)
existing = result.scalar_one_or_none()
@@ -2385,7 +2403,7 @@ class Database:
existing.updated_at = now
else:
# Create new connection
- connection = GmailConnection(
+ connection = GoogleConnection(
customer_id=customer_id,
email=email,
name=name,
@@ -2399,52 +2417,52 @@ class Database:
session.add(connection)
await session.commit()
- logger.info(f"Saved Gmail connection for customer {customer_id}")
+ logger.info(f"Saved Google connection for customer {customer_id}")
return True
except Exception as e:
- logger.error(f"Failed to save Gmail connection: {e}")
+ logger.error(f"Failed to save Google connection: {e}")
return False
- async def get_gmail_connection(self, customer_id: str) -> Optional[GmailConnection]:
- """Get Gmail connection for a customer."""
+ async def get_google_connection(self, customer_id: str) -> Optional[GoogleConnection]:
+ """Get Google Workspace connection for a customer."""
try:
async with self.get_session() as session:
result = await session.execute(
- select(GmailConnection).where(
- GmailConnection.customer_id == customer_id,
- GmailConnection.is_active == True
+ select(GoogleConnection).where(
+ GoogleConnection.customer_id == customer_id,
+ GoogleConnection.is_active == True
)
)
return result.scalar_one_or_none()
except Exception as e:
- logger.error(f"Failed to get Gmail connection: {e}")
+ logger.error(f"Failed to get Google connection: {e}")
return None
- async def delete_gmail_connection(self, customer_id: str) -> bool:
- """Delete Gmail connection for a customer."""
+ async def delete_google_connection(self, customer_id: str) -> bool:
+ """Delete Google Workspace connection for a customer."""
try:
async with self.get_session() as session:
result = await session.execute(
- select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ select(GoogleConnection).where(GoogleConnection.customer_id == customer_id)
)
connection = result.scalar_one_or_none()
if connection:
await session.delete(connection)
await session.commit()
- logger.info(f"Deleted Gmail connection for customer {customer_id}")
+ logger.info(f"Deleted Google connection for customer {customer_id}")
return True
except Exception as e:
- logger.error(f"Failed to delete Gmail connection: {e}")
+ logger.error(f"Failed to delete Google connection: {e}")
return False
- async def list_gmail_connections(self, limit: int = 100) -> List[Dict[str, Any]]:
- """List all Gmail connections."""
+ async def list_google_connections(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """List all Google Workspace connections."""
try:
async with self.get_session() as session:
result = await session.execute(
- select(GmailConnection)
- .where(GmailConnection.is_active == True)
- .order_by(GmailConnection.connected_at.desc())
+ select(GoogleConnection)
+ .where(GoogleConnection.is_active == True)
+ .order_by(GoogleConnection.connected_at.desc())
.limit(limit)
)
connections = result.scalars().all()
@@ -2459,20 +2477,20 @@ class Database:
for c in connections
]
except Exception as e:
- logger.error(f"Failed to list Gmail connections: {e}")
+ logger.error(f"Failed to list Google connections: {e}")
return []
- async def update_gmail_connection_tokens(
+ async def update_google_connection_tokens(
self,
customer_id: str,
access_token: str,
refresh_token: Optional[str] = None,
) -> bool:
- """Update tokens for a Gmail connection (after refresh)."""
+ """Update tokens for a Google Workspace connection (after refresh)."""
try:
async with self.get_session() as session:
result = await session.execute(
- select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ select(GoogleConnection).where(GoogleConnection.customer_id == customer_id)
)
connection = result.scalar_one_or_none()
if connection:
@@ -2484,15 +2502,15 @@ class Database:
return True
return False
except Exception as e:
- logger.error(f"Failed to update Gmail tokens: {e}")
+ logger.error(f"Failed to update Google tokens: {e}")
return False
- async def update_gmail_last_used(self, customer_id: str) -> bool:
- """Update last_used_at timestamp for a Gmail connection."""
+ async def update_google_last_used(self, customer_id: str) -> bool:
+ """Update last_used_at timestamp for a Google Workspace connection."""
try:
async with self.get_session() as session:
result = await session.execute(
- select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ select(GoogleConnection).where(GoogleConnection.customer_id == customer_id)
)
connection = result.scalar_one_or_none()
if connection:
@@ -2501,5 +2519,5 @@ class Database:
return True
return False
except Exception as e:
- logger.error(f"Failed to update Gmail last used: {e}")
+ logger.error(f"Failed to update Google last used: {e}")
return False
\ No newline at end of file
diff --git a/server/main.py b/server/main.py
index 7cd5b564..8a94fe86 100644
--- a/server/main.py
+++ b/server/main.py
@@ -27,7 +27,7 @@ from fastapi.responses import ORJSONResponse
from core.container import container
from core.config import Settings
from core.logging import configure_logging, get_logger, setup_websocket_logging, shutdown_websocket_logging
-from routers import workflow, database, maps, nodejs_compat, android, websocket, webhook, auth, twitter, gmail
+from routers import workflow, database, maps, nodejs_compat, android, websocket, webhook, auth, twitter, google
# Initialize settings and logging
settings = Settings()
@@ -62,7 +62,7 @@ async def lifespan(app: FastAPI):
"routers.webhook",
"routers.auth",
"routers.twitter",
- "routers.gmail",
+ "routers.google",
"middleware.auth"
])
@@ -277,7 +277,7 @@ app.include_router(android.router)
app.include_router(websocket.router)
app.include_router(webhook.router)
app.include_router(twitter.router) # Twitter/X OAuth routes
-app.include_router(gmail.router) # Gmail OAuth routes
+app.include_router(google.router) # Google Workspace OAuth routes (Gmail, Calendar, Drive, Sheets, Tasks, Contacts)
@app.get("/health")
diff --git a/server/models/database.py b/server/models/database.py
index 2296cef6..37e7d08f 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -495,21 +495,22 @@ class AgentMessage(SQLModel, table=True):
)
-class GmailConnection(SQLModel, table=True):
- """Gmail OAuth connections for customer access mode.
+class GoogleConnection(SQLModel, table=True):
+ """Google Workspace OAuth connections for customer access mode.
- Stores OAuth tokens for each connected Gmail account, supporting both:
+ Stores OAuth tokens for each connected Google account, supporting both:
- Owner mode: Single account stored via auth_service (credentials modal)
- Customer mode: Multiple customer accounts stored here with customer_id
- This enables apps to access customer Gmail (like CRM apps, email clients).
+ This enables apps to access customer Google Workspace services
+ (Gmail, Calendar, Drive, Sheets, Tasks, Contacts).
"""
- __tablename__ = "gmail_connections"
+ __tablename__ = "google_connections"
id: Optional[int] = Field(default=None, primary_key=True)
customer_id: str = Field(index=True, max_length=255) # Your app's customer identifier
- email: str = Field(max_length=255) # Connected Gmail address
+ email: str = Field(max_length=255) # Connected Google account email
name: Optional[str] = Field(default=None, max_length=255) # User's display name
access_token: str = Field(max_length=2000) # Encrypted OAuth access token
refresh_token: str = Field(max_length=2000) # Encrypted OAuth refresh token
diff --git a/server/routers/gmail.py b/server/routers/google.py
similarity index 64%
rename from server/routers/gmail.py
rename to server/routers/google.py
index e32276ec..93e3f206 100644
--- a/server/routers/gmail.py
+++ b/server/routers/google.py
@@ -1,17 +1,20 @@
"""
-Gmail OAuth 2.0 callback and API routes.
+Google Workspace OAuth 2.0 callback and API routes.
OAuth flow:
-1. Frontend calls WebSocket 'gmail_oauth_login' handler
+1. Frontend calls WebSocket 'google_oauth_login' handler
2. Backend generates authorization URL, opens browser
3. User authorizes on Google
-4. Google redirects to /api/gmail/callback with code
+4. Google redirects to /api/google/callback with code
5. Backend exchanges code for tokens, stores them via auth_service
-6. Frontend polls WebSocket 'gmail_oauth_status' for completion
+6. Frontend polls WebSocket 'google_oauth_status' for completion
Two access modes:
- Owner Mode: Tokens stored via auth_service (single account)
-- Customer Mode: Tokens stored in gmail_connections table (multi-account)
+- Customer Mode: Tokens stored in google_connections table (multi-account)
+
+Supports all Google Workspace services:
+- Gmail, Calendar, Drive, Sheets, Tasks, Contacts
"""
from typing import Optional
@@ -21,10 +24,10 @@ from fastapi.responses import HTMLResponse, RedirectResponse
from core.container import container
from core.logging import get_logger
-from services.gmail_oauth import GmailOAuth, get_pending_state
+from services.google_oauth import GoogleOAuth, get_pending_state
logger = get_logger(__name__)
-router = APIRouter(prefix="/api/gmail", tags=["gmail"])
+router = APIRouter(prefix="/api/google", tags=["google"])
def get_settings():
@@ -43,20 +46,20 @@ def get_database():
@router.get("/callback")
-async def gmail_oauth_callback(
+async def google_oauth_callback(
code: Optional[str] = Query(None),
state: Optional[str] = Query(None),
error: Optional[str] = Query(None),
error_description: Optional[str] = Query(None),
):
"""
- Handle Gmail OAuth callback.
+ Handle Google OAuth callback.
Google redirects here after user authorizes (or denies) the app.
"""
# Handle authorization denied
if error:
- logger.warning(f"Gmail OAuth denied: {error} - {error_description}")
+ logger.warning(f"Google OAuth denied: {error} - {error_description}")
return HTMLResponse(
content=_callback_html(success=False, error=error_description or error),
status_code=200,
@@ -64,7 +67,7 @@ async def gmail_oauth_callback(
# Validate required parameters
if not code or not state:
- logger.error("Gmail OAuth callback missing code or state")
+ logger.error("Google OAuth callback missing code or state")
return HTMLResponse(
content=_callback_html(success=False, error="Missing authorization code or state"),
status_code=400,
@@ -73,7 +76,7 @@ async def gmail_oauth_callback(
# Verify state exists (CSRF protection)
pending_state = get_pending_state(state)
if not pending_state:
- logger.error("Gmail OAuth callback with invalid/expired state")
+ logger.error("Google OAuth callback with invalid/expired state")
return HTMLResponse(
content=_callback_html(success=False, error="Invalid or expired state. Please try again."),
status_code=400,
@@ -88,26 +91,26 @@ async def gmail_oauth_callback(
# Get settings and credentials
settings = get_settings()
auth_service = get_auth_service()
- client_id = await auth_service.get_api_key("gmail_client_id") or ""
- client_secret = await auth_service.get_api_key("gmail_client_secret") or ""
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
if not client_id or not client_secret:
return HTMLResponse(
- content=_callback_html(success=False, error="Gmail not configured. Add Client ID and Secret in Credentials."),
+ content=_callback_html(success=False, error="Google not configured. Add Client ID and Secret in Credentials."),
status_code=400,
)
- oauth = GmailOAuth(
+ oauth = GoogleOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri=settings.gmail_redirect_uri,
+ redirect_uri=settings.google_redirect_uri,
)
# Exchange code for tokens
result = oauth.exchange_code(code=code, state=state)
if not result.get("success"):
- logger.error(f"Gmail token exchange failed: {result.get('error')}")
+ logger.error(f"Google token exchange failed: {result.get('error')}")
return HTMLResponse(
content=_callback_html(success=False, error=result.get("error", "Token exchange failed")),
status_code=400,
@@ -119,9 +122,9 @@ async def gmail_oauth_callback(
refresh_token = result.get("refresh_token")
if mode == "customer" and customer_id:
- # Customer mode: store in gmail_connections table
+ # Customer mode: store in google_connections table
database = get_database()
- await database.save_gmail_connection(
+ await database.save_google_connection(
customer_id=customer_id,
email=email,
name=name,
@@ -129,23 +132,23 @@ async def gmail_oauth_callback(
refresh_token=refresh_token,
scopes=",".join(result.get("scopes", [])),
)
- logger.info(f"Gmail OAuth successful for customer {customer_id}: {email}")
+ logger.info(f"Google OAuth successful for customer {customer_id}: {email}")
if redirect_after:
- return RedirectResponse(url=f"{redirect_after}?gmail_connected=true&customer={customer_id}&email={email}")
+ return RedirectResponse(url=f"{redirect_after}?google_connected=true&customer={customer_id}&email={email}")
else:
# Owner mode: store via auth_service
- await auth_service.store_api_key(provider="gmail_access_token", api_key=access_token, models=[], session_id="default")
+ await auth_service.store_api_key(provider="google_access_token", api_key=access_token, models=[], session_id="default")
if refresh_token:
- await auth_service.store_api_key(provider="gmail_refresh_token", api_key=refresh_token, models=[], session_id="default")
- await auth_service.store_api_key(provider="gmail_user_info", api_key=f"{email}:{name}", models=[], session_id="default")
- logger.info(f"Gmail OAuth successful for {email}")
+ await auth_service.store_api_key(provider="google_refresh_token", api_key=refresh_token, models=[], session_id="default")
+ await auth_service.store_api_key(provider="google_user_info", api_key=f"{email}:{name}", models=[], session_id="default")
+ logger.info(f"Google OAuth successful for {email}")
# Broadcast completion event
from services.status_broadcaster import get_status_broadcaster
broadcaster = get_status_broadcaster()
await broadcaster.broadcast({
- "type": "gmail_oauth_complete",
+ "type": "google_oauth_complete",
"data": {"success": True, "email": email, "name": name, "mode": mode, "customer_id": customer_id},
})
@@ -153,15 +156,15 @@ async def gmail_oauth_callback(
@router.get("/status")
-async def get_gmail_status():
- """Get Gmail connection status for owner mode."""
+async def get_google_status():
+ """Get Google connection status for owner mode."""
auth_service = get_auth_service()
- access_token = await auth_service.get_api_key("gmail_access_token")
+ access_token = await auth_service.get_api_key("google_access_token")
if not access_token:
return {"connected": False, "email": None}
- user_info_str = await auth_service.get_api_key("gmail_user_info")
+ user_info_str = await auth_service.get_api_key("google_user_info")
email, name = None, None
if user_info_str:
parts = user_info_str.split(":", 1)
@@ -172,41 +175,41 @@ async def get_gmail_status():
@router.post("/logout")
-async def gmail_logout():
- """Disconnect Gmail (owner mode)."""
+async def google_logout():
+ """Disconnect Google (owner mode)."""
auth_service = get_auth_service()
- await auth_service.remove_api_key("gmail_access_token")
- await auth_service.remove_api_key("gmail_refresh_token")
- await auth_service.remove_api_key("gmail_user_info")
- logger.info("Gmail disconnected")
- return {"success": True, "message": "Gmail disconnected"}
+ await auth_service.remove_api_key("google_access_token")
+ await auth_service.remove_api_key("google_refresh_token")
+ await auth_service.remove_api_key("google_user_info")
+ logger.info("Google disconnected")
+ return {"success": True, "message": "Google disconnected"}
@router.post("/customer-auth-url")
async def generate_customer_auth_url(customer_id: str, redirect_after: Optional[str] = None):
- """Generate OAuth URL for a customer to connect their Gmail."""
+ """Generate OAuth URL for a customer to connect their Google account."""
settings = get_settings()
auth_service = get_auth_service()
- client_id = await auth_service.get_api_key("gmail_client_id") or ""
- client_secret = await auth_service.get_api_key("gmail_client_secret") or ""
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
if not client_id or not client_secret:
- return {"success": False, "error": "Gmail not configured. Add Client ID and Secret."}
+ return {"success": False, "error": "Google not configured. Add Client ID and Secret."}
- oauth = GmailOAuth(
+ oauth = GoogleOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri=settings.gmail_redirect_uri,
+ redirect_uri=settings.google_redirect_uri,
)
result = oauth.generate_authorization_url(state_data={"customer_id": customer_id, "redirect_after": redirect_after, "mode": "customer"})
return {"success": True, "url": result["url"], "state": result["state"]}
@router.get("/customer/{customer_id}/status")
-async def get_customer_gmail_status(customer_id: str):
- """Get Gmail connection status for a customer."""
+async def get_customer_google_status(customer_id: str):
+ """Get Google connection status for a customer."""
database = get_database()
- connection = await database.get_gmail_connection(customer_id)
+ connection = await database.get_google_connection(customer_id)
if not connection:
return {"connected": False, "customer_id": customer_id}
return {
@@ -219,18 +222,18 @@ async def get_customer_gmail_status(customer_id: str):
@router.post("/customer/{customer_id}/disconnect")
-async def disconnect_customer_gmail(customer_id: str):
- """Disconnect a customer's Gmail."""
+async def disconnect_customer_google(customer_id: str):
+ """Disconnect a customer's Google account."""
database = get_database()
- await database.delete_gmail_connection(customer_id)
- logger.info(f"Gmail disconnected for customer {customer_id}")
+ await database.delete_google_connection(customer_id)
+ logger.info(f"Google disconnected for customer {customer_id}")
return {"success": True, "customer_id": customer_id}
def _callback_html(success: bool, email: str = None, error: str = None) -> str:
"""Generate callback HTML page."""
if success:
- title, message, color = "Gmail Connected", f"Successfully connected as {email}!", "#34a853"
+ title, message, color = "Google Connected", f"Successfully connected as {email}!", "#34a853"
else:
title, message, color = "Connection Failed", error or "Failed to connect", "#ea4335"
@@ -253,6 +256,6 @@ p{{font-size:16px;color:rgba(255,255,255,0.8);margin-bottom:20px}}
<h1>{title}</h1><p>{message}</p><p class="close-text">This window will close automatically...</p>
</div>
<script>
-if(window.opener){{window.opener.postMessage({{type:'gmail_oauth_callback',success:{str(success).lower()},{"email:'"+email+"'," if email else ""}{"error:'"+error.replace("'","\\'")+"'," if error else ""}}},'*')}}
+if(window.opener){{window.opener.postMessage({{type:'google_oauth_callback',success:{str(success).lower()},{"email:'"+email+"'," if email else ""}{"error:'"+error.replace("'","\\'")+"'," if error else ""}}},'*')}}
setTimeout(function(){{window.close()}},2000);
</script></body></html>"""
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 9c679785..db00ec51 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1203,36 +1203,37 @@ async def handle_twitter_logout(data: Dict[str, Any], websocket: WebSocket) -> D
# ============================================================================
-# Gmail OAuth Handlers
+# Google Workspace OAuth Handlers
# ============================================================================
@ws_handler()
-async def handle_gmail_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+async def handle_google_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""
- Initiate Gmail OAuth 2.0 flow.
+ Initiate Google Workspace OAuth 2.0 flow.
Opens browser to Google authorization page. After user authorizes,
- Google redirects to /api/gmail/callback which stores tokens.
+ Google redirects to /api/google/callback which stores tokens.
+ Grants access to all Google Workspace services (Gmail, Calendar, Drive, etc).
"""
import webbrowser
- from services.gmail_oauth import GmailOAuth
+ from services.google_oauth import GoogleOAuth
auth_service = container.auth_service()
settings = container.settings()
- client_id = await auth_service.get_api_key("gmail_client_id")
- client_secret = await auth_service.get_api_key("gmail_client_secret")
+ client_id = await auth_service.get_api_key("google_client_id")
+ client_secret = await auth_service.get_api_key("google_client_secret")
if not client_id or not client_secret:
return {
"success": False,
- "error": "Gmail Client ID and Secret not configured. Add your Google API credentials first."
+ "error": "Google Workspace Client ID and Secret not configured. Add your Google API credentials first."
}
- oauth = GmailOAuth(
+ oauth = GoogleOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri=settings.gmail_redirect_uri,
+ redirect_uri=settings.google_redirect_uri,
)
auth_data = oauth.generate_authorization_url()
@@ -1247,18 +1248,18 @@ async def handle_gmail_oauth_login(data: Dict[str, Any], websocket: WebSocket) -
@ws_handler()
-async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+async def handle_google_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""
- Check Gmail OAuth connection status.
+ Check Google Workspace OAuth connection status.
Returns connection status and user info if connected.
"""
- from services.gmail_oauth import GmailOAuth
+ from services.google_oauth import GoogleOAuth
auth_service = container.auth_service()
settings = container.settings()
- access_token = await auth_service.get_api_key("gmail_access_token")
+ access_token = await auth_service.get_api_key("google_access_token")
if not access_token:
return {
@@ -1267,7 +1268,7 @@ async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket)
"name": None,
}
- user_info_str = await auth_service.get_api_key("gmail_user_info")
+ user_info_str = await auth_service.get_api_key("google_user_info")
email, name = None, None
if user_info_str:
parts = user_info_str.split(":", 1)
@@ -1276,21 +1277,20 @@ async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket)
# Verify token is valid by checking if we can build service
try:
- client_id = await auth_service.get_api_key("gmail_client_id") or ""
- client_secret = await auth_service.get_api_key("gmail_client_secret") or ""
- refresh_token = await auth_service.get_api_key("gmail_refresh_token")
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
# Try to refresh if needed
if refresh_token and client_id and client_secret:
- refreshed = GmailOAuth.refresh_credentials(
+ refreshed = GoogleOAuth.refresh_credentials(
refresh_token=refresh_token,
client_id=client_id,
client_secret=client_secret,
)
if refreshed.get("success") and refreshed.get("access_token"):
- # Store new access token
await auth_service.store_api_key(
- provider="gmail_access_token",
+ provider="google_access_token",
api_key=refreshed["access_token"],
models=[],
session_id="default"
@@ -1302,7 +1302,7 @@ async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket)
"name": name,
}
except Exception as e:
- logger.warning(f"Gmail token validation failed: {e}")
+ logger.warning(f"Google token validation failed: {e}")
return {
"connected": False,
"email": None,
@@ -1312,17 +1312,17 @@ async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket)
@ws_handler()
-async def handle_gmail_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+async def handle_google_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""
- Disconnect Gmail by clearing stored credentials.
+ Disconnect Google Workspace by clearing stored credentials.
"""
auth_service = container.auth_service()
- await auth_service.remove_api_key("gmail_access_token")
- await auth_service.remove_api_key("gmail_refresh_token")
- await auth_service.remove_api_key("gmail_user_info")
+ await auth_service.remove_api_key("google_access_token")
+ await auth_service.remove_api_key("google_refresh_token")
+ await auth_service.remove_api_key("google_user_info")
- return {"success": True, "message": "Gmail disconnected"}
+ return {"success": True, "message": "Google Workspace disconnected"}
@ws_handler("url")
@@ -2586,10 +2586,10 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"twitter_oauth_status": handle_twitter_oauth_status,
"twitter_logout": handle_twitter_logout,
- # Gmail OAuth operations
- "gmail_oauth_login": handle_gmail_oauth_login,
- "gmail_oauth_status": handle_gmail_oauth_status,
- "gmail_logout": handle_gmail_logout,
+ # Google Workspace OAuth operations
+ "google_oauth_login": handle_google_oauth_login,
+ "google_oauth_status": handle_google_oauth_status,
+ "google_logout": handle_google_logout,
# Android operations
"get_android_devices": handle_get_android_devices,
diff --git a/server/services/ai.py b/server/services/ai.py
index 7d6a5d9e..ef9b73a9 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -3020,6 +3020,512 @@ class AIService:
return GmailReadSchema
+ # ============================================================================
+ # GOOGLE CALENDAR TOOL SCHEMAS
+ # ============================================================================
+
+ # Calendar Create tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'calendarCreate':
+ class CalendarCreateSchema(BaseModel):
+ """Create a new event in Google Calendar."""
+ title: str = Field(
+ description="Event title/summary"
+ )
+ start_time: str = Field(
+ description="Start time in ISO 8601 format (e.g., '2026-02-22T14:00:00') or date only for all-day (e.g., '2026-02-22')"
+ )
+ end_time: str = Field(
+ description="End time in ISO 8601 format or date only for all-day events"
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="Event description/notes"
+ )
+ location: Optional[str] = Field(
+ default=None,
+ description="Event location (address or place name)"
+ )
+ attendees: Optional[str] = Field(
+ default=None,
+ description="Comma-separated list of attendee email addresses"
+ )
+ timezone: str = Field(
+ default="UTC",
+ description="Timezone for the event (e.g., 'America/New_York', 'Europe/London')"
+ )
+ calendar_id: str = Field(
+ default="primary",
+ description="Calendar ID (use 'primary' for main calendar)"
+ )
+ send_updates: str = Field(
+ default="none",
+ description="Send update notifications: 'all', 'externalOnly', or 'none'"
+ )
+
+ return CalendarCreateSchema
+
+ # Calendar List tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'calendarList':
+ class CalendarListSchema(BaseModel):
+ """List events from Google Calendar within a date range."""
+ start_date: str = Field(
+ description="Start date in ISO 8601 format (e.g., '2026-02-22' or '2026-02-22T00:00:00Z')"
+ )
+ end_date: str = Field(
+ description="End date in ISO 8601 format"
+ )
+ calendar_id: str = Field(
+ default="primary",
+ description="Calendar ID (use 'primary' for main calendar)"
+ )
+ max_results: int = Field(
+ default=50,
+ description="Maximum number of events to return (1-2500)"
+ )
+ query: Optional[str] = Field(
+ default=None,
+ description="Free text search query to filter events"
+ )
+
+ return CalendarListSchema
+
+ # Calendar Update tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'calendarUpdate':
+ class CalendarUpdateSchema(BaseModel):
+ """Update an existing Google Calendar event."""
+ event_id: str = Field(
+ description="The event ID to update"
+ )
+ title: Optional[str] = Field(
+ default=None,
+ description="New event title (leave empty to keep current)"
+ )
+ start_time: Optional[str] = Field(
+ default=None,
+ description="New start time in ISO 8601 format (leave empty to keep current)"
+ )
+ end_time: Optional[str] = Field(
+ default=None,
+ description="New end time in ISO 8601 format (leave empty to keep current)"
+ )
+ description: Optional[str] = Field(
+ default=None,
+ description="New description (leave empty to keep current)"
+ )
+ location: Optional[str] = Field(
+ default=None,
+ description="New location (leave empty to keep current)"
+ )
+ calendar_id: str = Field(
+ default="primary",
+ description="Calendar ID"
+ )
+ send_updates: str = Field(
+ default="none",
+ description="Send update notifications: 'all', 'externalOnly', or 'none'"
+ )
+
+ return CalendarUpdateSchema
+
+ # Calendar Delete tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'calendarDelete':
+ class CalendarDeleteSchema(BaseModel):
+ """Delete an event from Google Calendar."""
+ event_id: str = Field(
+ description="The event ID to delete"
+ )
+ calendar_id: str = Field(
+ default="primary",
+ description="Calendar ID"
+ )
+ send_updates: str = Field(
+ default="none",
+ description="Send cancellation notifications: 'all', 'externalOnly', or 'none'"
+ )
+
+ return CalendarDeleteSchema
+
+ # ============================================================================
+ # GOOGLE DRIVE TOOL SCHEMAS
+ # ============================================================================
+
+ # Drive Upload tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'driveUpload':
+ class DriveUploadSchema(BaseModel):
+ """Upload a file to Google Drive."""
+ file_url: str = Field(
+ description="URL of the file to upload (will be downloaded and uploaded to Drive)"
+ )
+ filename: Optional[str] = Field(
+ default=None,
+ description="Custom filename for the uploaded file (optional, auto-detected from URL)"
+ )
+ folder_id: Optional[str] = Field(
+ default=None,
+ description="Parent folder ID (omit for root Drive folder)"
+ )
+ mime_type: Optional[str] = Field(
+ default=None,
+ description="MIME type (e.g., 'application/pdf'). Auto-detected if not specified."
+ )
+
+ return DriveUploadSchema
+
+ # Drive Download tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'driveDownload':
+ class DriveDownloadSchema(BaseModel):
+ """Download a file from Google Drive."""
+ file_id: str = Field(
+ description="The Drive file ID to download"
+ )
+
+ return DriveDownloadSchema
+
+ # Drive List tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'driveList':
+ class DriveListSchema(BaseModel):
+ """List files in Google Drive."""
+ folder_id: Optional[str] = Field(
+ default=None,
+ description="Folder ID to list files from (omit for root or all files)"
+ )
+ query: Optional[str] = Field(
+ default=None,
+ description="Drive search query (e.g., \"name contains 'report'\" or \"mimeType='application/pdf'\")"
+ )
+ max_results: int = Field(
+ default=100,
+ description="Maximum number of files to return (1-1000)"
+ )
+ file_types: Optional[str] = Field(
+ default=None,
+ description="Filter by file type: 'documents', 'spreadsheets', 'presentations', 'pdfs', 'images', 'videos'"
+ )
+
+ return DriveListSchema
+
+ # Drive Share tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'driveShare':
+ class DriveShareSchema(BaseModel):
+ """Share a Google Drive file with someone."""
+ file_id: str = Field(
+ description="The Drive file ID to share"
+ )
+ email: str = Field(
+ description="Email address to share with"
+ )
+ role: str = Field(
+ default="reader",
+ description="Permission role: 'reader', 'writer', or 'commenter'"
+ )
+ send_notification: bool = Field(
+ default=True,
+ description="Whether to send an email notification to the user"
+ )
+
+ return DriveShareSchema
+
+ # ============================================================================
+ # GOOGLE SHEETS TOOL SCHEMAS
+ # ============================================================================
+
+ # Sheets Read tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'sheetsRead':
+ class SheetsReadSchema(BaseModel):
+ """Read data from a Google Sheets spreadsheet."""
+ spreadsheet_id: str = Field(
+ description="Spreadsheet ID (from the URL, between /d/ and /edit)"
+ )
+ range: str = Field(
+ description="A1 notation range (e.g., 'Sheet1!A1:D10' or 'A:D' for entire columns)"
+ )
+ value_render_option: str = Field(
+ default="FORMATTED_VALUE",
+ description="How values are rendered: 'FORMATTED_VALUE', 'UNFORMATTED_VALUE', or 'FORMULA'"
+ )
+ major_dimension: str = Field(
+ default="ROWS",
+ description="Whether to return rows or columns first: 'ROWS' or 'COLUMNS'"
+ )
+
+ return SheetsReadSchema
+
+ # Sheets Write tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'sheetsWrite':
+ class SheetsWriteSchema(BaseModel):
+ """Write data to a Google Sheets spreadsheet."""
+ spreadsheet_id: str = Field(
+ description="Spreadsheet ID (from the URL)"
+ )
+ range: str = Field(
+ description="Starting cell in A1 notation (e.g., 'Sheet1!A1')"
+ )
+ values: str = Field(
+ description="2D array of values as JSON string (e.g., '[[\"Name\", \"Age\"], [\"Alice\", 25]]')"
+ )
+ value_input_option: str = Field(
+ default="USER_ENTERED",
+ description="How input is interpreted: 'USER_ENTERED' (parses formulas) or 'RAW'"
+ )
+
+ return SheetsWriteSchema
+
+ # Sheets Append tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'sheetsAppend':
+ class SheetsAppendSchema(BaseModel):
+ """Append rows to a Google Sheets spreadsheet."""
+ spreadsheet_id: str = Field(
+ description="Spreadsheet ID (from the URL)"
+ )
+ range: str = Field(
+ description="Table range in A1 notation (e.g., 'Sheet1!A:D')"
+ )
+ values: str = Field(
+ description="2D array of rows to append as JSON string (e.g., '[[\"Alice\", 25, \"[email protected]\"]]')"
+ )
+ value_input_option: str = Field(
+ default="USER_ENTERED",
+ description="How input is interpreted: 'USER_ENTERED' or 'RAW'"
+ )
+ insert_data_option: str = Field(
+ default="INSERT_ROWS",
+ description="How data is inserted: 'INSERT_ROWS' or 'OVERWRITE'"
+ )
+
+ return SheetsAppendSchema
+
+ # ============================================================================
+ # GOOGLE TASKS TOOL SCHEMAS
+ # ============================================================================
+
+ # Tasks Create tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'tasksCreate':
+ class TasksCreateSchema(BaseModel):
+ """Create a new task in Google Tasks."""
+ title: str = Field(
+ description="Task title (required)"
+ )
+ notes: Optional[str] = Field(
+ default=None,
+ description="Task notes/description"
+ )
+ due_date: Optional[str] = Field(
+ default=None,
+ description="Due date in ISO 8601 format (e.g., '2026-02-25' or '2026-02-25T14:00:00Z')"
+ )
+ tasklist_id: str = Field(
+ default="@default",
+ description="Task list ID (use '@default' for the default list)"
+ )
+
+ return TasksCreateSchema
+
+ # Tasks List tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'tasksList':
+ class TasksListSchema(BaseModel):
+ """List tasks from Google Tasks."""
+ tasklist_id: str = Field(
+ default="@default",
+ description="Task list ID (use '@default' for the default list)"
+ )
+ show_completed: bool = Field(
+ default=False,
+ description="Include completed tasks"
+ )
+ show_hidden: bool = Field(
+ default=False,
+ description="Include hidden tasks"
+ )
+ max_results: int = Field(
+ default=100,
+ description="Maximum number of tasks to return"
+ )
+
+ return TasksListSchema
+
+ # Tasks Complete tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'tasksComplete':
+ class TasksCompleteSchema(BaseModel):
+ """Mark a Google Task as completed."""
+ task_id: str = Field(
+ description="The task ID to mark as completed"
+ )
+ tasklist_id: str = Field(
+ default="@default",
+ description="Task list ID"
+ )
+
+ return TasksCompleteSchema
+
+ # Tasks Update tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'tasksUpdate':
+ class TasksUpdateSchema(BaseModel):
+ """Update an existing Google Task."""
+ task_id: str = Field(
+ description="The task ID to update"
+ )
+ tasklist_id: str = Field(
+ default="@default",
+ description="Task list ID"
+ )
+ title: Optional[str] = Field(
+ default=None,
+ description="New task title (leave empty to keep current)"
+ )
+ notes: Optional[str] = Field(
+ default=None,
+ description="New task notes (leave empty to keep current)"
+ )
+ due_date: Optional[str] = Field(
+ default=None,
+ description="New due date in ISO 8601 format (leave empty to keep current)"
+ )
+ status: Optional[str] = Field(
+ default=None,
+ description="New status: 'needsAction' or 'completed'"
+ )
+
+ return TasksUpdateSchema
+
+ # Tasks Delete tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'tasksDelete':
+ class TasksDeleteSchema(BaseModel):
+ """Delete a task from Google Tasks."""
+ task_id: str = Field(
+ description="The task ID to delete"
+ )
+ tasklist_id: str = Field(
+ default="@default",
+ description="Task list ID"
+ )
+
+ return TasksDeleteSchema
+
+ # ============================================================================
+ # GOOGLE CONTACTS (PEOPLE API) TOOL SCHEMAS
+ # ============================================================================
+
+ # Contacts Create tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsCreate':
+ class ContactsCreateSchema(BaseModel):
+ """Create a new contact in Google Contacts."""
+ first_name: str = Field(
+ description="Contact's first name (required)"
+ )
+ last_name: Optional[str] = Field(
+ default=None,
+ description="Contact's last name"
+ )
+ email: Optional[str] = Field(
+ default=None,
+ description="Email address"
+ )
+ phone: Optional[str] = Field(
+ default=None,
+ description="Phone number"
+ )
+ company: Optional[str] = Field(
+ default=None,
+ description="Company/organization name"
+ )
+ job_title: Optional[str] = Field(
+ default=None,
+ description="Job title"
+ )
+ notes: Optional[str] = Field(
+ default=None,
+ description="Notes about the contact"
+ )
+
+ return ContactsCreateSchema
+
+ # Contacts List tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsList':
+ class ContactsListSchema(BaseModel):
+ """List contacts from Google Contacts."""
+ page_size: int = Field(
+ default=100,
+ description="Number of contacts to return (1-1000)"
+ )
+ sort_order: str = Field(
+ default="LAST_MODIFIED_DESCENDING",
+ description="Sort order: 'LAST_MODIFIED_DESCENDING', 'LAST_MODIFIED_ASCENDING', 'FIRST_NAME_ASCENDING', 'LAST_NAME_ASCENDING'"
+ )
+ page_token: Optional[str] = Field(
+ default=None,
+ description="Token for pagination (from previous request)"
+ )
+
+ return ContactsListSchema
+
+ # Contacts Search tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsSearch':
+ class ContactsSearchSchema(BaseModel):
+ """Search contacts in Google Contacts by name, email, or phone."""
+ query: str = Field(
+ description="Search query (name, email, or phone number)"
+ )
+ page_size: int = Field(
+ default=30,
+ description="Maximum number of results (1-100)"
+ )
+
+ return ContactsSearchSchema
+
+ # Contacts Get tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsGet':
+ class ContactsGetSchema(BaseModel):
+ """Get a specific contact by resource name."""
+ resource_name: str = Field(
+ description="Contact resource name (e.g., 'people/c12345678')"
+ )
+
+ return ContactsGetSchema
+
+ # Contacts Update tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsUpdate':
+ class ContactsUpdateSchema(BaseModel):
+ """Update an existing contact in Google Contacts."""
+ resource_name: str = Field(
+ description="Contact resource name to update (e.g., 'people/c12345678')"
+ )
+ first_name: Optional[str] = Field(
+ default=None,
+ description="New first name (leave empty to keep current)"
+ )
+ last_name: Optional[str] = Field(
+ default=None,
+ description="New last name (leave empty to keep current)"
+ )
+ email: Optional[str] = Field(
+ default=None,
+ description="New email (leave empty to keep current)"
+ )
+ phone: Optional[str] = Field(
+ default=None,
+ description="New phone (leave empty to keep current)"
+ )
+ company: Optional[str] = Field(
+ default=None,
+ description="New company (leave empty to keep current)"
+ )
+ job_title: Optional[str] = Field(
+ default=None,
+ description="New job title (leave empty to keep current)"
+ )
+
+ return ContactsUpdateSchema
+
+ # Contacts Delete tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'contactsDelete':
+ class ContactsDeleteSchema(BaseModel):
+ """Delete a contact from Google Contacts."""
+ resource_name: str = Field(
+ description="Contact resource name to delete (e.g., 'people/c12345678')"
+ )
+
+ return ContactsDeleteSchema
+
# Check delegated tasks schema (built-in tool for result retrieval)
if node_type == '_builtin_check_delegated_tasks':
class CheckDelegatedTasksSchema(BaseModel):
diff --git a/server/services/gmail_oauth.py b/server/services/google_oauth.py
similarity index 51%
rename from server/services/gmail_oauth.py
rename to server/services/google_oauth.py
index c8f3e3fe..980a7c54 100644
--- a/server/services/gmail_oauth.py
+++ b/server/services/google_oauth.py
@@ -1,16 +1,25 @@
"""
-Gmail OAuth 2.0 using google-auth-oauthlib library.
+Google Workspace OAuth 2.0 using google-auth-oauthlib library.
+
+Unified OAuth for all Google services:
+- Gmail (send, search, read emails)
+- Google Calendar (create, list, update, delete events)
+- Google Drive (upload, download, list, share files)
+- Google Sheets (read, write, append data)
+- Google Tasks (create, list, complete tasks)
+- Google Contacts (create, list, search contacts)
Two access modes:
-1. Owner Mode - Your own Gmail (Credentials Modal)
-2. Customer Mode - Customer's Gmail (database storage)
+1. Owner Mode - Your own Google account (Credentials Modal)
+2. Customer Mode - Customer's Google account (database storage)
-Docs: https://googleapis.dev/python/google-auth-oauthlib/latest/reference/google_auth_oauthlib.flow.html
+API endpoints loaded from config/google_apis.json
+Docs: https://developers.google.com/identity/protocols/oauth2
"""
import json
-import secrets
import time
+from pathlib import Path
from typing import Any, Dict, List, Optional
from google.auth.transport.requests import Request
@@ -22,45 +31,116 @@ from core.logging import get_logger
logger = get_logger(__name__)
-# Gmail API scopes
-DEFAULT_SCOPES = [
- "https://www.googleapis.com/auth/gmail.send",
- "https://www.googleapis.com/auth/gmail.readonly",
- "https://www.googleapis.com/auth/gmail.modify",
- "https://www.googleapis.com/auth/userinfo.email",
- "https://www.googleapis.com/auth/userinfo.profile",
- "openid",
-]
+# Load Google API config from JSON
+_config_path = Path(__file__).parent.parent / "config" / "google_apis.json"
+_google_config: Dict[str, Any] = {}
+
+def _load_config() -> Dict[str, Any]:
+ """Load Google API config from JSON file."""
+ global _google_config
+ if not _google_config:
+ try:
+ with open(_config_path, "r", encoding="utf-8") as f:
+ _google_config = json.load(f)
+ logger.debug("Loaded Google API config", version=_google_config.get("version"))
+ except Exception as e:
+ logger.error("Failed to load Google API config", error=str(e))
+ _google_config = _get_default_config()
+ return _google_config
+
+def _get_default_config() -> Dict[str, Any]:
+ """Return default config if JSON fails to load."""
+ return {
+ "oauth": {
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "revoke_uri": "https://oauth2.googleapis.com/revoke",
+ "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo"
+ },
+ "scopes": {
+ "userinfo": ["openid", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"],
+ "gmail": ["https://www.googleapis.com/auth/gmail.send", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.modify"],
+ "calendar": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events"],
+ "drive": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"],
+ "sheets": ["https://www.googleapis.com/auth/spreadsheets"],
+ "tasks": ["https://www.googleapis.com/auth/tasks"],
+ "contacts": ["https://www.googleapis.com/auth/contacts", "https://www.googleapis.com/auth/contacts.readonly"]
+ }
+ }
+
+def get_oauth_endpoints() -> Dict[str, str]:
+ """Get OAuth endpoint URLs from config."""
+ config = _load_config()
+ return config.get("oauth", _get_default_config()["oauth"])
+
+def get_service_config(service: str) -> Dict[str, Any]:
+ """Get service-specific config (base_url, version, etc.)."""
+ config = _load_config()
+ return config.get("services", {}).get(service, {})
+
+def get_all_scopes() -> List[str]:
+ """Get combined scopes for all Google Workspace services."""
+ config = _load_config()
+ scopes_config = config.get("scopes", _get_default_config()["scopes"])
+ all_scopes = []
+ for scope_list in scopes_config.values():
+ all_scopes.extend(scope_list)
+ return list(dict.fromkeys(all_scopes)) # Remove duplicates, preserve order
+
+def get_scopes_for_services(services: List[str]) -> List[str]:
+ """Get scopes for specific services only."""
+ config = _load_config()
+ scopes_config = config.get("scopes", _get_default_config()["scopes"])
+ scopes = []
+ # Always include userinfo
+ scopes.extend(scopes_config.get("userinfo", []))
+ for service in services:
+ scopes.extend(scopes_config.get(service, []))
+ return list(dict.fromkeys(scopes))
+
+# Combined scopes for all services (loaded from config)
+GOOGLE_WORKSPACE_SCOPES = get_all_scopes()
+
+# Legacy alias for backward compatibility
+DEFAULT_SCOPES = GOOGLE_WORKSPACE_SCOPES
# In-memory state store (use Redis in production)
_oauth_states: Dict[str, Dict[str, Any]] = {}
-class GmailOAuth:
- """Gmail OAuth 2.0 using google-auth-oauthlib Flow."""
+class GoogleOAuth:
+ """Google Workspace OAuth 2.0 using google-auth-oauthlib Flow.
+
+ Provides unified OAuth for all Google Workspace services.
+ API endpoints loaded from config/google_apis.json for easy updates.
+ """
def __init__(
self,
client_id: str,
client_secret: str,
- redirect_uri: str = "http://localhost:3010/api/gmail/callback",
+ redirect_uri: str = "http://localhost:3010/api/google/callback",
scopes: Optional[List[str]] = None,
):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
- self.scopes = scopes or DEFAULT_SCOPES
+ self.scopes = scopes or GOOGLE_WORKSPACE_SCOPES
+
+ # Get OAuth endpoints from config
+ oauth_endpoints = get_oauth_endpoints()
# Build client config in Google's format
self.client_config = {
"web": {
"client_id": client_id,
"client_secret": client_secret,
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
- "token_uri": "https://oauth2.googleapis.com/token",
+ "auth_uri": oauth_endpoints["auth_uri"],
+ "token_uri": oauth_endpoints["token_uri"],
"redirect_uris": [redirect_uri],
}
}
+ self.token_uri = oauth_endpoints["token_uri"]
def generate_authorization_url(
self,
@@ -95,7 +175,7 @@ class GmailOAuth:
"data": state_data or {"mode": "owner"},
}
- logger.info("Generated Gmail OAuth URL", state=state[:8])
+ logger.info("Generated Google OAuth URL", state=state[:8])
return {
"url": authorization_url,
@@ -136,7 +216,7 @@ class GmailOAuth:
# Get user info
user_info = self._get_user_info(creds)
- logger.info("Gmail OAuth successful", email=user_info.get("email", "")[:20])
+ logger.info("Google OAuth successful", email=user_info.get("email", "")[:20])
return {
"success": True,
@@ -150,6 +230,7 @@ class GmailOAuth:
"state_data": state_data,
"email": user_info.get("email"),
"name": user_info.get("name"),
+ "picture": user_info.get("picture"),
}
except Exception as e:
@@ -175,7 +256,7 @@ class GmailOAuth:
refresh_token: str,
client_id: str,
client_secret: str,
- token_uri: str = "https://oauth2.googleapis.com/token",
+ token_uri: Optional[str] = None,
) -> Dict[str, Any]:
"""
Refresh expired credentials.
@@ -184,11 +265,14 @@ class GmailOAuth:
refresh_token: The refresh token
client_id: OAuth client ID
client_secret: OAuth client secret
- token_uri: Token endpoint
+ token_uri: Token endpoint (loaded from config if not provided)
Returns:
Dict with new access_token
"""
+ if not token_uri:
+ token_uri = get_oauth_endpoints()["token_uri"]
+
try:
creds = Credentials(
token=None,
@@ -214,28 +298,61 @@ class GmailOAuth:
refresh_token: str,
client_id: str,
client_secret: str,
- token_uri: str = "https://oauth2.googleapis.com/token",
+ token_uri: Optional[str] = None,
scopes: Optional[List[str]] = None,
) -> Credentials:
"""
Build Credentials object from stored tokens.
- Use this to create credentials for Gmail API calls.
+ Use this to create credentials for Google API calls.
"""
+ if not token_uri:
+ token_uri = get_oauth_endpoints()["token_uri"]
+
return Credentials(
token=access_token,
refresh_token=refresh_token,
token_uri=token_uri,
client_id=client_id,
client_secret=client_secret,
- scopes=scopes or DEFAULT_SCOPES,
+ scopes=scopes or GOOGLE_WORKSPACE_SCOPES,
)
+ # Service builders for each Google API
@staticmethod
def build_gmail_service(creds: Credentials):
"""Build Gmail API service from credentials."""
return build("gmail", "v1", credentials=creds)
+ @staticmethod
+ def build_calendar_service(creds: Credentials):
+ """Build Calendar API service from credentials."""
+ return build("calendar", "v3", credentials=creds)
+
+ @staticmethod
+ def build_drive_service(creds: Credentials):
+ """Build Drive API service from credentials."""
+ return build("drive", "v3", credentials=creds)
+
+ @staticmethod
+ def build_sheets_service(creds: Credentials):
+ """Build Sheets API service from credentials."""
+ return build("sheets", "v4", credentials=creds)
+
+ @staticmethod
+ def build_tasks_service(creds: Credentials):
+ """Build Tasks API service from credentials."""
+ return build("tasks", "v1", credentials=creds)
+
+ @staticmethod
+ def build_people_service(creds: Credentials):
+ """Build People API service (Contacts) from credentials."""
+ return build("people", "v1", credentials=creds)
+
+
+# Backward compatibility alias
+GmailOAuth = GoogleOAuth
+
def cleanup_expired_states(max_age_seconds: int = 600):
"""Remove expired OAuth states."""
diff --git a/server/services/handlers/calendar.py b/server/services/handlers/calendar.py
new file mode 100644
index 00000000..a9f0b95d
--- /dev/null
+++ b/server/services/handlers/calendar.py
@@ -0,0 +1,444 @@
+"""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, List, Optional
+
+from google.oauth2.credentials import Credentials
+from googleapiclient.discovery import build
+
+from core.logging import get_logger
+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.
+
+ Supports two modes:
+ - Owner mode: Uses tokens from auth_service (Credentials Modal)
+ - Customer mode: Uses tokens from google_connections table
+ """
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
+
+ if not access_token:
+ raise ValueError("Google not connected. Please authenticate via Credentials.")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ 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}
diff --git a/server/services/handlers/contacts.py b/server/services/handlers/contacts.py
new file mode 100644
index 00000000..a6d34210
--- /dev/null
+++ b/server/services/handlers/contacts.py
@@ -0,0 +1,522 @@
+"""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, List
+
+from google.oauth2.credentials import Credentials
+from googleapiclient.discovery import build
+
+from core.logging import get_logger
+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."""
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
+
+ if not access_token:
+ raise ValueError("Google not connected. Please authenticate via Credentials.")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ def build_service():
+ return build("people", "v1", credentials=creds)
+
+ loop = asyncio.get_event_loop()
+ service = await loop.run_in_executor(None, build_service)
+
+ return 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', [])
+ addresses = 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}
diff --git a/server/services/handlers/drive.py b/server/services/handlers/drive.py
new file mode 100644
index 00000000..41350ceb
--- /dev/null
+++ b/server/services/handlers/drive.py
@@ -0,0 +1,476 @@
+"""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, Optional
+
+import httpx
+from google.oauth2.credentials import Credentials
+from googleapiclient.discovery import build
+from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload, MediaIoBaseDownload
+
+from core.logging import get_logger
+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.
+
+ Supports two modes:
+ - Owner mode: Uses tokens from auth_service (Credentials Modal)
+ - Customer mode: Uses tokens from google_connections table
+ """
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
+
+ if not access_token:
+ raise ValueError("Google not connected. Please authenticate via Credentials.")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ def build_service():
+ return build("drive", "v3", credentials=creds)
+
+ loop = asyncio.get_event_loop()
+ service = await loop.run_in_executor(None, build_service)
+
+ return 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}
diff --git a/server/services/handlers/gmail.py b/server/services/handlers/gmail.py
index e0f8277b..f5b29476 100644
--- a/server/services/handlers/gmail.py
+++ b/server/services/handlers/gmail.py
@@ -67,7 +67,7 @@ async def _get_gmail_service(
Supports two modes:
- Owner mode: Uses tokens from auth_service (Credentials Modal)
- - Customer mode: Uses tokens from gmail_connections table
+ - Customer mode: Uses tokens from google_connections table
Args:
parameters: Node parameters (may include account_mode, customer_id)
@@ -86,29 +86,29 @@ async def _get_gmail_service(
raise ValueError("customer_id required for customer mode")
db = container.database()
- connection = await db.get_gmail_connection(customer_id)
+ connection = await db.get_google_connection(customer_id)
if not connection:
- raise ValueError(f"No Gmail connection for customer: {customer_id}")
+ raise ValueError(f"No Google connection for customer: {customer_id}")
if not connection.is_active:
- raise ValueError(f"Gmail connection inactive for customer: {customer_id}")
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
access_token = connection.access_token
refresh_token = connection.refresh_token
- await db.update_gmail_last_used(customer_id)
+ await db.update_google_last_used(customer_id)
else:
auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("gmail_access_token")
- refresh_token = await auth_service.get_api_key("gmail_refresh_token")
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
if not access_token:
- raise ValueError("Gmail not connected. Please authenticate via Credentials.")
+ raise ValueError("Google Workspace not connected. Please authenticate via Credentials.")
auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("gmail_client_id") or ""
- client_secret = await auth_service.get_api_key("gmail_client_secret") or ""
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
creds = Credentials(
token=access_token,
diff --git a/server/services/handlers/sheets.py b/server/services/handlers/sheets.py
new file mode 100644
index 00000000..c06933fb
--- /dev/null
+++ b/server/services/handlers/sheets.py
@@ -0,0 +1,323 @@
+"""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, List
+
+from google.oauth2.credentials import Credentials
+from googleapiclient.discovery import build
+
+from core.logging import get_logger
+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."""
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
+
+ if not access_token:
+ raise ValueError("Google not connected. Please authenticate via Credentials.")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ def build_service():
+ return build("sheets", "v4", credentials=creds)
+
+ loop = asyncio.get_event_loop()
+ service = await loop.run_in_executor(None, build_service)
+
+ return 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}
diff --git a/server/services/handlers/tasks.py b/server/services/handlers/tasks.py
new file mode 100644
index 00000000..ccb78580
--- /dev/null
+++ b/server/services/handlers/tasks.py
@@ -0,0 +1,444 @@
+"""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 google.oauth2.credentials import Credentials
+from googleapiclient.discovery import build
+
+from core.logging import get_logger
+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."""
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("google_access_token")
+ refresh_token = await auth_service.get_api_key("google_refresh_token")
+
+ if not access_token:
+ raise ValueError("Google not connected. Please authenticate via Credentials.")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ def build_service():
+ return build("tasks", "v1", credentials=creds)
+
+ loop = asyncio.get_event_loop()
+ service = await loop.run_in_executor(None, build_service)
+
+ return 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}
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 2c94096c..251f2ebf 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -131,6 +131,64 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
if node_type == 'gmailRead':
return await _execute_gmail_read(tool_args, config.get('parameters', {}))
+ # ========================================================================
+ # GOOGLE WORKSPACE TOOLS (Calendar, Drive, Sheets, Tasks, Contacts)
+ # ========================================================================
+
+ # Google Calendar tools
+ if node_type == 'calendarCreate':
+ return await _execute_calendar_create(tool_args, config.get('parameters', {}))
+ if node_type == 'calendarList':
+ return await _execute_calendar_list(tool_args, config.get('parameters', {}))
+ if node_type == 'calendarUpdate':
+ return await _execute_calendar_update(tool_args, config.get('parameters', {}))
+ if node_type == 'calendarDelete':
+ return await _execute_calendar_delete(tool_args, config.get('parameters', {}))
+
+ # Google Drive tools
+ if node_type == 'driveUpload':
+ return await _execute_drive_upload(tool_args, config.get('parameters', {}))
+ if node_type == 'driveDownload':
+ return await _execute_drive_download(tool_args, config.get('parameters', {}))
+ if node_type == 'driveList':
+ return await _execute_drive_list(tool_args, config.get('parameters', {}))
+ if node_type == 'driveShare':
+ return await _execute_drive_share(tool_args, config.get('parameters', {}))
+
+ # Google Sheets tools
+ if node_type == 'sheetsRead':
+ return await _execute_sheets_read(tool_args, config.get('parameters', {}))
+ if node_type == 'sheetsWrite':
+ return await _execute_sheets_write(tool_args, config.get('parameters', {}))
+ if node_type == 'sheetsAppend':
+ return await _execute_sheets_append(tool_args, config.get('parameters', {}))
+
+ # Google Tasks tools
+ if node_type == 'tasksCreate':
+ return await _execute_tasks_create(tool_args, config.get('parameters', {}))
+ if node_type == 'tasksList':
+ return await _execute_tasks_list(tool_args, config.get('parameters', {}))
+ if node_type == 'tasksComplete':
+ return await _execute_tasks_complete(tool_args, config.get('parameters', {}))
+ if node_type == 'tasksUpdate':
+ return await _execute_tasks_update(tool_args, config.get('parameters', {}))
+ if node_type == 'tasksDelete':
+ return await _execute_tasks_delete(tool_args, config.get('parameters', {}))
+
+ # Google Contacts tools
+ if node_type == 'contactsCreate':
+ return await _execute_contacts_create(tool_args, config.get('parameters', {}))
+ if node_type == 'contactsList':
+ return await _execute_contacts_list(tool_args, config.get('parameters', {}))
+ if node_type == 'contactsSearch':
+ return await _execute_contacts_search(tool_args, config.get('parameters', {}))
+ if node_type == 'contactsGet':
+ return await _execute_contacts_get(tool_args, config.get('parameters', {}))
+ if node_type == 'contactsUpdate':
+ return await _execute_contacts_update(tool_args, config.get('parameters', {}))
+ if node_type == 'contactsDelete':
+ return await _execute_contacts_delete(tool_args, config.get('parameters', {}))
+
# Android toolkit - routes to connected service nodes
if node_type == 'androidTool':
return await _execute_android_toolkit(tool_args, config)
@@ -1283,6 +1341,338 @@ async def _execute_gmail_read(args: Dict[str, Any],
)
+# ============================================================================
+# GOOGLE WORKSPACE TOOL HANDLERS (Calendar, Drive, Sheets, Tasks, Contacts)
+# ============================================================================
+
+# ---------------------------------------------------------------------------
+# Google Calendar Tools
+# ---------------------------------------------------------------------------
+
+async def _execute_calendar_create(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Calendar create event via Google API."""
+ from services.handlers.calendar import handle_calendar_create
+
+ parameters = {**node_params, **args}
+ return await handle_calendar_create(
+ node_id="tool_calendar_create",
+ node_type="calendarCreate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_calendar_list(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Calendar list events via Google API."""
+ from services.handlers.calendar import handle_calendar_list
+
+ parameters = {**node_params, **args}
+ return await handle_calendar_list(
+ node_id="tool_calendar_list",
+ node_type="calendarList",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_calendar_update(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Calendar update event via Google API."""
+ from services.handlers.calendar import handle_calendar_update
+
+ parameters = {**node_params, **args}
+ return await handle_calendar_update(
+ node_id="tool_calendar_update",
+ node_type="calendarUpdate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_calendar_delete(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Calendar delete event via Google API."""
+ from services.handlers.calendar import handle_calendar_delete
+
+ parameters = {**node_params, **args}
+ return await handle_calendar_delete(
+ node_id="tool_calendar_delete",
+ node_type="calendarDelete",
+ parameters=parameters,
+ context={}
+ )
+
+
+# ---------------------------------------------------------------------------
+# Google Drive Tools
+# ---------------------------------------------------------------------------
+
+async def _execute_drive_upload(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Drive upload file via Google API."""
+ from services.handlers.drive import handle_drive_upload
+
+ parameters = {**node_params, **args}
+ return await handle_drive_upload(
+ node_id="tool_drive_upload",
+ node_type="driveUpload",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_drive_download(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Drive download file via Google API."""
+ from services.handlers.drive import handle_drive_download
+
+ parameters = {**node_params, **args}
+ return await handle_drive_download(
+ node_id="tool_drive_download",
+ node_type="driveDownload",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_drive_list(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Drive list files via Google API."""
+ from services.handlers.drive import handle_drive_list
+
+ parameters = {**node_params, **args}
+ return await handle_drive_list(
+ node_id="tool_drive_list",
+ node_type="driveList",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_drive_share(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Drive share file via Google API."""
+ from services.handlers.drive import handle_drive_share
+
+ parameters = {**node_params, **args}
+ return await handle_drive_share(
+ node_id="tool_drive_share",
+ node_type="driveShare",
+ parameters=parameters,
+ context={}
+ )
+
+
+# ---------------------------------------------------------------------------
+# Google Sheets Tools
+# ---------------------------------------------------------------------------
+
+async def _execute_sheets_read(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Sheets read data via Google API."""
+ from services.handlers.sheets import handle_sheets_read
+
+ parameters = {**node_params, **args}
+ return await handle_sheets_read(
+ node_id="tool_sheets_read",
+ node_type="sheetsRead",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_sheets_write(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Sheets write data via Google API."""
+ from services.handlers.sheets import handle_sheets_write
+
+ parameters = {**node_params, **args}
+ return await handle_sheets_write(
+ node_id="tool_sheets_write",
+ node_type="sheetsWrite",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_sheets_append(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Sheets append rows via Google API."""
+ from services.handlers.sheets import handle_sheets_append
+
+ parameters = {**node_params, **args}
+ return await handle_sheets_append(
+ node_id="tool_sheets_append",
+ node_type="sheetsAppend",
+ parameters=parameters,
+ context={}
+ )
+
+
+# ---------------------------------------------------------------------------
+# Google Tasks Tools
+# ---------------------------------------------------------------------------
+
+async def _execute_tasks_create(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Tasks create via Google API."""
+ from services.handlers.tasks import handle_tasks_create
+
+ parameters = {**node_params, **args}
+ return await handle_tasks_create(
+ node_id="tool_tasks_create",
+ node_type="tasksCreate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_tasks_list(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Tasks list via Google API."""
+ from services.handlers.tasks import handle_tasks_list
+
+ parameters = {**node_params, **args}
+ return await handle_tasks_list(
+ node_id="tool_tasks_list",
+ node_type="tasksList",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_tasks_complete(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Tasks complete via Google API."""
+ from services.handlers.tasks import handle_tasks_complete
+
+ parameters = {**node_params, **args}
+ return await handle_tasks_complete(
+ node_id="tool_tasks_complete",
+ node_type="tasksComplete",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_tasks_update(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Tasks update via Google API."""
+ from services.handlers.tasks import handle_tasks_update
+
+ parameters = {**node_params, **args}
+ return await handle_tasks_update(
+ node_id="tool_tasks_update",
+ node_type="tasksUpdate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_tasks_delete(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Tasks delete via Google API."""
+ from services.handlers.tasks import handle_tasks_delete
+
+ parameters = {**node_params, **args}
+ return await handle_tasks_delete(
+ node_id="tool_tasks_delete",
+ node_type="tasksDelete",
+ parameters=parameters,
+ context={}
+ )
+
+
+# ---------------------------------------------------------------------------
+# Google Contacts Tools
+# ---------------------------------------------------------------------------
+
+async def _execute_contacts_create(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts create via Google People API."""
+ from services.handlers.contacts import handle_contacts_create
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_create(
+ node_id="tool_contacts_create",
+ node_type="contactsCreate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_contacts_list(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts list via Google People API."""
+ from services.handlers.contacts import handle_contacts_list
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_list(
+ node_id="tool_contacts_list",
+ node_type="contactsList",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_contacts_search(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts search via Google People API."""
+ from services.handlers.contacts import handle_contacts_search
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_search(
+ node_id="tool_contacts_search",
+ node_type="contactsSearch",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_contacts_get(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts get via Google People API."""
+ from services.handlers.contacts import handle_contacts_get
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_get(
+ node_id="tool_contacts_get",
+ node_type="contactsGet",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_contacts_update(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts update via Google People API."""
+ from services.handlers.contacts import handle_contacts_update
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_update(
+ node_id="tool_contacts_update",
+ node_type="contactsUpdate",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_contacts_delete(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Contacts delete via Google People API."""
+ from services.handlers.contacts import handle_contacts_delete
+
+ parameters = {**node_params, **args}
+ return await handle_contacts_delete(
+ node_id="tool_contacts_delete",
+ node_type="contactsDelete",
+ parameters=parameters,
+ context={}
+ )
+
+
async def _execute_generic(args: Dict[str, Any],
config: Dict[str, Any]) -> Dict[str, Any]:
"""Execute a generic tool (fallback handler).
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 65527f99..efc9c6fa 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -39,6 +39,22 @@ from services.handlers import (
handle_twitter_send, handle_twitter_search, handle_twitter_user,
handle_gmail_send, handle_gmail_search, handle_gmail_read,
)
+from services.handlers.calendar import (
+ handle_calendar_create, handle_calendar_list, handle_calendar_update, handle_calendar_delete,
+)
+from services.handlers.drive import (
+ handle_drive_upload, handle_drive_download, handle_drive_list, handle_drive_share,
+)
+from services.handlers.sheets import (
+ handle_sheets_read, handle_sheets_write, handle_sheets_append,
+)
+from services.handlers.tasks import (
+ handle_tasks_create, handle_tasks_list, handle_tasks_complete, handle_tasks_update, handle_tasks_delete,
+)
+from services.handlers.contacts import (
+ handle_contacts_create, handle_contacts_list, handle_contacts_search,
+ handle_contacts_get, handle_contacts_update, handle_contacts_delete,
+)
if TYPE_CHECKING:
from core.config import Settings
@@ -144,6 +160,33 @@ class NodeExecutor:
'gmailSend': handle_gmail_send,
'gmailSearch': handle_gmail_search,
'gmailRead': handle_gmail_read,
+ # Google Calendar
+ 'calendarCreate': handle_calendar_create,
+ 'calendarList': handle_calendar_list,
+ 'calendarUpdate': handle_calendar_update,
+ 'calendarDelete': handle_calendar_delete,
+ # Google Drive
+ 'driveUpload': handle_drive_upload,
+ 'driveDownload': handle_drive_download,
+ 'driveList': handle_drive_list,
+ 'driveShare': handle_drive_share,
+ # Google Sheets
+ 'sheetsRead': handle_sheets_read,
+ 'sheetsWrite': handle_sheets_write,
+ 'sheetsAppend': handle_sheets_append,
+ # Google Tasks
+ 'tasksCreate': handle_tasks_create,
+ 'tasksList': handle_tasks_list,
+ 'tasksComplete': handle_tasks_complete,
+ 'tasksUpdate': handle_tasks_update,
+ 'tasksDelete': handle_tasks_delete,
+ # Google Contacts (People API)
+ 'contactsCreate': handle_contacts_create,
+ 'contactsList': handle_contacts_list,
+ 'contactsSearch': handle_contacts_search,
+ 'contactsGet': handle_contacts_get,
+ 'contactsUpdate': handle_contacts_update,
+ 'contactsDelete': handle_contacts_delete,
# Social (unified messaging)
# Note: socialReceive handled in _dispatch with connected_outputs
'socialSend': handle_social_send,
diff --git a/server/skills/GUIDE.md b/server/skills/GUIDE.md
index 53ed59d7..08e1e49a 100644
--- a/server/skills/GUIDE.md
+++ b/server/skills/GUIDE.md
@@ -8,19 +8,58 @@ Skills are organized in subfolders under `server/skills/`:
```
server/skills/
-├── GUIDE.md # This file
-├── assistant/ # General-purpose assistant skills
+├── GUIDE.md # This file
+├── assistant/ # General-purpose assistant skills
│ ├── assistant-personality/SKILL.md
-│ ├── code-skill/SKILL.md
-│ ├── http-skill/SKILL.md
-│ ├── maps-skill/SKILL.md
+│ ├── compaction-skill/SKILL.md
+│ ├── humanify-skill/SKILL.md
│ ├── memory-skill/SKILL.md
-│ ├── scheduler-skill/SKILL.md
-│ ├── web-search-skill/SKILL.md
-│ └── whatsapp-skill/SKILL.md
-└── android/ # Android device control skills
- ├── personality/SKILL.md
- └── skill/SKILL.md
+│ └── subagent-skill/SKILL.md
+├── android_agent/ # Android device control skills
+│ ├── personality/SKILL.md
+│ ├── battery-skill/SKILL.md
+│ ├── wifi-skill/SKILL.md
+│ ├── bluetooth-skill/SKILL.md
+│ ├── location-skill/SKILL.md
+│ ├── app-launcher-skill/SKILL.md
+│ ├── app-list-skill/SKILL.md
+│ ├── audio-skill/SKILL.md
+│ ├── screen-control-skill/SKILL.md
+│ ├── camera-skill/SKILL.md
+│ ├── motion-skill/SKILL.md
+│ └── environmental-skill/SKILL.md
+├── autonomous/ # Autonomous agent patterns
+│ ├── code-mode-skill/SKILL.md
+│ ├── agentic-loop-skill/SKILL.md
+│ ├── progressive-discovery-skill/SKILL.md
+│ ├── error-recovery-skill/SKILL.md
+│ └── multi-tool-orchestration-skill/SKILL.md
+├── coding_agent/ # Code execution skills
+│ ├── python-skill/SKILL.md
+│ └── javascript-skill/SKILL.md
+├── productivity_agent/ # Google Workspace skills
+│ ├── gmail-skill/SKILL.md
+│ ├── calendar-skill/SKILL.md
+│ ├── drive-skill/SKILL.md
+│ ├── sheets-skill/SKILL.md
+│ ├── tasks-skill/SKILL.md
+│ └── contacts-skill/SKILL.md
+├── social_agent/ # Social messaging skills
+│ ├── whatsapp-send-skill/SKILL.md
+│ ├── whatsapp-db-skill/SKILL.md
+│ ├── twitter-send-skill/SKILL.md
+│ ├── twitter-search-skill/SKILL.md
+│ └── twitter-user-skill/SKILL.md
+├── task_agent/ # Task management skills
+│ ├── timer-skill/SKILL.md
+│ ├── cron-scheduler-skill/SKILL.md
+│ └── task-manager-skill/SKILL.md
+├── travel_agent/ # Location and maps skills
+│ ├── geocoding-skill/SKILL.md
+│ └── nearby-places-skill/SKILL.md
+└── web_agent/ # Web automation skills
+ ├── web-search-skill/SKILL.md
+ └── http-request-skill/SKILL.md
```
Each top-level folder (e.g. `assistant`, `android`) appears as an option in the Master Skill node's folder dropdown. Skills inside are discovered recursively via `SKILL.md` files.
diff --git a/server/skills/productivity_agent/calendar-skill/SKILL.md b/server/skills/productivity_agent/calendar-skill/SKILL.md
new file mode 100644
index 00000000..a988877d
--- /dev/null
+++ b/server/skills/productivity_agent/calendar-skill/SKILL.md
@@ -0,0 +1,161 @@
+---
+name: calendar-skill
+description: Create, list, update, and delete Google Calendar events. Supports attendees, reminders, and recurring events.
+allowed-tools: calendar_create calendar_list calendar_update calendar_delete
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "📅"
+ color: "#4285F4"
+---
+
+# Google Calendar Skill
+
+Manage Google Calendar events - create, list, update, and delete.
+
+## Available Tools
+
+### calendar_create
+
+Create a new calendar event.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| title | string | Yes | Event title/summary |
+| start_time | string | Yes | Start time in ISO 8601 format |
+| end_time | string | Yes | End time in ISO 8601 format |
+| description | string | No | Event description |
+| location | string | No | Event location |
+| attendees | string | No | Comma-separated email addresses |
+| reminder_minutes | integer | No | Minutes before event for reminder |
+| timezone | string | No | Timezone (default: user's timezone) |
+
+**Example - Simple event:**
+```json
+{
+ "title": "Team Meeting",
+ "start_time": "2024-02-01T14:00:00",
+ "end_time": "2024-02-01T15:00:00",
+ "description": "Weekly team sync"
+}
+```
+
+**Example - Event with attendees:**
+```json
+{
+ "title": "Project Review",
+ "start_time": "2024-02-01T10:00:00",
+ "end_time": "2024-02-01T11:30:00",
+ "location": "Conference Room A",
+ "reminder_minutes": 30
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "event_id": "abc123xyz",
+ "title": "Team Meeting",
+ "html_link": "https://calendar.google.com/event?eid=..."
+}
+```
+
+### calendar_list
+
+List calendar events within a date range.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| start_date | string | No | Start date (ISO 8601, default: today) |
+| end_date | string | No | End date (ISO 8601, default: 7 days ahead) |
+| max_results | integer | No | Maximum results (default: 10, max: 100) |
+| calendar_id | string | No | Calendar ID (default: primary) |
+
+**Example - List this week's events:**
+```json
+{
+ "start_date": "2024-02-01",
+ "end_date": "2024-02-07",
+ "max_results": 20
+}
+```
+
+**Response:**
+```json
+{
+ "events": [
+ {
+ "id": "abc123",
+ "title": "Team Meeting",
+ "start": "2024-02-01T14:00:00Z",
+ "end": "2024-02-01T15:00:00Z",
+ "location": "Conference Room A",
+ "attendees": ["[email protected]"]
+ }
+ ],
+ "count": 1
+}
+```
+
+### calendar_update
+
+Update an existing calendar event.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| event_id | string | Yes | Event ID to update |
+| title | string | No | New title |
+| start_time | string | No | New start time |
+| end_time | string | No | New end time |
+| description | string | No | New description |
+| location | string | No | New location |
+| attendees | string | No | New attendees (replaces existing) |
+
+**Example:**
+```json
+{
+ "event_id": "abc123xyz",
+ "title": "Updated Team Meeting",
+ "start_time": "2024-02-01T15:00:00",
+ "end_time": "2024-02-01T16:00:00"
+}
+```
+
+### calendar_delete
+
+Delete a calendar event.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| event_id | string | Yes | Event ID to delete |
+| calendar_id | string | No | Calendar ID (default: primary) |
+
+**Example:**
+```json
+{
+ "event_id": "abc123xyz"
+}
+```
+
+## Date/Time Formats
+
+- **ISO 8601**: `2024-02-01T14:00:00` (local time)
+- **With timezone**: `2024-02-01T14:00:00-05:00` (EST)
+- **UTC**: `2024-02-01T19:00:00Z`
+- **Date only**: `2024-02-01` (all-day event)
+
+## Common Workflows
+
+1. **Schedule a meeting**: Create event with attendees, they receive invites
+2. **Check availability**: List events for a date range
+3. **Reschedule**: Update event with new times
+4. **Cancel meeting**: Delete the event
+
+## Setup Requirements
+
+1. Connect Calendar nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure Calendar API scopes are authorized
diff --git a/server/skills/productivity_agent/contacts-skill/SKILL.md b/server/skills/productivity_agent/contacts-skill/SKILL.md
new file mode 100644
index 00000000..2d3efbf4
--- /dev/null
+++ b/server/skills/productivity_agent/contacts-skill/SKILL.md
@@ -0,0 +1,188 @@
+---
+name: contacts-skill
+description: Create, list, and search Google Contacts. Supports names, emails, phone numbers, and organizations.
+allowed-tools: contacts_create contacts_list contacts_search
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "👥"
+ color: "#4285F4"
+---
+
+# Google Contacts Skill
+
+Manage Google Contacts - create, list, and search contacts.
+
+## Available Tools
+
+### contacts_create
+
+Create a new contact.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| first_name | string | Yes | Contact's first name |
+| last_name | string | No | Contact's last name |
+| email | string | No | Email address |
+| phone | string | No | Phone number |
+| company | string | No | Company/organization name |
+| job_title | string | No | Job title |
+| notes | string | No | Notes about contact |
+
+**Example - Basic contact:**
+```json
+{
+ "first_name": "John",
+ "last_name": "Smith",
+ "email": "[email protected]",
+ "phone": "+1-555-123-4567"
+}
+```
+
+**Example - Full contact:**
+```json
+{
+ "first_name": "Jane",
+ "last_name": "Doe",
+ "email": "[email protected]",
+ "phone": "+1-555-987-6543",
+ "company": "Acme Corporation",
+ "job_title": "Senior Engineer",
+ "notes": "Met at tech conference 2024"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "resource_name": "people/c1234567890",
+ "display_name": "John Smith",
+ "email": "[email protected]",
+ "phone": "+1-555-123-4567"
+}
+```
+
+### contacts_list
+
+List contacts from your address book.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| page_size | integer | No | Results per page (default: 20, max: 100) |
+| page_token | string | No | Token for next page |
+| sort_order | string | No | Sort by: LAST_MODIFIED_ASCENDING, LAST_MODIFIED_DESCENDING, FIRST_NAME_ASCENDING, LAST_NAME_ASCENDING |
+
+**Example - List contacts:**
+```json
+{
+ "page_size": 50,
+ "sort_order": "FIRST_NAME_ASCENDING"
+}
+```
+
+**Response:**
+```json
+{
+ "contacts": [
+ {
+ "resource_name": "people/c1234567890",
+ "display_name": "Alice Johnson",
+ "email": "[email protected]",
+ "phone": "+1-555-111-2222",
+ "company": "Tech Corp",
+ "job_title": "Product Manager"
+ },
+ {
+ "resource_name": "people/c0987654321",
+ "display_name": "Bob Williams",
+ "email": "[email protected]",
+ "phone": "+1-555-333-4444"
+ }
+ ],
+ "count": 2,
+ "next_page_token": "..."
+}
+```
+
+### contacts_search
+
+Search contacts by name or email.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| query | string | Yes | Search query (name or email) |
+| page_size | integer | No | Results per page (default: 10, max: 30) |
+
+**Example - Search by name:**
+```json
+{
+ "query": "John"
+}
+```
+
+**Example - Search by email domain:**
+```json
+{
+ "query": "@company.com"
+}
+```
+
+**Response:**
+```json
+{
+ "contacts": [
+ {
+ "resource_name": "people/c1234567890",
+ "display_name": "John Smith",
+ "email": "[email protected]",
+ "phone": "+1-555-123-4567",
+ "company": "Example Inc"
+ }
+ ],
+ "count": 1
+}
+```
+
+## Contact Fields
+
+| Field | Description |
+|-------|-------------|
+| `resource_name` | Unique identifier (people/cXXX) |
+| `display_name` | Full formatted name |
+| `first_name` | Given name |
+| `last_name` | Family name |
+| `email` | Primary email address |
+| `phone` | Primary phone number |
+| `company` | Organization name |
+| `job_title` | Position/title |
+| `notes` | Free-form notes |
+
+## Phone Number Formats
+
+Accepted formats:
+- `+1-555-123-4567` (international)
+- `(555) 123-4567` (US format)
+- `555-123-4567` (simple)
+- `5551234567` (digits only)
+
+## Common Workflows
+
+1. **Add new contact**: Create with basic info after meeting someone
+2. **Find contact**: Search by name to get their details
+3. **Build mailing list**: List contacts, filter by company
+4. **Update CRM**: Export contacts for business use
+
+## Tips
+
+- Search is case-insensitive
+- Partial matches work for names
+- Email search matches any part of address
+- Use page_token for pagination through large lists
+
+## Setup Requirements
+
+1. Connect Contacts nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure People API (Contacts) scopes are authorized
diff --git a/server/skills/productivity_agent/drive-skill/SKILL.md b/server/skills/productivity_agent/drive-skill/SKILL.md
new file mode 100644
index 00000000..f25e828e
--- /dev/null
+++ b/server/skills/productivity_agent/drive-skill/SKILL.md
@@ -0,0 +1,202 @@
+---
+name: drive-skill
+description: Upload, download, list, and share Google Drive files. Supports folders, file search, and permission management.
+allowed-tools: drive_upload drive_download drive_list drive_share
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "📁"
+ color: "#0F9D58"
+---
+
+# Google Drive Skill
+
+Manage Google Drive files - upload, download, list, and share.
+
+## Available Tools
+
+### drive_upload
+
+Upload a file to Google Drive.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| file_url | string | Yes* | URL of file to upload |
+| file_content | string | Yes* | Base64 encoded file content |
+| filename | string | Yes | Name for the uploaded file |
+| folder_id | string | No | Destination folder ID (default: root) |
+| mime_type | string | No | File MIME type (auto-detected if not provided) |
+
+*Either `file_url` OR `file_content` is required.
+
+**Example - Upload from URL:**
+```json
+{
+ "file_url": "https://example.com/report.pdf",
+ "filename": "Q4_Report.pdf",
+ "folder_id": "1abc123def456"
+}
+```
+
+**Example - Upload with content:**
+```json
+{
+ "file_content": "SGVsbG8gV29ybGQh...",
+ "filename": "notes.txt",
+ "mime_type": "text/plain"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "file_id": "1xyz789abc",
+ "name": "Q4_Report.pdf",
+ "web_link": "https://drive.google.com/file/d/1xyz789abc/view",
+ "size": 102400
+}
+```
+
+### drive_download
+
+Download a file from Google Drive.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| file_id | string | Yes | File ID to download |
+| output_path | string | No | Local path to save file |
+
+**Example:**
+```json
+{
+ "file_id": "1xyz789abc"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "file_id": "1xyz789abc",
+ "name": "report.pdf",
+ "mime_type": "application/pdf",
+ "size": 102400,
+ "content": "base64_encoded_content..."
+}
+```
+
+### drive_list
+
+List files in Google Drive.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| folder_id | string | No | Folder ID (default: root) |
+| query | string | No | Search query |
+| max_results | integer | No | Maximum results (default: 10, max: 100) |
+| file_types | string | No | Filter by MIME types (comma-separated) |
+
+**Query Syntax:**
+- `name contains 'report'` - Files with "report" in name
+- `mimeType = 'application/pdf'` - PDF files only
+- `modifiedTime > '2024-01-01'` - Recently modified
+- `'folder_id' in parents` - Files in specific folder
+- `trashed = false` - Exclude trashed files
+
+**Example - List folder contents:**
+```json
+{
+ "folder_id": "1abc123def456",
+ "max_results": 20
+}
+```
+
+**Example - Search for PDFs:**
+```json
+{
+ "query": "name contains 'invoice' and mimeType = 'application/pdf'",
+ "max_results": 50
+}
+```
+
+**Response:**
+```json
+{
+ "files": [
+ {
+ "id": "1xyz789abc",
+ "name": "invoice_001.pdf",
+ "mime_type": "application/pdf",
+ "size": 51200,
+ "created_time": "2024-01-15T10:30:00Z",
+ "modified_time": "2024-01-15T10:30:00Z",
+ "web_link": "https://drive.google.com/file/d/1xyz789abc/view"
+ }
+ ],
+ "count": 1,
+ "next_page_token": "..."
+}
+```
+
+### drive_share
+
+Share a file with specific users.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| file_id | string | Yes | File ID to share |
+| email | string | Yes | Email address to share with |
+| role | string | No | Permission role (default: reader) |
+| send_notification | boolean | No | Send email notification (default: true) |
+
+**Roles:**
+- `reader` - View only
+- `commenter` - View and comment
+- `writer` - View, comment, and edit
+
+**Example:**
+```json
+{
+ "file_id": "1xyz789abc",
+ "email": "[email protected]",
+ "role": "writer"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "file_id": "1xyz789abc",
+ "shared_with": "[email protected]",
+ "role": "writer",
+ "share_link": "https://drive.google.com/file/d/1xyz789abc/view?usp=sharing"
+}
+```
+
+## Common MIME Types
+
+| Type | MIME Type |
+|------|-----------|
+| PDF | `application/pdf` |
+| Word | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
+| Excel | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
+| PowerPoint | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
+| Google Doc | `application/vnd.google-apps.document` |
+| Google Sheet | `application/vnd.google-apps.spreadsheet` |
+| Folder | `application/vnd.google-apps.folder` |
+
+## Common Workflows
+
+1. **Backup files**: Upload local files to Drive folder
+2. **Share report**: Upload file, then share with team
+3. **Find files**: List with search query
+4. **Download for processing**: Download, process locally, re-upload
+
+## Setup Requirements
+
+1. Connect Drive nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure Drive API scopes are authorized
diff --git a/server/skills/productivity_agent/gmail-skill/SKILL.md b/server/skills/productivity_agent/gmail-skill/SKILL.md
new file mode 100644
index 00000000..ad412a04
--- /dev/null
+++ b/server/skills/productivity_agent/gmail-skill/SKILL.md
@@ -0,0 +1,140 @@
+---
+name: gmail-skill
+description: Send, search, and read Gmail emails. Supports composing emails with attachments, searching by query, and reading email content.
+allowed-tools: gmail_send gmail_search gmail_read
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "📧"
+ color: "#EA4335"
+---
+
+# Gmail Skill
+
+Send, search, and read emails using Gmail API.
+
+## Available Tools
+
+### gmail_send
+
+Send an email message.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| to | string | Yes | Recipient email address |
+| subject | string | Yes | Email subject line |
+| body | string | Yes | Email body (plain text or HTML) |
+| cc | string | No | CC recipients (comma-separated) |
+| bcc | string | No | BCC recipients (comma-separated) |
+| is_html | boolean | No | Set true for HTML body (default: false) |
+
+**Example - Send plain text email:**
+```json
+{
+ "subject": "Meeting Tomorrow",
+ "body": "Hi,\n\nJust a reminder about our meeting tomorrow at 2pm.\n\nBest regards"
+}
+```
+
+**Example - Send HTML email:**
+```json
+{
+ "subject": "Weekly Report",
+ "body": "<h1>Weekly Report</h1><p>Here are the highlights...</p>",
+ "is_html": true
+}
+```
+
+### gmail_search
+
+Search emails using Gmail query syntax.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| query | string | Yes | Gmail search query |
+| max_results | integer | No | Maximum results (default: 10, max: 100) |
+
+**Query Syntax Examples:**
+- `from:[email protected]` - Emails from specific sender
+- `to:[email protected]` - Emails to specific recipient
+- `subject:meeting` - Emails with "meeting" in subject
+- `has:attachment` - Emails with attachments
+- `is:unread` - Unread emails
+- `after:2024/01/01` - Emails after date
+- `before:2024/12/31` - Emails before date
+- `label:important` - Emails with label
+- `"exact phrase"` - Exact phrase match
+- `from:[email protected] is:unread` - Combine multiple filters
+
+**Example:**
+```json
+{
+ "query": "from:[email protected] has:attachment after:2024/01/01",
+ "max_results": 20
+}
+```
+
+**Response:**
+```json
+{
+ "emails": [
+ {
+ "id": "abc123",
+ "thread_id": "thread456",
+ "subject": "Project Files",
+ "from": "[email protected]",
+ "date": "2024-01-15T10:30:00Z",
+ "snippet": "Please find attached..."
+ }
+ ],
+ "count": 1
+}
+```
+
+### gmail_read
+
+Read full email content by ID.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| email_id | string | Yes | Email ID from search results |
+
+**Example:**
+```json
+{
+ "email_id": "abc123"
+}
+```
+
+**Response:**
+```json
+{
+ "id": "abc123",
+ "thread_id": "thread456",
+ "subject": "Project Files",
+ "from": "[email protected]",
+ "date": "2024-01-15T10:30:00Z",
+ "body": "Full email body content...",
+ "attachments": [
+ {"filename": "report.pdf", "mime_type": "application/pdf", "size": 102400}
+ ]
+}
+```
+
+## Common Workflows
+
+1. **Check unread emails**: Search with `is:unread`, then read important ones
+2. **Find emails from someone**: Search with `from:[email protected]`
+3. **Reply to email**: Read the email first, then send with same subject prefixed with "Re:"
+4. **Forward email**: Read email, send to new recipient with "Fwd:" prefix
+
+## Setup Requirements
+
+1. Connect Gmail nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure Gmail API scopes are authorized
diff --git a/server/skills/productivity_agent/sheets-skill/SKILL.md b/server/skills/productivity_agent/sheets-skill/SKILL.md
new file mode 100644
index 00000000..4b453811
--- /dev/null
+++ b/server/skills/productivity_agent/sheets-skill/SKILL.md
@@ -0,0 +1,181 @@
+---
+name: sheets-skill
+description: Read, write, and append data to Google Sheets spreadsheets. Supports cell ranges, formulas, and batch operations.
+allowed-tools: sheets_read sheets_write sheets_append
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "📊"
+ color: "#0F9D58"
+---
+
+# Google Sheets Skill
+
+Read and write data to Google Sheets spreadsheets.
+
+## Available Tools
+
+### sheets_read
+
+Read data from a spreadsheet range.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| spreadsheet_id | string | Yes | Spreadsheet ID from URL |
+| range | string | Yes | A1 notation range (e.g., "Sheet1!A1:D10") |
+
+**How to find Spreadsheet ID:**
+From URL: `https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit`
+
+**Range Notation (A1):**
+- `Sheet1!A1:D10` - Specific range on Sheet1
+- `Sheet1!A:D` - Entire columns A through D
+- `Sheet1!1:10` - Rows 1 through 10
+- `A1:D10` - Default sheet, specific range
+- `Sheet1` - Entire sheet
+
+**Example:**
+```json
+{
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "range": "Sheet1!A1:E10"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "range": "Sheet1!A1:E10",
+ "values": [
+ ["Name", "Email", "Department", "Start Date", "Status"],
+ ["Alice", "[email protected]", "Engineering", "2023-01-15", "Active"],
+ ["Bob", "[email protected]", "Marketing", "2023-03-20", "Active"]
+ ],
+ "rows": 3,
+ "columns": 5
+}
+```
+
+### sheets_write
+
+Write data to a specific range (overwrites existing data).
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| spreadsheet_id | string | Yes | Spreadsheet ID |
+| range | string | Yes | A1 notation range |
+| values | array | Yes | 2D array of values |
+| value_input_option | string | No | How to interpret values (default: USER_ENTERED) |
+
+**Value Input Options:**
+- `USER_ENTERED` - Parse values as if typed by user (formulas work)
+- `RAW` - Store values as-is (no parsing)
+
+**Example - Write data:**
+```json
+{
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "range": "Sheet1!A1:C3",
+ "values": [
+ ["Name", "Score", "Grade"],
+ ["Alice", 95, "A"],
+ ["Bob", 87, "B"]
+ ]
+}
+```
+
+**Example - Write formula:**
+```json
+{
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "range": "Sheet1!D2",
+ "values": [["=SUM(B2:C2)"]],
+ "value_input_option": "USER_ENTERED"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "updated_range": "Sheet1!A1:C3",
+ "updated_rows": 3,
+ "updated_columns": 3,
+ "updated_cells": 9
+}
+```
+
+### sheets_append
+
+Append rows to the end of a table.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| spreadsheet_id | string | Yes | Spreadsheet ID |
+| range | string | Yes | Table range (e.g., "Sheet1!A:E") |
+| values | array | Yes | 2D array of rows to append |
+| value_input_option | string | No | How to interpret values (default: USER_ENTERED) |
+| insert_data_option | string | No | How to insert (default: INSERT_ROWS) |
+
+**Insert Options:**
+- `INSERT_ROWS` - Insert new rows for data
+- `OVERWRITE` - Overwrite existing data after table
+
+**Example - Append new rows:**
+```json
+{
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "range": "Sheet1!A:E",
+ "values": [
+ ["Charlie", "[email protected]", "Sales", "2024-02-01", "Active"],
+ ["Diana", "[email protected]", "HR", "2024-02-15", "Active"]
+ ]
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "updated_range": "Sheet1!A4:E5",
+ "appended_rows": 2
+}
+```
+
+## Common Formulas
+
+| Formula | Description |
+|---------|-------------|
+| `=SUM(A1:A10)` | Sum of range |
+| `=AVERAGE(B1:B10)` | Average of range |
+| `=COUNT(A:A)` | Count numbers in column |
+| `=COUNTA(A:A)` | Count non-empty cells |
+| `=VLOOKUP(E1,A:C,2,FALSE)` | Vertical lookup |
+| `=IF(A1>90,"A","B")` | Conditional logic |
+| `=TODAY()` | Current date |
+| `=NOW()` | Current date and time |
+
+## Common Workflows
+
+1. **Import data**: Write headers, then append data rows
+2. **Update records**: Read to find row, write to specific cells
+3. **Generate reports**: Read data, process, write summary
+4. **Log entries**: Append new rows with timestamps
+
+## Tips
+
+- Always check spreadsheet exists before writing
+- Use `USER_ENTERED` for formulas to work
+- Range must match data dimensions
+- Append is safer than write for adding data
+
+## Setup Requirements
+
+1. Connect Sheets nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure Sheets API scopes are authorized
+4. Spreadsheet must be accessible to authenticated account
diff --git a/server/skills/productivity_agent/tasks-skill/SKILL.md b/server/skills/productivity_agent/tasks-skill/SKILL.md
new file mode 100644
index 00000000..92da80a1
--- /dev/null
+++ b/server/skills/productivity_agent/tasks-skill/SKILL.md
@@ -0,0 +1,183 @@
+---
+name: tasks-skill
+description: Create, list, and complete Google Tasks. Supports task lists, due dates, and notes.
+allowed-tools: tasks_create tasks_list tasks_complete
+metadata:
+ author: machina
+ version: "1.0"
+ category: productivity
+ icon: "✅"
+ color: "#4285F4"
+---
+
+# Google Tasks Skill
+
+Manage Google Tasks - create, list, and complete tasks.
+
+## Available Tools
+
+### tasks_create
+
+Create a new task.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| title | string | Yes | Task title |
+| notes | string | No | Task notes/description |
+| due_date | string | No | Due date (ISO 8601 or YYYY-MM-DD) |
+| tasklist_id | string | No | Task list ID (default: @default) |
+
+**Example - Simple task:**
+```json
+{
+ "title": "Review quarterly report"
+}
+```
+
+**Example - Task with details:**
+```json
+{
+ "title": "Submit expense report",
+ "notes": "Include receipts for conference travel",
+ "due_date": "2024-02-15"
+}
+```
+
+**Example - Task in specific list:**
+```json
+{
+ "title": "Buy groceries",
+ "tasklist_id": "MTIzNDU2Nzg5MA",
+ "due_date": "2024-02-01"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "task_id": "abc123xyz",
+ "title": "Submit expense report",
+ "status": "needsAction",
+ "due": "2024-02-15T00:00:00Z"
+}
+```
+
+### tasks_list
+
+List tasks from a task list.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| tasklist_id | string | No | Task list ID (default: @default) |
+| show_completed | boolean | No | Include completed tasks (default: false) |
+| show_hidden | boolean | No | Include hidden tasks (default: false) |
+| max_results | integer | No | Maximum results (default: 20, max: 100) |
+| due_min | string | No | Filter by minimum due date |
+| due_max | string | No | Filter by maximum due date |
+
+**Example - List pending tasks:**
+```json
+{
+ "show_completed": false,
+ "max_results": 50
+}
+```
+
+**Example - Tasks due this week:**
+```json
+{
+ "due_min": "2024-02-01",
+ "due_max": "2024-02-07"
+}
+```
+
+**Response:**
+```json
+{
+ "tasks": [
+ {
+ "id": "abc123xyz",
+ "title": "Submit expense report",
+ "notes": "Include receipts for conference travel",
+ "status": "needsAction",
+ "due": "2024-02-15T00:00:00Z",
+ "updated": "2024-02-01T10:30:00Z"
+ },
+ {
+ "id": "def456uvw",
+ "title": "Review quarterly report",
+ "status": "needsAction",
+ "updated": "2024-02-01T09:00:00Z"
+ }
+ ],
+ "count": 2
+}
+```
+
+### tasks_complete
+
+Mark a task as completed.
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| task_id | string | Yes | Task ID to complete |
+| tasklist_id | string | No | Task list ID (default: @default) |
+
+**Example:**
+```json
+{
+ "task_id": "abc123xyz"
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "task_id": "abc123xyz",
+ "title": "Submit expense report",
+ "status": "completed",
+ "completed": "2024-02-10T14:30:00Z"
+}
+```
+
+## Task Statuses
+
+| Status | Description |
+|--------|-------------|
+| `needsAction` | Task is pending |
+| `completed` | Task is done |
+
+## Date Formats
+
+- **ISO 8601**: `2024-02-15T14:00:00Z`
+- **Date only**: `2024-02-15` (interpreted as midnight UTC)
+
+## Working with Task Lists
+
+The default task list is `@default`. To work with custom lists:
+
+1. Use Google Tasks app to create lists
+2. Get list ID from API (not exposed in this skill yet)
+3. Pass `tasklist_id` parameter
+
+## Common Workflows
+
+1. **Daily review**: List pending tasks, prioritize
+2. **Add reminders**: Create tasks with due dates
+3. **Track completion**: Mark tasks done as you finish
+4. **Weekly planning**: Create tasks for the week ahead
+
+## Tips
+
+- Tasks without due dates appear at the top of the list
+- Completed tasks are hidden by default
+- Notes can contain multiline text
+- Due dates are in UTC timezone
+
+## Setup Requirements
+
+1. Connect Tasks nodes to AI Agent's `input-tools` handle
+2. Authenticate with Google Workspace in Credentials Modal
+3. Ensure Tasks API scopes are authorized