Skip to content

Self-improving AI Employees for everyone

feat: Add persistent Node.js server for JS/TS code execution

trohitgf3a552c3ea33
diff --git a/.env.template b/.env.template
index 005efc58..b6e46565 100644
--- a/.env.template
+++ b/.env.template
@@ -84,6 +84,10 @@ WHATSAPP_SERVICE_URL=http://localhost:5000
# Default port for AI proxy servers (e.g., Ollama, Claude Code CLI proxy)
AI_PROXY_DEFAULT_PORT=11434
+# OAuth Redirect URIs
+GMAIL_REDIRECT_URI=http://localhost:3010/api/gmail/callback
+TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback
+
# External API Keys (managed through UI, these are optional defaults)
OPENAI_API_KEY=
GOOGLE_MAPS_API_KEY=
diff --git a/CLAUDE.md b/CLAUDE.md
index e8b52360..27dcb944 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -17,6 +17,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Agent Delegation](./docs-internal/agent_delegation.md)** | How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool |
| **[Agent Teams](./docs-internal/agent_teams.md)** | Claude SDK Agent Teams pattern - AI Employee and Orchestrator nodes with input-teammates handle for multi-agent coordination |
| **[Memory Compaction](./docs-internal/memory_compaction.md)** | Token tracking and memory compaction service using native provider APIs (Anthropic, OpenAI) |
+| **[Pricing Service](./docs-internal/pricing_service.md)** | Centralized cost tracking for LLM tokens and API services (Twitter, Google Maps) with HTTPX event hooks |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Workflow Schema](./docs-internal/workflow-schema.md)** | JSON schema for workflows, edge handle conventions, config node architecture |
| **[Execution Engine Design](./docs-internal/DESIGN.md)** | Architecture patterns, design standards, and implementation details for the workflow execution engine |
@@ -60,6 +61,9 @@ server/services/
├── node_executor.py # Single node execution with registry pattern
├── parameter_resolver.py # Template variable resolution
├── agent_team.py # AgentTeamService for multi-agent coordination
+├── nodejs_client.py # HTTP client for Node.js code executor
+├── pricing.py # LLM and API cost calculation (loads config/pricing.json)
+├── tracked_http.py # HTTPX event hooks for automatic API cost tracking
├── deployment/ # Event-driven deployment lifecycle
│ ├── __init__.py
│ ├── state.py # DeploymentState, TriggerInfo dataclasses
@@ -89,7 +93,17 @@ server/core/
server/models/
├── cache.py # CacheEntry SQLModel for SQLite cache
├── auth.py # User model with bcrypt
-└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage, TokenUsageMetric, CompactionEvent, SessionTokenState, UserSettings, ProviderDefaults, AgentTeam, TeamMember, TeamTask, AgentMessage tables
+└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage, TokenUsageMetric, APIUsageMetric, CompactionEvent, SessionTokenState, UserSettings, ProviderDefaults, AgentTeam, TeamMember, TeamTask, AgentMessage tables
+
+server/config/
+└── pricing.json # User-editable pricing config for LLM models and API services
+
+server/nodejs/ # Persistent Node.js server for JS/TS execution
+├── package.json # Dependencies: express, tsx
+├── tsconfig.json # TypeScript config (ES2024)
+├── src/
+│ └── index.ts # Express server (/execute, /health, /packages/*)
+└── user-packages/ # User-installed npm packages
```
### Polyglot Server Integration (Optional)
@@ -179,6 +193,59 @@ POLYGLOT_SERVER_URL=http://localhost:8080 # polyglot-server address
**Current Status**: Standalone integration files created. Not wired into NodeExecutor to avoid disturbing existing workflow execution flow. Future integration will add polyglot node types to handler registry via `functools.partial` pattern.
+### Node.js Code Executor
+Persistent Node.js server for JavaScript/TypeScript code execution, replacing subprocess spawning per execution.
+
+**Architecture:**
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Python Backend (port 3010) │
+│ ┌────────────────┐ HTTP/JSON ┌──────────────────┐ │
+│ │ NodeJSClient │◄──────────────────►│ Node.js Server │ │
+│ │ (aiohttp) │ localhost:3020 │ (Express + tsx) │ │
+│ └────────────────┘ └──────────────────┘ │
+│ ▲ │
+│ │ │
+│ ┌──────┴─────────┐ │
+│ │ code.py │ │
+│ │ handlers │ │
+│ └────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+```
+
+**Files:**
+```
+server/nodejs/
+├── package.json # Dependencies: express, tsx
+├── tsconfig.json # TypeScript config (ES2024)
+├── src/
+│ └── index.ts # Express server with /execute, /health, /packages/*
+└── user-packages/ # User npm packages directory
+ └── package.json
+
+server/services/
+├── nodejs_client.py # Async HTTP client for Node.js server
+└── handlers/
+ └── code.py # handle_javascript_executor, handle_typescript_executor
+```
+
+**Endpoints:**
+| Endpoint | Method | Description |
+|----------|--------|-------------|
+| `/health` | GET | Health check with Node.js version |
+| `/execute` | POST | Execute JS/TS code with input_data and timeout |
+| `/packages/install` | POST | Install npm packages to user-packages |
+| `/packages` | GET | List installed packages |
+
+**Environment Variables:**
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `NODEJS_EXECUTOR_URL` | `http://localhost:3020` | Server URL for Python client |
+| `NODEJS_EXECUTOR_TIMEOUT` | `30` | Request timeout in seconds |
+| `NODEJS_EXECUTOR_PORT` | `3020` | Server port |
+| `NODEJS_EXECUTOR_HOST` | `localhost` | Server host |
+| `NODEJS_EXECUTOR_BODY_LIMIT` | `10mb` | Max request body size |
+
**Key Modules:**
| Module | Responsibility | Pattern |
@@ -292,7 +359,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **83 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 + 2 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow)
+- **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)
- **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
@@ -324,7 +391,7 @@ The project was completely refactored from schema-based node definitions to expl
- `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)
-- `src/nodeDefinitions/codeNodes.ts` - Python and JavaScript code execution nodes
+- `src/nodeDefinitions/codeNodes.ts` - Python, JavaScript, and TypeScript code execution nodes
- `src/nodeDefinitions/utilityNodes.ts` - HTTP, Webhook, chatTrigger, and console nodes
- `src/nodeDefinitions/documentNodes.ts` - Document processing nodes (httpScraper, fileDownloader, documentParser, textChunker, embeddingGenerator, vectorStore)
- `src/nodeDefinitions/chatNodes.ts` - Chat send and history nodes
@@ -690,7 +757,8 @@ Nodes that work BOTH as standalone workflow nodes AND as AI Agent tools. When co
- **whatsappSend**: Send WhatsApp messages (text, media, location, contact). Full schema for all message types.
- **whatsappDb**: Query WhatsApp database - chat history, contacts, groups with filtering and pagination.
- **pythonExecutor**: Execute Python code for calculations, data processing, and automation. Tool name: `python_code`. Available: math, json, datetime, Counter, defaultdict, random.
-- **javascriptExecutor**: Execute JavaScript code for calculations, data processing, and JSON manipulation. Tool name: `javascript_code`.
+- **javascriptExecutor**: Execute JavaScript code via persistent Node.js server for calculations, data processing, and JSON manipulation. Tool name: `javascript_code`.
+- **typescriptExecutor**: Execute TypeScript code via persistent Node.js server with type safety. Tool name: `typescript_code`.
- **gmaps_locations**: Google Maps Geocoding service for address-to-coordinates conversion. Tool name: `geocode`.
- **gmaps_nearby_places**: Google Places API nearbySearch. Tool name: `nearby_places`.
@@ -839,9 +907,10 @@ TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback
- **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.
-### Code Nodes (2 nodes)
+### Code Nodes (3 nodes)
- **pythonExecutor**: **Dual-purpose node** - Execute Python code with syntax-highlighted editor, input_data access, and console output. Works as workflow node OR AI Agent tool (`python_code`). Available libraries: math, json, datetime, timedelta, re, random, Counter, defaultdict.
-- **javascriptExecutor**: **Dual-purpose node** - Execute JavaScript code with syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`javascript_code`).
+- **javascriptExecutor**: **Dual-purpose node** - Execute JavaScript code via persistent Node.js server with syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`javascript_code`).
+- **typescriptExecutor**: **Dual-purpose node** - Execute TypeScript code via persistent Node.js server with type safety, syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`typescript_code`).
### Utility Nodes (6 nodes)
- **httpRequest**: Make HTTP requests to external APIs (GET, POST, PUT, DELETE, PATCH) with configurable headers, body, and timeout
@@ -1062,7 +1131,8 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
## Current Status
✅ **INodeProperties System**: Fully implemented with 75 functional node components
✅ **WebSocket-First Architecture**: 87 message handlers replacing REST APIs
-✅ **Code Editor**: Python executor with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output
+✅ **Code Editor**: Python, JavaScript, and TypeScript executors with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output
+✅ **Node.js Executor**: Persistent Node.js server (Express + tsx) for fast JS/TS execution, replacing subprocess spawning
✅ **Component Palette**: Emoji icons with distinct dracula-themed category colors, localStorage persistence for collapsed sections
✅ **Android Integration**: 16 Android service nodes with ADB automation and remote WebSocket support
✅ **Conditional Parameter Display**: Dynamic UI rendering based on parameter values (displayOptions.show)
@@ -1893,11 +1963,13 @@ The project deploys using Docker Compose with nginx reverse proxy.
- Size: ~54 MB
**Backend (`server/Dockerfile`):**
-- Python 3.12-slim base
+- Python 3.12-slim base with Node.js 22.x for JS/TS execution
+- Includes persistent Node.js server (Express + tsx) on port 3020
- Optimized bytecode compilation (`python -O -m compileall`)
- Health check endpoint on port 3010
+- Startup script (`start.sh`) runs both Python and Node.js servers
- Depends on: redis, whatsapp
-- Size: ~528 MB
+- Size: ~600 MB
**WhatsApp (`docker/Dockerfile.whatsapp`):**
- Uses npm package `whatsapp-rpc` with pre-built binaries
@@ -2981,6 +3053,47 @@ compaction_svc.set_ai_service(container.ai_service())
- **100K Threshold**: Matches Claude Code's default (configurable per session)
- **Singleton Pattern**: Service accessible via `get_compaction_service()`
+## API Cost Tracking
+
+Centralized cost tracking for third-party API services (Twitter/X, Google Maps). See [Pricing Service](./docs-internal/pricing_service.md) for full documentation.
+
+### Two Tracking Methods
+
+**1. Manual Tracking** - For services using native SDKs:
+```python
+# server/services/handlers/twitter.py
+await _track_twitter_usage(node_id, 'tweet', 1, workflow_id, session_id)
+
+# server/services/maps.py
+await _track_maps_usage(node_id, 'geocode', 1, workflow_id, session_id)
+```
+
+**2. Automatic HTTPX Tracking** - For services using httpx client:
+```python
+from services.tracked_http import get_tracked_client, set_tracking_context
+
+set_tracking_context(node_id="twitter-1", session_id="user-123")
+client = get_tracked_client()
+response = await client.post("https://api.twitter.com/2/tweets", json={...})
+# Automatically tracked via HTTPX response event hook!
+```
+
+### Pricing Configuration
+
+All pricing in `server/config/pricing.json` (user-editable):
+- `llm`: Per-model token pricing (USD/MTok)
+- `api`: Per-service operation pricing (USD/request)
+- `operation_map`: Maps handler actions to pricing operations
+- `url_patterns`: Regex patterns for automatic HTTPX tracking
+
+### Database Storage
+
+`APIUsageMetric` table stores: service, operation, endpoint, resource_count, cost (USD)
+
+### Frontend Display
+
+`CredentialsModal.renderApiUsagePanel()` shows per-service usage and costs.
+
## AI Agent Tool System
### Overview
@@ -4319,4 +4432,5 @@ This function:
- **Workflow Export Sanitization**: `exportWorkflow()` in `useWorkflow.ts` strips transient fields (`selected`, `dragging`, `width`, `height`, `measured`, `positionAbsolute`) from nodes and edges before export. Only `id`, `type`, `position`, `data.label` are included per node.
- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution: node definition (SVG) > SKILL.md metadata (emoji) > fallback. Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor.
- **Example Workflows**: Auto-load example workflows from `workflows/` folder on first use. Uses `UserSettings.examples_loaded` flag to track import status. Supports anonymous users (`user_id="default"`). Reuses existing `database.save_workflow()` for import. See "Example Workflows" section for details.
+- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 3020 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. Handlers in `server/services/handlers/code.py` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).
- never use emojis in prints
\ No newline at end of file
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 149b41e7..f97c39b8 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -66,7 +66,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
const types: Record<string, React.ComponentType<any>> = {};
// Trigger nodes (no input handles) - check by group or specific types
- const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'chatTrigger', 'taskTrigger'];
+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'gmailReceive', 'chatTrigger', 'taskTrigger'];
// Pre-register specialized agent nodes explicitly to ensure they're always available
// This handles cases where nodeDefinitions iteration order might miss them
@@ -94,6 +94,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (type === 'twitterSend' || type === 'twitterSearch' || type === 'twitterUser') {
// Twitter action nodes use SquareNode (twitterReceive is a trigger)
types[type] = SquareNode;
+ } else if (type === 'gmailSend' || type === 'gmailSearch' || type === 'gmailRead') {
+ // Gmail action nodes use SquareNode (gmailReceive is a trigger)
+ 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/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index b66e8485..38a1b439 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -12,13 +12,14 @@ import {
ReloadOutlined,
DollarOutlined,
TwitterOutlined,
+ GoogleOutlined,
} from '@ant-design/icons';
import Modal from './ui/Modal';
import QRCodeDisplay from './ui/QRCodeDisplay';
import ApiKeyInput from './ui/ApiKeyInput';
import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary } from '../hooks/useApiKeys';
import { useAppTheme } from '../hooks/useAppTheme';
-import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
+import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGmailStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
import { useWhatsApp } from '../hooks/useWhatsApp';
import {
OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,
@@ -51,6 +52,10 @@ const XIcon = () => (
<TwitterOutlined style={{ fontSize: 20, color: '#000000' }} />
);
+const GmailIcon = () => (
+ <GoogleOutlined style={{ fontSize: 20, color: '#EA4335' }} />
+);
+
// ============================================================================
// TYPES & DATA
// ============================================================================
@@ -64,7 +69,7 @@ interface CredentialItem {
Icon?: React.FC<{ size?: number }>;
CustomIcon?: React.FC;
isSpecial?: boolean;
- panelType?: 'whatsapp' | 'android' | 'twitter' | 'google_maps';
+ panelType?: 'whatsapp' | 'android' | 'twitter' | 'gmail' | 'google_maps';
}
interface Category {
@@ -92,6 +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' },
],
},
{
@@ -126,6 +132,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const whatsappStatus = useWhatsAppStatus();
const androidStatus = useAndroidStatus();
const twitterStatus = useTwitterStatus();
+ const gmailStatus = useGmailStatus();
// Tag style helper - consistent theming for status tags
@@ -276,6 +283,8 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const panelType = selectedItem?.panelType;
if (panelType === 'twitter' && isConnected) {
loadApiUsage('twitter');
+ } else if (panelType === 'gmail' && isConnected) {
+ loadApiUsage('gmail');
} else if (panelType === 'google_maps' && isConnected) {
loadApiUsage('google_maps');
}
@@ -317,6 +326,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
if (item.panelType === 'twitter') {
return { connected: twitterStatus.connected, label: twitterStatus.connected ? `@${twitterStatus.username}` : 'Not Connected' };
}
+ if (item.panelType === 'gmail') {
+ return { connected: gmailStatus.connected, label: gmailStatus.connected ? gmailStatus.email : 'Not Connected' };
+ }
return null;
};
@@ -447,6 +459,13 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const [twitterLoading, setTwitterLoading] = useState<string | null>(null);
const [twitterError, setTwitterError] = useState<string | null>(null);
+ // Gmail state
+ const [gmailClientId, setGmailClientId] = useState('');
+ const [gmailClientSecret, setGmailClientSecret] = useState('');
+ const [gmailCredentialsStored, setGmailCredentialsStored] = useState<boolean | null>(null);
+ const [gmailLoading, setGmailLoading] = useState<string | null>(null);
+ const [gmailError, setGmailError] = useState<string | null>(null);
+
// Rate limit state
const [rateLimitConfig, setRateLimitConfig] = useState<RateLimitConfig | null>(null);
const [rateLimitStats, setRateLimitStats] = useState<RateLimitStats | null>(null);
@@ -483,6 +502,21 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [visible, hasStoredKey, getStoredApiKey]);
+ // Load Gmail credentials on mount
+ useEffect(() => {
+ if (visible) {
+ hasStoredKey('gmail_client_id').then(async (has) => {
+ setGmailCredentialsStored(has);
+ if (has) {
+ const clientId = await getStoredApiKey('gmail_client_id');
+ const clientSecret = await getStoredApiKey('gmail_client_secret');
+ if (clientId) setGmailClientId(clientId);
+ if (clientSecret) setGmailClientSecret(clientSecret);
+ }
+ });
+ }
+ }, [visible, hasStoredKey, getStoredApiKey]);
+
// Twitter handlers
const handleTwitterSaveCredentials = async () => {
if (!twitterClientId.trim()) {
@@ -546,6 +580,71 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
};
+ // Gmail handlers
+ const handleGmailSaveCredentials = async () => {
+ if (!gmailClientId.trim()) {
+ setGmailError('Client ID is required');
+ return;
+ }
+ if (!gmailClientSecret.trim()) {
+ setGmailError('Client Secret is required');
+ return;
+ }
+ setGmailLoading('save');
+ setGmailError(null);
+ try {
+ await saveApiKey('gmail_client_id', gmailClientId.trim());
+ await saveApiKey('gmail_client_secret', gmailClientSecret.trim());
+ setGmailCredentialsStored(true);
+ } catch (err: any) {
+ setGmailError(err.message || 'Failed to save credentials');
+ } finally {
+ setGmailLoading(null);
+ }
+ };
+
+ const handleGmailLogin = async () => {
+ setGmailLoading('login');
+ setGmailError(null);
+ try {
+ const response = await sendRequest('gmail_oauth_login', {});
+ if (!response.success) {
+ setGmailError(response.error || 'Failed to start OAuth');
+ }
+ } catch (err: any) {
+ setGmailError(err.message || 'Failed to start OAuth');
+ } finally {
+ setGmailLoading(null);
+ }
+ };
+
+ const handleGmailLogout = async () => {
+ setGmailLoading('logout');
+ setGmailError(null);
+ try {
+ const response = await sendRequest('gmail_logout', {});
+ if (!response.success) {
+ setGmailError(response.error || 'Failed to disconnect');
+ }
+ } catch (err: any) {
+ setGmailError(err.message || 'Failed to disconnect');
+ } finally {
+ setGmailLoading(null);
+ }
+ };
+
+ const handleGmailRefreshStatus = async () => {
+ setGmailLoading('refresh');
+ setGmailError(null);
+ try {
+ await sendRequest('gmail_oauth_status', {});
+ } catch (err: any) {
+ setGmailError(err.message || 'Failed to refresh status');
+ } finally {
+ setGmailLoading(null);
+ }
+ };
+
// Android handlers
const handleAndroidSaveKey = async () => {
if (!androidApiKey.trim()) return;
@@ -1534,6 +1633,204 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
);
}
+ // Gmail panel
+ 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>}
+ bordered
+ column={1}
+ size="small"
+ style={{
+ marginBottom: theme.spacing.lg,
+ borderRadius: theme.borderRadius.md,
+ }}
+ styles={{
+ label: {
+ backgroundColor: theme.colors.backgroundPanel,
+ color: theme.colors.textSecondary,
+ fontWeight: theme.fontWeight.medium,
+ },
+ content: {
+ backgroundColor: theme.colors.background,
+ color: theme.colors.text,
+ },
+ }}
+ >
+ <Descriptions.Item label="Status">
+ <Tag style={getTagStyle(gmailStatus.connected ? 'success' : 'error')}>
+ {gmailStatus.connected ? 'Connected' : 'Not Connected'}
+ </Tag>
+ </Descriptions.Item>
+ <Descriptions.Item label="API Credentials">
+ <Tag style={getTagStyle(gmailCredentialsStored ? 'success' : 'error')}>
+ {gmailCredentialsStored === null ? 'Checking...' : gmailCredentialsStored ? 'Configured' : 'Not configured'}
+ </Tag>
+ </Descriptions.Item>
+ {gmailStatus.connected && gmailStatus.email && (
+ <Descriptions.Item label="Account">
+ <Space>
+ {gmailStatus.profile_image_url && (
+ <img
+ src={gmailStatus.profile_image_url}
+ alt={gmailStatus.email}
+ style={{ width: 24, height: 24, borderRadius: '50%' }}
+ />
+ )}
+ <span style={{ fontFamily: theme.fontFamily.mono, fontSize: theme.fontSize.sm }}>{gmailStatus.email}</span>
+ {gmailStatus.name && <span style={{ color: theme.colors.textSecondary }}>({gmailStatus.name})</span>}
+ </Space>
+ </Descriptions.Item>
+ )}
+ </Descriptions>
+
+ {/* API Credentials Input - Only show if not connected */}
+ {!gmailStatus.connected && (
+ <div style={{ marginBottom: theme.spacing.xl }}>
+ <label style={{
+ display: 'block',
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.medium,
+ color: theme.colors.text,
+ marginBottom: theme.spacing.sm,
+ }}>
+ Gmail API Credentials
+ </label>
+ <div style={{ marginBottom: theme.spacing.md }}>
+ <Input
+ value={gmailClientId}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setGmailClientId(e.target.value)}
+ placeholder="Client ID (from Google Cloud Console)"
+ style={{
+ marginBottom: theme.spacing.sm,
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ color: theme.colors.text,
+ fontFamily: theme.fontFamily.mono,
+ fontSize: theme.fontSize.sm,
+ }}
+ />
+ <Input.Password
+ value={gmailClientSecret}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setGmailClientSecret(e.target.value)}
+ placeholder="Client Secret (required)"
+ style={{
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ color: theme.colors.text,
+ fontFamily: theme.fontFamily.mono,
+ fontSize: theme.fontSize.sm,
+ }}
+ />
+ </div>
+ <Button
+ onClick={handleGmailSaveCredentials}
+ loading={gmailLoading === 'save'}
+ disabled={!gmailClientId.trim() || !gmailClientSecret.trim()}
+ style={{
+ backgroundColor: `${theme.dracula.purple}25`,
+ borderColor: `${theme.dracula.purple}60`,
+ color: theme.dracula.purple,
+ }}
+ >
+ Save Credentials
+ </Button>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textMuted,
+ marginTop: theme.spacing.sm,
+ lineHeight: 1.5,
+ }}>
+ Get credentials from Google Cloud Console. Enable the Gmail API and create OAuth 2.0 credentials.
+ <br />
+ Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/gmail/callback</code>
+ </div>
+ </div>
+ )}
+
+ {gmailError && (
+ <Alert type="error" message={gmailError} showIcon style={{ marginBottom: theme.spacing.lg }} />
+ )}
+
+ {/* API Usage Stats */}
+ {renderApiUsagePanel('gmail', 'Gmail')}
+
+ {/* Info box */}
+ <div style={{
+ padding: theme.spacing.md,
+ borderRadius: theme.borderRadius.md,
+ backgroundColor: `${theme.dracula.cyan}10`,
+ border: `1px solid ${theme.dracula.cyan}30`,
+ marginBottom: theme.spacing.xl,
+ flex: 1,
+ }}>
+ <div style={{
+ fontSize: theme.fontSize.sm,
+ color: theme.colors.textSecondary,
+ lineHeight: 1.5,
+ }}>
+ {gmailStatus.connected ? (
+ <>Your Gmail account is connected. You can now use Gmail 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.</>
+ )}
+ </div>
+ </div>
+
+ {/* Actions */}
+ <div style={{
+ display: 'flex',
+ gap: theme.spacing.sm,
+ justifyContent: 'center',
+ paddingTop: theme.spacing.md,
+ borderTop: `1px solid ${theme.colors.border}`,
+ }}>
+ {!gmailStatus.connected ? (
+ <Button
+ onClick={handleGmailLogin}
+ loading={gmailLoading === 'login'}
+ disabled={!gmailCredentialsStored}
+ style={{
+ backgroundColor: `${theme.dracula.green}25`,
+ borderColor: `${theme.dracula.green}60`,
+ color: theme.dracula.green,
+ }}
+ >
+ Login with Google
+ </Button>
+ ) : (
+ <Button
+ onClick={handleGmailLogout}
+ loading={gmailLoading === 'logout'}
+ style={{
+ backgroundColor: `${theme.dracula.pink}25`,
+ borderColor: `${theme.dracula.pink}60`,
+ color: theme.dracula.pink,
+ }}
+ >
+ Disconnect
+ </Button>
+ )}
+ <Button
+ onClick={handleGmailRefreshStatus}
+ loading={gmailLoading === 'refresh'}
+ icon={<ReloadOutlined />}
+ style={{
+ backgroundColor: `${theme.dracula.cyan}25`,
+ borderColor: `${theme.dracula.cyan}60`,
+ color: theme.dracula.cyan,
+ }}
+ >
+ Refresh
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
const item = selectedItem;
const isValid = validKeys[item.id];
const Icon = item.Icon;
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsx
index a524a4fa..1e2d6ede 100644
--- a/client/src/components/SquareNode.tsx
+++ b/client/src/components/SquareNode.tsx
@@ -9,6 +9,7 @@ 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;
@@ -457,8 +458,18 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
return emojiRegex.test(str);
};
- // Helper to render icon (handles URLs, emojis, and icon names)
+ // Helper to render icon (handles URLs, emojis, component markers, 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
if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {
return (
diff --git a/client/src/components/TriggerNode.tsx b/client/src/components/TriggerNode.tsx
index 28eb41a8..1df516dd 100644
--- a/client/src/components/TriggerNode.tsx
+++ b/client/src/components/TriggerNode.tsx
@@ -14,6 +14,7 @@ import { nodeDefinitions } from '../nodeDefinitions';
import { useAppTheme } from '../hooks/useAppTheme';
import { useWebSocket, useWhatsAppStatus } from '../contexts/WebSocketContext';
import { PlayCircleFilled, ScheduleOutlined } from '@ant-design/icons';
+import { Google } from '@lobehub/icons';
const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
const theme = useAppTheme();
@@ -150,6 +151,16 @@ const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
// Helper to render icon
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 '⚡';
+ }
+
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 c793c5a0..ab29cd59 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -277,6 +277,42 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
profile_image_url: 'string',
verified: 'boolean'
},
+ // Gmail node output schemas
+ gmail: {
+ message_id: 'string',
+ thread_id: 'string',
+ to: 'string',
+ subject: 'string',
+ label_ids: 'array'
+ },
+ gmailSearch: {
+ messages: [{
+ message_id: 'string',
+ thread_id: 'string',
+ from: 'string',
+ to: 'string',
+ subject: 'string',
+ date: 'string',
+ snippet: 'string',
+ labels: 'array'
+ }],
+ count: 'number',
+ query: 'string',
+ result_size_estimate: 'number'
+ },
+ gmailRead: {
+ message_id: 'string',
+ thread_id: 'string',
+ from: 'string',
+ to: 'string',
+ cc: 'string',
+ subject: 'string',
+ date: 'string',
+ snippet: 'string',
+ body: 'string',
+ labels: 'array',
+ attachments: 'array'
+ },
httpRequest: {
status: 'number',
data: 'any',
@@ -527,6 +563,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const isTaskTrigger = nodeType === 'taskTrigger';
const isSocialReceive = nodeType === 'socialReceive';
const isSocialSend = nodeType === 'socialSend';
+ const isGmailSend = nodeType === 'gmailSend';
+ const isGmailSearch = nodeType === 'gmailSearch';
+ const isGmailRead = nodeType === 'gmailRead';
// Document processing node detection
const documentNodeTypes = ['httpScraper', 'fileDownloader', 'documentParser', 'textChunker', 'embeddingGenerator', 'vectorStore'];
@@ -561,6 +600,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
isFile ? sampleSchemas.file :
isWhatsAppDb ? sampleSchemas.whatsappDb :
isWhatsApp ? sampleSchemas.whatsapp :
+ isGmailSend ? sampleSchemas.gmail :
+ isGmailSearch ? sampleSchemas.gmailSearch :
+ isGmailRead ? sampleSchemas.gmailRead :
isWebhook ? sampleSchemas.webhook :
isHttpRequest ? sampleSchemas.httpRequest :
isCodeExecutor ? sampleSchemas.python :
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 33a61273..9b0c6230 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -99,6 +99,13 @@ export interface TwitterStatus {
verified?: boolean;
}
+export interface GmailStatus {
+ connected: boolean;
+ email: string | null;
+ name?: string;
+ profile_image_url?: string;
+}
+
// WhatsApp Rate Limit types (from Go RPC schema)
export interface RateLimitConfig {
enabled: boolean;
@@ -213,6 +220,7 @@ interface WebSocketContextValue {
setAndroidStatus: React.Dispatch<React.SetStateAction<AndroidStatus>>;
whatsappStatus: WhatsAppStatus;
twitterStatus: TwitterStatus;
+ gmailStatus: GmailStatus;
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
@@ -338,6 +346,11 @@ const defaultTwitterStatus: TwitterStatus = {
user_id: null,
};
+const defaultGmailStatus: GmailStatus = {
+ connected: false,
+ email: null,
+};
+
const WebSocketContext = createContext<WebSocketContextValue | null>(null);
// WebSocket URL (convert http to ws)
@@ -372,6 +385,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);
const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);
const [twitterStatus, setTwitterStatus] = useState<TwitterStatus>(defaultTwitterStatus);
+ const [gmailStatus, setGmailStatus] = useState<GmailStatus>(defaultGmailStatus);
const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
@@ -487,6 +501,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
if (data.android) setAndroidStatus(data.android);
if (data.whatsapp) setWhatsappStatus(data.whatsapp);
if (data.twitter) setTwitterStatus(data.twitter);
+ if (data.gmail) setGmailStatus(data.gmail);
if (data.api_keys) setApiKeyStatuses(data.api_keys);
// Node statuses from initial_status - group by workflow_id (n8n pattern)
if (data.nodes) {
@@ -554,6 +569,18 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
+ case 'gmail_oauth_complete':
+ // Handle Gmail OAuth completion broadcast from backend
+ if (data?.success) {
+ setGmailStatus({
+ connected: true,
+ email: data.email || null,
+ name: data.name,
+ profile_image_url: data.profile_image_url,
+ });
+ }
+ break;
+
case 'whatsapp_message_received':
// Handle incoming WhatsApp message from Go service
if (data) {
@@ -1991,6 +2018,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
setAndroidStatus,
whatsappStatus,
twitterStatus,
+ gmailStatus,
whatsappMessages,
lastWhatsAppMessage,
apiKeyStatuses,
@@ -2127,6 +2155,12 @@ export const useTwitterStatus = (): TwitterStatus => {
return twitterStatus;
};
+// Hook specifically for Gmail status
+export const useGmailStatus = (): GmailStatus => {
+ const { gmailStatus } = useWebSocket();
+ return gmailStatus;
+};
+
// Hook specifically for deployment status
export const useDeploymentStatus = (): DeploymentStatus => {
const { deploymentStatus } = useWebSocket();
diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.ts
index 84bc42ae..c73843e9 100644
--- a/client/src/nodeDefinitions.ts
+++ b/client/src/nodeDefinitions.ts
@@ -18,6 +18,7 @@ import { skillNodes, SKILL_NODE_TYPES } from './nodeDefinitions/skillNodes';
import { documentNodes, DOCUMENT_NODE_TYPES } from './nodeDefinitions/documentNodes';
import { socialNodes, SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';
import { twitterNodes, TWITTER_NODE_TYPES } from './nodeDefinitions/twitterNodes';
+import { gmailNodes, GMAIL_NODE_TYPES } from './nodeDefinitions/gmailNodes';
// ============================================================================
// MAIN NODE REGISTRY - Combining all modular definitions
@@ -40,7 +41,8 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {
...skillNodes,
...documentNodes,
...socialNodes,
- ...twitterNodes
+ ...twitterNodes,
+ ...gmailNodes
};
// ============================================================================
@@ -116,5 +118,9 @@ export const TWITTER_NODES = [
...TWITTER_NODE_TYPES
];
+export const GMAIL_NODES = [
+ ...GMAIL_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/codeNodes.ts b/client/src/nodeDefinitions/codeNodes.ts
index e6dc7577..ceb73e32 100644
--- a/client/src/nodeDefinitions/codeNodes.ts
+++ b/client/src/nodeDefinitions/codeNodes.ts
@@ -48,7 +48,31 @@ export const codeNodes: Record<string, INodeTypeDescription> = {
placeholder: '// Write your JavaScript code here...'
}
]
+ },
+
+ typescriptExecutor: {
+ displayName: 'TypeScript Executor',
+ name: 'typescriptExecutor',
+ icon: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/typescript/typescript-original.svg',
+ group: ['code', 'tool'],
+ version: 1,
+ subtitle: 'Run TypeScript Code',
+ description: 'Execute TypeScript code with input data access and type safety',
+ defaults: { name: 'TypeScript Executor', color: '#3178C6' },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Input data as input_data variable' }],
+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'TypeScript execution result' }],
+ properties: [
+ {
+ displayName: 'Code',
+ name: 'code',
+ type: 'string',
+ default: '// TypeScript Executor - Transform and process data with type safety\n//\n// Available:\n// input_data - object with connected node outputs\n// console.log() - for debugging\n//\n// Set the "output" variable with your result\n\ninterface Result {\n message: string;\n input_received: unknown;\n processed: boolean;\n}\n\n// Example: Get data from connected node\nconst data = input_data?.start || input_data || {};\n\n// Process data with type safety\nconst result: Result = {\n message: "Hello from TypeScript!",\n input_received: data,\n processed: true\n};\n\n// Set output (required)\noutput = result;',
+ required: true,
+ typeOptions: { rows: 5, editor: 'code', editorLanguage: 'typescript' },
+ placeholder: '// Write your TypeScript code here...'
+ }
+ ]
}
};
-export const CODE_NODE_TYPES = ['pythonExecutor', 'javascriptExecutor'];
+export const CODE_NODE_TYPES = ['pythonExecutor', 'javascriptExecutor', 'typescriptExecutor'];
diff --git a/client/src/nodeDefinitions/gmailNodes.ts b/client/src/nodeDefinitions/gmailNodes.ts
new file mode 100644
index 00000000..53e275d8
--- /dev/null
+++ b/client/src/nodeDefinitions/gmailNodes.ts
@@ -0,0 +1,397 @@
+// Gmail Node Definitions - Google Gmail API integration via OAuth 2.0
+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';
+
+// ============================================================================
+// GMAIL NODES
+// ============================================================================
+
+export const gmailNodes: Record<string, INodeTypeDescription> = {
+ // Gmail Send - Send emails
+ gmailSend: {
+ displayName: 'Gmail Send',
+ name: 'gmailSend',
+ icon: GMAIL_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Send Email',
+ description: 'Send emails via Gmail API',
+ defaults: { name: 'Gmail Send', color: '#EA4335' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Email input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Send result (message_id, thread_id)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== ACCOUNT MODE =====
+ {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options',
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Gmail account to use'
+ },
+ {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string',
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Gmail connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+ },
+
+ // ===== RECIPIENTS =====
+ {
+ displayName: 'To',
+ name: 'to',
+ type: 'string',
+ default: '',
+ required: true,
+ description: 'Recipient email addresses (comma-separated)'
+ },
+ {
+ displayName: 'CC',
+ name: 'cc',
+ type: 'string',
+ default: '',
+ placeholder: '[email protected]',
+ description: 'CC recipients (optional)'
+ },
+ {
+ displayName: 'BCC',
+ name: 'bcc',
+ type: 'string',
+ default: '',
+ placeholder: '[email protected]',
+ description: 'BCC recipients (optional)'
+ },
+
+ // ===== CONTENT =====
+ {
+ displayName: 'Subject',
+ name: 'subject',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'Email subject line',
+ description: 'Email subject'
+ },
+ {
+ displayName: 'Body Type',
+ name: 'body_type',
+ type: 'options',
+ options: [
+ { name: 'Plain Text', value: 'text' },
+ { name: 'HTML', value: 'html' }
+ ],
+ default: 'text',
+ description: 'Email body format'
+ },
+ {
+ displayName: 'Body',
+ name: 'body',
+ type: 'string',
+ default: '',
+ required: true,
+ typeOptions: { rows: 6 },
+ placeholder: 'Email content...',
+ description: 'Email body content'
+ }
+ ]
+ },
+
+ // Gmail Search - Search emails
+ gmailSearch: {
+ displayName: 'Gmail Search',
+ name: 'gmailSearch',
+ icon: GMAIL_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Search Emails',
+ description: 'Search emails using Gmail query syntax',
+ defaults: { name: 'Gmail Search', color: '#EA4335' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Search input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Search results (messages array)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== ACCOUNT MODE =====
+ {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options',
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Gmail account to use'
+ },
+ {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string',
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Gmail connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+ },
+
+ // ===== SEARCH =====
+ {
+ displayName: 'Search Query',
+ name: 'query',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'from:[email protected] subject:meeting',
+ description: 'Gmail search query (same syntax as Gmail web)'
+ },
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 10,
+ typeOptions: { minValue: 1, maxValue: 100 },
+ description: 'Maximum number of messages to return'
+ },
+ {
+ displayName: 'Include Body',
+ name: 'include_body',
+ type: 'boolean',
+ default: false,
+ description: 'Fetch full message body (slower but includes content)'
+ }
+ ]
+ },
+
+ // Gmail Read - Read a specific email
+ gmailRead: {
+ displayName: 'Gmail Read',
+ name: 'gmailRead',
+ icon: GMAIL_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Read Email',
+ description: 'Read a specific email by message ID',
+ defaults: { name: 'Gmail Read', color: '#EA4335' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Message ID input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Email content (from, to, subject, body, attachments)'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== ACCOUNT MODE =====
+ {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options',
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Gmail account to use'
+ },
+ {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string',
+ default: '',
+ placeholder: 'customer_123 or {{input.customer_id}}',
+ description: 'Customer identifier to look up their Gmail connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+ },
+
+ // ===== MESSAGE =====
+ {
+ displayName: 'Message ID',
+ name: 'message_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '18d5a7e2c3b4f5a6',
+ description: 'Gmail message ID to read'
+ },
+ {
+ displayName: 'Format',
+ name: 'format',
+ type: 'options',
+ options: [
+ { name: 'Full (with body)', value: 'full' },
+ { name: 'Metadata (headers only)', value: 'metadata' },
+ { name: 'Minimal', value: 'minimal' },
+ { name: 'Raw', value: 'raw' }
+ ],
+ default: 'full',
+ description: 'Message format to retrieve'
+ }
+ ]
+ },
+
+ // Gmail Receive - Trigger on incoming emails (polling-based)
+ gmailReceive: {
+ displayName: 'Gmail Receive',
+ name: 'gmailReceive',
+ icon: GMAIL_ICON,
+ group: ['social', 'trigger'],
+ version: 1,
+ subtitle: 'On New Email',
+ description: 'Trigger workflow on new emails (polling-based)',
+ defaults: { name: 'Gmail Receive', color: '#EA4335' },
+ inputs: [],
+ outputs: [{
+ name: 'main',
+ displayName: 'Email',
+ type: 'main' as NodeConnectionType,
+ description: 'Received email (message_id, from, to, subject, body, date, labels, attachments)'
+ }],
+ properties: [
+ // ===== ACCOUNT MODE =====
+ {
+ displayName: 'Account',
+ name: 'account_mode',
+ type: 'options',
+ options: [
+ { name: 'Owner Account', value: 'owner' },
+ { name: 'Customer Account', value: 'customer' }
+ ],
+ default: 'owner',
+ description: 'Which Gmail account to monitor'
+ },
+ {
+ displayName: 'Customer ID',
+ name: 'customer_id',
+ type: 'string',
+ default: '',
+ placeholder: 'customer_123',
+ description: 'Customer identifier for their Gmail connection',
+ displayOptions: {
+ show: { account_mode: ['customer'] }
+ }
+ },
+
+ // ===== FILTER =====
+ {
+ displayName: 'Filter Query',
+ name: 'filter_query',
+ type: 'string',
+ default: 'is:unread',
+ placeholder: 'from:[email protected] OR label:work',
+ description: 'Gmail filter query (same as Gmail search)'
+ },
+ {
+ displayName: 'Label Filter',
+ name: 'label_filter',
+ type: 'options',
+ options: [
+ { name: 'All Labels', value: 'all' },
+ { name: 'Inbox Only', value: 'INBOX' },
+ { name: 'Important', value: 'IMPORTANT' },
+ { name: 'Starred', value: 'STARRED' },
+ { name: 'Sent', value: 'SENT' },
+ { name: 'Drafts', value: 'DRAFT' }
+ ],
+ default: 'INBOX',
+ description: 'Filter by Gmail label'
+ },
+ {
+ displayName: 'Mark as Read',
+ name: 'mark_as_read',
+ type: 'boolean',
+ default: false,
+ description: 'Automatically mark emails as read after processing'
+ },
+
+ // ===== POLLING =====
+ {
+ displayName: 'Poll Interval (seconds)',
+ name: 'poll_interval',
+ type: 'number',
+ default: 60,
+ typeOptions: { minValue: 30, maxValue: 3600 },
+ description: 'How often to check for new emails (30s - 1 hour)'
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const GMAIL_NODE_TYPES = ['gmailSend', 'gmailSearch', 'gmailRead', 'gmailReceive'];
diff --git a/docs-internal/pricing_service.md b/docs-internal/pricing_service.md
new file mode 100644
index 00000000..5a96cf8a
--- /dev/null
+++ b/docs-internal/pricing_service.md
@@ -0,0 +1,463 @@
+# API Cost Tracking and Pricing Service
+
+## Overview
+
+The pricing service provides centralized cost tracking for both LLM tokens and external API services (Twitter/X, Google Maps). It supports:
+
+- **LLM Token Costs**: Per-model pricing with input/output/cache/reasoning token breakdown
+- **API Service Costs**: Per-request/resource pricing for third-party APIs
+- **Automatic Tracking**: HTTPX event hooks for transparent API call tracking
+- **Manual Tracking**: Helper functions for services that don't use HTTPX
+
+## Architecture
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ Pricing Configuration │
+│ server/config/pricing.json │
+│ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────────┐ │
+│ │ llm │ │ api │ │ operation │ │ url_patterns │ │
+│ │ pricing │ │ pricing │ │ _map │ │ │ │
+│ └───────────┘ └───────────┘ └───────────┘ └───────────────┘ │
+└─────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ PricingService │
+│ server/services/pricing.py │
+│ ┌────────────────────────────────────────────────────────────┐ │
+│ │ LLM Methods: │ │
+│ │ - get_pricing(provider, model) → ModelPricing │ │
+│ │ - calculate_cost(provider, model, tokens...) → cost dict │ │
+│ │ │ │
+│ │ API Methods: │ │
+│ │ - get_api_price(service, operation) → USD │ │
+│ │ - map_action_to_operation(service, action) → operation │ │
+│ │ - calculate_api_cost(service, action, count) → cost dict │ │
+│ └────────────────────────────────────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────┘
+ │
+ ┌─────────────────┼─────────────────┐
+ ▼ ▼ ▼
+┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
+│ Manual Tracking │ │ HTTPX Event Hooks │ │ AI Service │
+│ _track_*_usage() │ │ tracked_http.py │ │ _track_token_ │
+│ maps.py │ │ │ │ usage() ai.py │
+│ twitter.py │ │ │ │ │
+└───────────────────┘ └───────────────────┘ └───────────────────┘
+ │ │ │
+ └─────────────────┼─────────────────┘
+ ▼
+┌─────────────────────────────────────────────────────────────────┐
+│ Database Storage │
+│ ┌────────────────────────┐ ┌────────────────────────────────┐ │
+│ │ APIUsageMetric │ │ TokenUsageMetric │ │
+│ │ (twitter, maps) │ │ (LLM token usage) │ │
+│ └────────────────────────┘ └────────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Configuration: pricing.json
+
+Located at `server/config/pricing.json`. User-editable with hot-reload support.
+
+### Structure
+
+```json
+{
+ "version": "2026.02",
+ "last_updated": "2026-02-20",
+
+ "llm": {
+ "openai": {
+ "gpt-5": {"input": 1.25, "output": 10.00},
+ "o3": {"input": 2.00, "output": 8.00, "reasoning": 8.00},
+ "_default": {"input": 2.50, "output": 10.00}
+ },
+ "anthropic": {
+ "claude-opus-4.6": {"input": 5.00, "output": 25.00, "cache_read": 0.50},
+ "_default": {"input": 3.00, "output": 15.00, "cache_read": 0.30}
+ }
+ },
+
+ "api": {
+ "google_maps": {
+ "_description": "Google Maps pricing per request (USD)",
+ "geocode": 0.005,
+ "nearby_search": 0.032,
+ "_default": 0.005
+ },
+ "twitter": {
+ "_description": "X/Twitter Pay-Per-Use API pricing",
+ "posts_read": 0.005,
+ "content_create": 0.010,
+ "user_read": 0.010
+ }
+ },
+
+ "operation_map": {
+ "google_maps": {
+ "geocode": "geocode",
+ "nearby_places": "nearby_search"
+ },
+ "twitter": {
+ "tweet": "content_create",
+ "search": "posts_read"
+ }
+ },
+
+ "url_patterns": {
+ "twitter": {
+ "base": "https?://api\\.(twitter|x)\\.com",
+ "actions": {
+ "/2/tweets$": {"action": "content_create", "method": "POST"},
+ "/2/tweets/search": {"action": "posts_read", "method": "GET", "count_path": "data.length"}
+ }
+ }
+ }
+}
+```
+
+### Sections
+
+| Section | Purpose |
+|---------|---------|
+| `llm` | Per-model pricing in USD per million tokens (MTok). Supports `input`, `output`, `cache_read`, `reasoning` |
+| `api` | Per-service pricing in USD per request/resource. Keys starting with `_` are metadata |
+| `operation_map` | Maps handler action names to pricing operation keys |
+| `url_patterns` | Regex patterns for automatic HTTPX tracking. `count_path` extracts resource count from response JSON |
+
+## PricingService API
+
+Singleton accessed via `get_pricing_service()`.
+
+### LLM Methods
+
+```python
+from services.pricing import get_pricing_service
+
+pricing = get_pricing_service()
+
+# Get pricing for a model (partial matching supported)
+model_pricing = pricing.get_pricing('anthropic', 'claude-3-5-sonnet-20241022')
+# Returns ModelPricing(input_per_mtok=3.00, output_per_mtok=15.00, ...)
+
+# Calculate cost for token usage
+cost = pricing.calculate_cost(
+ provider='anthropic',
+ model='claude-3-5-sonnet',
+ input_tokens=5000,
+ output_tokens=1500,
+ cache_read_tokens=200
+)
+# Returns: {
+# 'input_cost': 0.015,
+# 'output_cost': 0.0225,
+# 'cache_cost': 0.00006,
+# 'reasoning_cost': 0.0,
+# 'total_cost': 0.03756
+# }
+```
+
+### API Methods
+
+```python
+# Get price for a specific operation
+price = pricing.get_api_price('twitter', 'content_create') # 0.010
+
+# Map handler action to pricing operation
+op = pricing.map_action_to_operation('twitter', 'tweet') # 'content_create'
+
+# Calculate API cost
+cost = pricing.calculate_api_cost('twitter', 'tweet', resource_count=1)
+# Returns: {'operation': 'content_create', 'unit_cost': 0.010, 'resource_count': 1, 'total_cost': 0.01}
+```
+
+### Config Management
+
+```python
+# Get full config for frontend editing
+config = pricing.get_config()
+
+# Save updated config (updates last_updated, reloads registry)
+pricing.save_config(updated_config)
+
+# Force reload from disk
+pricing.reload()
+```
+
+## Manual Tracking Pattern
+
+For services that make API calls directly (not through HTTPX), use manual tracking functions.
+
+### Example: Maps Service
+
+```python
+# server/services/maps.py
+
+async def _track_maps_usage(
+ node_id: str,
+ action: str,
+ resource_count: int = 1,
+ workflow_id: str = None,
+ session_id: str = "default"
+) -> Dict[str, float]:
+ """Track Google Maps API usage."""
+ from core.container import container
+
+ pricing = get_pricing_service()
+ cost_data = pricing.calculate_api_cost('google_maps', 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_maps',
+ 'operation': cost_data.get('operation', action),
+ 'endpoint': action,
+ 'resource_count': resource_count,
+ 'cost': cost_data.get('total_cost', 0.0)
+ })
+
+ return cost_data
+
+# Usage in handler:
+async def geocode_location(self, node_id: str, parameters: Dict, context: Dict):
+ # ... API call ...
+ await _track_maps_usage(node_id, 'geocode', 1, context.get('workflow_id'))
+```
+
+### Example: Twitter Handler
+
+```python
+# server/services/handlers/twitter.py
+
+async def _track_twitter_usage(node_id, action, resource_count=1, workflow_id=None, session_id="default"):
+ # Same pattern as maps
+ pricing = get_pricing_service()
+ cost_data = pricing.calculate_api_cost('twitter', action, resource_count)
+ # ... save to database ...
+
+# Usage:
+await _track_twitter_usage(node_id, 'tweet', 1, workflow_id, session_id)
+```
+
+## Automatic HTTPX Tracking
+
+For services using `httpx.AsyncClient`, use the tracked client for transparent tracking.
+
+### Usage
+
+```python
+from services.tracked_http import get_tracked_client, set_tracking_context
+
+# Set context before making requests
+set_tracking_context(node_id="twitter-1", session_id="user-123")
+
+# Use tracked client - tracking happens automatically
+client = get_tracked_client()
+response = await client.post("https://api.twitter.com/2/tweets", json={...})
+# Automatically tracked via response hook!
+```
+
+### How It Works
+
+1. **Context Variables**: `set_tracking_context()` sets node_id, session_id, workflow_id in `contextvars`
+2. **URL Matching**: Response hook matches URL against `url_patterns` in pricing.json
+3. **Resource Counting**: `count_path` extracts resource count from response JSON (e.g., `data.length`)
+4. **Fire-and-Forget**: `_save_metric()` runs as `asyncio.create_task()` to avoid blocking
+
+### URL Pattern Format
+
+```json
+{
+ "twitter": {
+ "base": "https?://api\\.(twitter|x)\\.com",
+ "actions": {
+ "/2/tweets$": {"action": "content_create", "method": "POST"},
+ "/2/tweets/search": {
+ "action": "posts_read",
+ "method": "GET",
+ "count_path": "data.length"
+ }
+ }
+ }
+}
+```
+
+- `base`: Regex to match domain
+- `actions`: Dict of endpoint patterns to action config
+- `method`: HTTP method filter (`*` for any)
+- `count_path`: Dot-notation path to extract count from response (e.g., `data.length`, `results.count`)
+
+## Database Storage
+
+### APIUsageMetric
+
+For third-party API services (Twitter, Google Maps).
+
+```python
+class APIUsageMetric(SQLModel, table=True):
+ __tablename__ = "api_usage_metrics"
+
+ id: int
+ timestamp: datetime
+ session_id: str # Index for aggregation
+ node_id: str
+ workflow_id: Optional[str]
+ service: str # 'twitter', 'google_maps'
+ operation: str # 'content_create', 'geocode'
+ endpoint: str # Handler action name
+ resource_count: int # Number of resources
+ cost: float # USD cost
+```
+
+### TokenUsageMetric
+
+For LLM token usage (see memory_compaction.md for details).
+
+```python
+class TokenUsageMetric(SQLModel, table=True):
+ __tablename__ = "token_usage_metrics"
+
+ session_id: str
+ node_id: str
+ provider: str # 'openai', 'anthropic'
+ model: str
+ input_tokens: int
+ output_tokens: int
+ cache_read_tokens: int
+ reasoning_tokens: int
+ input_cost: float # USD
+ output_cost: float
+ total_cost: float
+```
+
+### Database Methods
+
+```python
+# Save API usage
+await db.save_api_usage_metric({
+ 'session_id': 'default',
+ 'node_id': 'twitter-1',
+ 'service': 'twitter',
+ 'operation': 'content_create',
+ 'endpoint': 'tweet',
+ 'resource_count': 1,
+ 'cost': 0.01
+})
+
+# Get usage summary (aggregated by service)
+summary = await db.get_api_usage_summary(service='twitter')
+# Returns: [{'service': 'twitter', 'total_resources': 50, 'total_cost': 0.5, 'execution_count': 45}]
+```
+
+## Frontend Display
+
+The CredentialsModal displays usage statistics via `renderApiUsagePanel()`:
+
+```typescript
+// client/src/components/CredentialsModal.tsx
+
+// Fetch usage data
+const { getApiUsage, apiUsage, apiUsageLoading } = usePricing();
+await getApiUsage('twitter');
+
+// Render panel
+{renderApiUsagePanel('twitter', 'Twitter')}
+{renderApiUsagePanel('google_maps', 'Google Maps')}
+```
+
+### Display Format
+
+- Collapsible panel with service icon and total cost tag
+- Table with operation breakdown (operation name, count, unit cost, total cost)
+- Refresh button to reload data
+- Loading state while fetching
+
+## Adding New Services
+
+### 1. Add Pricing to pricing.json
+
+```json
+{
+ "api": {
+ "new_service": {
+ "_description": "New Service API pricing",
+ "read_operation": 0.001,
+ "write_operation": 0.005
+ }
+ },
+ "operation_map": {
+ "new_service": {
+ "get_data": "read_operation",
+ "create_item": "write_operation"
+ }
+ }
+}
+```
+
+### 2. Add Manual Tracking (if not using HTTPX)
+
+```python
+# server/services/handlers/new_service.py
+
+async def _track_new_service_usage(node_id, action, count=1, workflow_id=None, session_id="default"):
+ from core.container import container
+ pricing = get_pricing_service()
+ cost_data = pricing.calculate_api_cost('new_service', action, count)
+
+ db = container.database()
+ await db.save_api_usage_metric({
+ 'session_id': session_id,
+ 'node_id': node_id,
+ 'workflow_id': workflow_id,
+ 'service': 'new_service',
+ 'operation': cost_data.get('operation', action),
+ 'endpoint': action,
+ 'resource_count': count,
+ 'cost': cost_data.get('total_cost', 0.0)
+ })
+ return cost_data
+
+# Call in handler:
+await _track_new_service_usage(node_id, 'get_data', len(results), workflow_id)
+```
+
+### 3. Add URL Patterns (if using HTTPX)
+
+```json
+{
+ "url_patterns": {
+ "new_service": {
+ "base": "https?://api\\.newservice\\.com",
+ "actions": {
+ "/v1/items$": {"action": "read_operation", "method": "GET", "count_path": "items.length"},
+ "/v1/items$": {"action": "write_operation", "method": "POST"}
+ }
+ }
+ }
+}
+```
+
+### 4. Add Frontend Display
+
+```typescript
+// In CredentialsModal.tsx, in the relevant panel:
+{renderApiUsagePanel('new_service', 'New Service')}
+```
+
+## Key Files
+
+| File | Purpose |
+|------|---------|
+| `server/config/pricing.json` | Pricing configuration (user-editable) |
+| `server/services/pricing.py` | PricingService with LLM and API cost calculation |
+| `server/services/tracked_http.py` | HTTPX event hooks for automatic tracking |
+| `server/services/maps.py` | Manual tracking example (`_track_maps_usage`) |
+| `server/services/handlers/twitter.py` | Manual tracking example (`_track_twitter_usage`) |
+| `server/models/database.py` | `APIUsageMetric`, `TokenUsageMetric` models |
+| `server/core/database.py` | `save_api_usage_metric()`, `get_api_usage_summary()` |
+| `client/src/components/CredentialsModal.tsx` | `renderApiUsagePanel()` UI component |
+| `client/src/hooks/usePricing.ts` | Frontend hook for pricing/usage data |
diff --git a/server/Dockerfile b/server/Dockerfile
index 90cb0523..c9384bc0 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -1,12 +1,14 @@
-# Python FastAPI Backend
+# Python FastAPI Backend with Node.js for JS/TS execution
FROM python:3.12-slim
WORKDIR /app
-# Install system dependencies and uv
+# Install system dependencies, uv, and Node.js
RUN apt-get update && apt-get install -y \
curl \
gcc \
+ && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
+ && apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/* \
&& pip install uv
@@ -22,18 +24,31 @@ COPY . .
# Create data directory for SQLite database
RUN mkdir -p /app/data
+# Install Node.js executor dependencies
+RUN cd /app/nodejs && npm install
+
+# Create user-packages directory for npm packages
+RUN mkdir -p /app/nodejs/user-packages && \
+ cd /app/nodejs/user-packages && \
+ npm init -y
+
# Compile Python files to optimized bytecode for faster imports
RUN python -O -m compileall -q -f .
-# Default port (overridden by environment)
+# Default ports (overridden by environment)
ENV PORT=3010
+ENV NODEJS_EXECUTOR_PORT=3020
+ENV NODEJS_EXECUTOR_HOST=localhost
-# Expose default port
-EXPOSE 3010
+# Expose default ports
+EXPOSE 3010 3020
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
CMD sh -c "curl -f http://localhost:\${PORT}/health || exit 1"
-# Run the application
-CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3010"]
+# Make startup script executable
+RUN chmod +x /app/start.sh
+
+# Run both Python and Node.js servers
+CMD ["/app/start.sh"]
diff --git a/server/config/pricing.json b/server/config/pricing.json
index 9981eb93..65d021c7 100644
--- a/server/config/pricing.json
+++ b/server/config/pricing.json
@@ -103,6 +103,24 @@
"static_map": 0.002,
"_default": 0.005
},
+ "gmail": {
+ "_description": "Gmail API (free tier with generous rate limits)",
+ "_source": "https://developers.google.com/gmail/api/reference/quota",
+ "_note": "Free API - costs are $0. Rate limit: 250 quota units/user/second",
+ "message_send": 0.0,
+ "message_read": 0.0,
+ "message_list": 0.0,
+ "message_search": 0.0,
+ "message_modify": 0.0,
+ "message_delete": 0.0,
+ "label_list": 0.0,
+ "label_manage": 0.0,
+ "thread_read": 0.0,
+ "thread_list": 0.0,
+ "draft_create": 0.0,
+ "attachment_read": 0.0,
+ "_default": 0.0
+ },
"twitter": {
"_description": "X/Twitter Pay-Per-Use API pricing (per resource/request)",
"_source": "https://developer.x.com/#pricing",
@@ -161,6 +179,18 @@
"by_id": "user_read",
"followers": "followers_read",
"following": "following_read"
+ },
+ "gmail": {
+ "send": "message_send",
+ "read": "message_read",
+ "list": "message_list",
+ "search": "message_search",
+ "modify": "message_modify",
+ "delete": "message_delete",
+ "labels": "label_list",
+ "threads": "thread_list",
+ "draft": "draft_create",
+ "attachment": "attachment_read"
}
},
diff --git a/server/core/config.py b/server/core/config.py
index a8501442..c718ee70 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -62,6 +62,10 @@ class Settings(BaseSettings):
# WhatsApp Service URL (Flask service)
whatsapp_service_url: str = Field(default="http://localhost:5000", env="WHATSAPP_SERVICE_URL")
+ # Node.js Executor Configuration
+ nodejs_executor_url: str = Field(default="http://localhost:3020", env="NODEJS_EXECUTOR_URL")
+ nodejs_executor_timeout: int = Field(default=30, env="NODEJS_EXECUTOR_TIMEOUT", ge=5, le=300)
+
# AI Proxy Configuration (Ollama-style proxy)
ai_proxy_default_port: int = Field(default=11434, env="AI_PROXY_DEFAULT_PORT")
@@ -69,6 +73,10 @@ class Settings(BaseSettings):
websocket_url: str = Field(default="", env="WEBSOCKET_URL")
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")
+ twitter_redirect_uri: str = Field(default="http://localhost:3010/api/twitter/callback", env="TWITTER_REDIRECT_URI")
+
# Android Relay Configuration (passed to Vite frontend)
vite_android_relay_url: Optional[str] = Field(default=None, env="VITE_ANDROID_RELAY_URL")
diff --git a/server/core/database.py b/server/core/database.py
index 28a18617..b4c9bcf7 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
+ AgentTeam, TeamMember, TeamTask, AgentMessage, GmailConnection
)
from models.cache import CacheEntry # SQLite-backed cache for Redis alternative
from models.auth import User # Import User model to ensure table creation
@@ -2349,4 +2349,157 @@ class Database:
}
except Exception as e:
logger.error(f"Failed to get team stats: {e}")
- return {"error": str(e)}
\ No newline at end of file
+ return {"error": str(e)}
+
+ # ============================================================================
+ # Gmail Connections - Customer Mode OAuth Storage
+ # ============================================================================
+
+ async def save_gmail_connection(
+ self,
+ customer_id: str,
+ email: str,
+ access_token: str,
+ refresh_token: str,
+ scopes: str,
+ name: Optional[str] = None,
+ ) -> bool:
+ """Save or update a Gmail 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)
+ )
+ existing = result.scalar_one_or_none()
+
+ now = datetime.now(timezone.utc)
+ if existing:
+ # Update existing connection
+ existing.email = email
+ existing.name = name
+ existing.access_token = access_token
+ existing.refresh_token = refresh_token
+ existing.scopes = scopes
+ existing.is_active = True
+ existing.updated_at = now
+ else:
+ # Create new connection
+ connection = GmailConnection(
+ customer_id=customer_id,
+ email=email,
+ name=name,
+ access_token=access_token,
+ refresh_token=refresh_token,
+ scopes=scopes,
+ is_active=True,
+ connected_at=now,
+ updated_at=now,
+ )
+ session.add(connection)
+
+ await session.commit()
+ logger.info(f"Saved Gmail connection for customer {customer_id}")
+ return True
+ except Exception as e:
+ logger.error(f"Failed to save Gmail connection: {e}")
+ return False
+
+ async def get_gmail_connection(self, customer_id: str) -> Optional[GmailConnection]:
+ """Get Gmail 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
+ )
+ )
+ return result.scalar_one_or_none()
+ except Exception as e:
+ logger.error(f"Failed to get Gmail connection: {e}")
+ return None
+
+ async def delete_gmail_connection(self, customer_id: str) -> bool:
+ """Delete Gmail connection for a customer."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(GmailConnection).where(GmailConnection.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}")
+ return True
+ except Exception as e:
+ logger.error(f"Failed to delete Gmail connection: {e}")
+ return False
+
+ async def list_gmail_connections(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """List all Gmail 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())
+ .limit(limit)
+ )
+ connections = result.scalars().all()
+ return [
+ {
+ "customer_id": c.customer_id,
+ "email": c.email,
+ "name": c.name,
+ "connected_at": c.connected_at.isoformat() if c.connected_at else None,
+ "last_used_at": c.last_used_at.isoformat() if c.last_used_at else None,
+ }
+ for c in connections
+ ]
+ except Exception as e:
+ logger.error(f"Failed to list Gmail connections: {e}")
+ return []
+
+ async def update_gmail_connection_tokens(
+ self,
+ customer_id: str,
+ access_token: str,
+ refresh_token: Optional[str] = None,
+ ) -> bool:
+ """Update tokens for a Gmail connection (after refresh)."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ )
+ connection = result.scalar_one_or_none()
+ if connection:
+ connection.access_token = access_token
+ if refresh_token:
+ connection.refresh_token = refresh_token
+ connection.updated_at = datetime.now(timezone.utc)
+ await session.commit()
+ return True
+ return False
+ except Exception as e:
+ logger.error(f"Failed to update Gmail tokens: {e}")
+ return False
+
+ async def update_gmail_last_used(self, customer_id: str) -> bool:
+ """Update last_used_at timestamp for a Gmail connection."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(GmailConnection).where(GmailConnection.customer_id == customer_id)
+ )
+ connection = result.scalar_one_or_none()
+ if connection:
+ connection.last_used_at = datetime.now(timezone.utc)
+ await session.commit()
+ return True
+ return False
+ except Exception as e:
+ logger.error(f"Failed to update Gmail last used: {e}")
+ return False
\ No newline at end of file
diff --git a/server/main.py b/server/main.py
index f930b791..7cd5b564 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
+from routers import workflow, database, maps, nodejs_compat, android, websocket, webhook, auth, twitter, gmail
# Initialize settings and logging
settings = Settings()
@@ -62,6 +62,7 @@ async def lifespan(app: FastAPI):
"routers.webhook",
"routers.auth",
"routers.twitter",
+ "routers.gmail",
"middleware.auth"
])
@@ -276,6 +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.get("/health")
diff --git a/server/models/database.py b/server/models/database.py
index 1b4afc69..2296cef6 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -492,4 +492,36 @@ class AgentMessage(SQLModel, table=True):
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+
+
+class GmailConnection(SQLModel, table=True):
+ """Gmail OAuth connections for customer access mode.
+
+ Stores OAuth tokens for each connected Gmail 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).
+ """
+
+ __tablename__ = "gmail_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
+ 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
+ token_expiry: Optional[datetime] = Field(default=None) # When access token expires
+ scopes: str = Field(max_length=1000) # Comma-separated granted scopes
+ is_active: bool = Field(default=True) # Whether connection is active
+ last_used_at: Optional[datetime] = Field(default=None) # Last API call timestamp
+ 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())
)
\ No newline at end of file
diff --git a/server/nodejs/package-lock.json b/server/nodejs/package-lock.json
new file mode 100644
index 00000000..1d4c4035
--- /dev/null
+++ b/server/nodejs/package-lock.json
@@ -0,0 +1,1496 @@
+{
+ "name": "machinaos-nodejs-executor",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "machinaos-nodejs-executor",
+ "version": "1.0.0",
+ "dependencies": {
+ "express": "^5.0.0"
+ },
+ "devDependencies": {
+ "@types/express": "^5.0.0",
+ "@types/node": "^22.0.0",
+ "tsx": "^4.21.0",
+ "typescript": "^5.7.0"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@types/body-parser": {
+ "version": "1.19.6",
+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/connect": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/connect": {
+ "version": "3.4.38",
+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/express": {
+ "version": "5.0.6",
+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/body-parser": "*",
+ "@types/express-serve-static-core": "^5.0.0",
+ "@types/serve-static": "^2"
+ }
+ },
+ "node_modules/@types/express-serve-static-core": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
+ "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "@types/qs": "*",
+ "@types/range-parser": "*",
+ "@types/send": "*"
+ }
+ },
+ "node_modules/@types/http-errors": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "22.19.11",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz",
+ "integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/range-parser": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/serve-static": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/http-errors": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/body-parser": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^1.0.5",
+ "debug": "^4.4.3",
+ "http-errors": "^2.0.0",
+ "iconv-lite": "^0.7.0",
+ "on-finished": "^2.4.1",
+ "qs": "^6.14.1",
+ "raw-body": "^3.0.1",
+ "type-is": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/content-disposition": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
+ "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "license": "MIT"
+ },
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.3",
+ "@esbuild/android-arm": "0.27.3",
+ "@esbuild/android-arm64": "0.27.3",
+ "@esbuild/android-x64": "0.27.3",
+ "@esbuild/darwin-arm64": "0.27.3",
+ "@esbuild/darwin-x64": "0.27.3",
+ "@esbuild/freebsd-arm64": "0.27.3",
+ "@esbuild/freebsd-x64": "0.27.3",
+ "@esbuild/linux-arm": "0.27.3",
+ "@esbuild/linux-arm64": "0.27.3",
+ "@esbuild/linux-ia32": "0.27.3",
+ "@esbuild/linux-loong64": "0.27.3",
+ "@esbuild/linux-mips64el": "0.27.3",
+ "@esbuild/linux-ppc64": "0.27.3",
+ "@esbuild/linux-riscv64": "0.27.3",
+ "@esbuild/linux-s390x": "0.27.3",
+ "@esbuild/linux-x64": "0.27.3",
+ "@esbuild/netbsd-arm64": "0.27.3",
+ "@esbuild/netbsd-x64": "0.27.3",
+ "@esbuild/openbsd-arm64": "0.27.3",
+ "@esbuild/openbsd-x64": "0.27.3",
+ "@esbuild/openharmony-arm64": "0.27.3",
+ "@esbuild/sunos-x64": "0.27.3",
+ "@esbuild/win32-arm64": "0.27.3",
+ "@esbuild/win32-ia32": "0.27.3",
+ "@esbuild/win32-x64": "0.27.3"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/express": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.2.1",
+ "content-disposition": "^1.0.0",
+ "content-type": "^1.0.5",
+ "cookie": "^0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "finalhandler": "^2.1.0",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "mime-types": "^3.0.0",
+ "on-finished": "^2.4.1",
+ "once": "^1.4.0",
+ "parseurl": "^1.3.3",
+ "proxy-addr": "^2.0.7",
+ "qs": "^6.14.0",
+ "range-parser": "^1.2.1",
+ "router": "^2.2.0",
+ "send": "^1.1.0",
+ "serve-static": "^2.2.0",
+ "statuses": "^2.0.1",
+ "type-is": "^2.0.1",
+ "vary": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/finalhandler": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/get-tsconfig": {
+ "version": "4.13.6",
+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
+ "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "resolve-pkg-maps": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/http-errors": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+ "license": "MIT",
+ "dependencies": {
+ "depd": "~2.0.0",
+ "inherits": "~2.0.4",
+ "setprototypeof": "~1.2.0",
+ "statuses": "~2.0.2",
+ "toidentifier": "~1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/negotiator": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
+ "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.15.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz",
+ "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/raw-body": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "~3.1.2",
+ "http-errors": "~2.0.1",
+ "iconv-lite": "~0.7.0",
+ "unpipe": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/resolve-pkg-maps": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
+ }
+ },
+ "node_modules/router": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.1",
+ "mime-types": "^3.0.2",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/serve-static": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+ "license": "MIT",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "license": "ISC"
+ },
+ "node_modules/side-channel": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/statuses": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/tsx": {
+ "version": "4.21.0",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.27.0",
+ "get-tsconfig": "^4.7.5"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/type-is": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^1.0.5",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ }
+ }
+}
diff --git a/server/nodejs/package.json b/server/nodejs/package.json
new file mode 100644
index 00000000..66caed79
--- /dev/null
+++ b/server/nodejs/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "machinaos-nodejs-executor",
+ "version": "1.0.0",
+ "description": "Persistent Node.js server for JavaScript/TypeScript code execution",
+ "type": "module",
+ "main": "src/index.ts",
+ "scripts": {
+ "start": "tsx src/index.ts",
+ "dev": "tsx watch src/index.ts"
+ },
+ "dependencies": {
+ "express": "^5.0.0"
+ },
+ "devDependencies": {
+ "@types/express": "^5.0.0",
+ "@types/node": "^22.0.0",
+ "tsx": "^4.21.0",
+ "typescript": "^5.7.0"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
+}
diff --git a/server/nodejs/src/index.ts b/server/nodejs/src/index.ts
new file mode 100644
index 00000000..202876ff
--- /dev/null
+++ b/server/nodejs/src/index.ts
@@ -0,0 +1,127 @@
+/**
+ * Node.js Code Execution Server
+ * Thin HTTP layer - all parameters from environment or requests
+ */
+
+import express, { Request, Response, NextFunction } from 'express';
+import vm from 'node:vm';
+import { execSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+// All configuration from environment variables
+const PORT = parseInt(process.env.NODEJS_EXECUTOR_PORT ?? '', 10) || 3020;
+const HOST = process.env.NODEJS_EXECUTOR_HOST ?? 'localhost';
+const BODY_LIMIT = process.env.NODEJS_EXECUTOR_BODY_LIMIT ?? '10mb';
+const USER_PACKAGES_DIR = process.env.NODEJS_USER_PACKAGES_DIR ?? path.join(__dirname, '..', 'user-packages');
+
+const app = express();
+app.use(express.json({ limit: BODY_LIMIT }));
+
+interface ExecuteRequest {
+ code: string;
+ language?: 'javascript' | 'typescript';
+ input_data?: Record<string, unknown>;
+ timeout?: number;
+}
+
+// Health check
+app.get('/health', (_req: Request, res: Response) => {
+ res.json({
+ status: 'healthy',
+ service: 'nodejs-executor',
+ node_version: process.version,
+ });
+});
+
+// Execute code - all parameters from request body
+app.post('/execute', (req: Request, res: Response) => {
+ const { code, input_data = {}, timeout = 30000 } = req.body as ExecuteRequest;
+
+ if (!code || typeof code !== 'string') {
+ res.status(400).json({ success: false, error: 'Missing or invalid "code" field' });
+ return;
+ }
+
+ const startTime = Date.now();
+ const consoleOutput: string[] = [];
+
+ const capturedConsole = {
+ log: (...args: unknown[]) => consoleOutput.push(args.map(String).join(' ')),
+ error: (...args: unknown[]) => consoleOutput.push(`[ERROR] ${args.map(String).join(' ')}`),
+ warn: (...args: unknown[]) => consoleOutput.push(`[WARN] ${args.map(String).join(' ')}`),
+ info: (...args: unknown[]) => consoleOutput.push(args.map(String).join(' ')),
+ };
+
+ const sandbox = {
+ console: capturedConsole,
+ input_data,
+ output: undefined as unknown,
+ JSON, Math, Date, Array, Object, String, Number, Boolean, RegExp, Map, Set, Promise,
+ setTimeout, setInterval, clearTimeout, clearInterval,
+ };
+
+ try {
+ const context = vm.createContext(sandbox);
+ vm.runInContext(code, context, { timeout, filename: 'user-code.js' });
+
+ res.json({
+ success: true,
+ output: sandbox.output,
+ console_output: consoleOutput.join('\n'),
+ execution_time_ms: Date.now() - startTime,
+ });
+ } catch (error) {
+ res.json({
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ console_output: consoleOutput.join('\n'),
+ execution_time_ms: Date.now() - startTime,
+ });
+ }
+});
+
+// Install packages - package list from request
+app.post('/packages/install', (req: Request, res: Response) => {
+ const { packages } = req.body as { packages: string[] };
+
+ if (!packages || !Array.isArray(packages) || packages.length === 0) {
+ res.status(400).json({ success: false, error: 'Missing or invalid "packages" array' });
+ return;
+ }
+
+ const validPattern = /^(@[\w-]+\/)?[\w-]+(@[\w.-]+)?$/;
+ const invalid = packages.filter(p => !validPattern.test(p));
+ if (invalid.length > 0) {
+ res.status(400).json({ success: false, error: `Invalid package names: ${invalid.join(', ')}` });
+ return;
+ }
+
+ try {
+ execSync(`npm install ${packages.join(' ')}`, { cwd: USER_PACKAGES_DIR, timeout: 60000 });
+ res.json({ success: true, message: `Installed: ${packages.join(', ')}` });
+ } catch (error) {
+ res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) });
+ }
+});
+
+// List packages
+app.get('/packages', (_req: Request, res: Response) => {
+ try {
+ const output = execSync('npm list --json --depth=0', { cwd: USER_PACKAGES_DIR, encoding: 'utf-8' });
+ res.json({ success: true, packages: JSON.parse(output).dependencies || {} });
+ } catch {
+ res.json({ success: true, packages: {} });
+ }
+});
+
+app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
+ console.error('Server error:', err);
+ res.status(500).json({ success: false, error: 'Internal server error' });
+});
+
+app.listen(PORT, HOST, () => {
+ console.log(`Node.js Executor running on http://${HOST}:${PORT}`);
+});
diff --git a/server/nodejs/tsconfig.json b/server/nodejs/tsconfig.json
new file mode 100644
index 00000000..82dd1d5b
--- /dev/null
+++ b/server/nodejs/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2024",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "lib": ["ES2024"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "user-packages"]
+}
diff --git a/server/pyproject.toml b/server/pyproject.toml
index 1f580cd1..a4d7070d 100644
--- a/server/pyproject.toml
+++ b/server/pyproject.toml
@@ -57,6 +57,12 @@ dependencies = [
# Twitter/X API
"xdk>=0.1.0",
+
+ # Gmail API
+ "google-api-python-client>=2.100.0",
+ "google-auth>=2.27.0",
+ "google-auth-oauthlib>=1.2.0",
+ "google-auth-httplib2>=0.2.0",
]
[project.optional-dependencies]
diff --git a/server/requirements.txt b/server/requirements.txt
index b116a1cc..ffd084ad 100644
--- a/server/requirements.txt
+++ b/server/requirements.txt
@@ -74,6 +74,12 @@ pytz>=2024.1
# Twitter/X API
xdk>=0.1.0
+# Gmail API
+google-api-python-client>=2.100.0
+google-auth>=2.27.0
+google-auth-oauthlib>=1.2.0
+google-auth-httplib2>=0.2.0
+
# Document Processing Nodes
beautifulsoup4>=4.12.0
langchain-text-splitters>=0.3.0
diff --git a/server/routers/gmail.py b/server/routers/gmail.py
new file mode 100644
index 00000000..e32276ec
--- /dev/null
+++ b/server/routers/gmail.py
@@ -0,0 +1,258 @@
+"""
+Gmail OAuth 2.0 callback and API routes.
+
+OAuth flow:
+1. Frontend calls WebSocket 'gmail_oauth_login' handler
+2. Backend generates authorization URL, opens browser
+3. User authorizes on Google
+4. Google redirects to /api/gmail/callback with code
+5. Backend exchanges code for tokens, stores them via auth_service
+6. Frontend polls WebSocket 'gmail_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)
+"""
+
+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.gmail_oauth import GmailOAuth, get_pending_state
+
+logger = get_logger(__name__)
+router = APIRouter(prefix="/api/gmail", tags=["gmail"])
+
+
+def get_settings():
+ """Get application settings."""
+ return container.settings()
+
+
+def get_auth_service():
+ """Get auth service for API key storage."""
+ return container.auth_service()
+
+
+def get_database():
+ """Get database for customer connections."""
+ return container.database()
+
+
[email protected]("/callback")
+async def gmail_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.
+
+ Google redirects here after user authorizes (or denies) the app.
+ """
+ # Handle authorization denied
+ if error:
+ logger.warning(f"Gmail OAuth denied: {error} - {error_description}")
+ return HTMLResponse(
+ content=_callback_html(success=False, error=error_description or error),
+ status_code=200,
+ )
+
+ # Validate required parameters
+ if not code or not state:
+ logger.error("Gmail OAuth callback missing code or state")
+ return HTMLResponse(
+ content=_callback_html(success=False, error="Missing authorization code or state"),
+ status_code=400,
+ )
+
+ # Verify state exists (CSRF protection)
+ pending_state = get_pending_state(state)
+ if not pending_state:
+ logger.error("Gmail OAuth callback with invalid/expired state")
+ return HTMLResponse(
+ content=_callback_html(success=False, error="Invalid or expired state. Please try again."),
+ status_code=400,
+ )
+
+ # Get state data
+ state_data = pending_state.get("data", {})
+ mode = state_data.get("mode", "owner")
+ customer_id = state_data.get("customer_id")
+ redirect_after = state_data.get("redirect_after")
+
+ # 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 ""
+
+ 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."),
+ status_code=400,
+ )
+
+ oauth = GmailOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri=settings.gmail_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')}")
+ return HTMLResponse(
+ content=_callback_html(success=False, error=result.get("error", "Token exchange failed")),
+ status_code=400,
+ )
+
+ email = result.get("email", "Unknown")
+ name = result.get("name", "")
+ access_token = result.get("access_token")
+ refresh_token = result.get("refresh_token")
+
+ if mode == "customer" and customer_id:
+ # Customer mode: store in gmail_connections table
+ database = get_database()
+ await database.save_gmail_connection(
+ customer_id=customer_id,
+ email=email,
+ name=name,
+ access_token=access_token,
+ refresh_token=refresh_token,
+ scopes=",".join(result.get("scopes", [])),
+ )
+ logger.info(f"Gmail OAuth successful for customer {customer_id}: {email}")
+
+ if redirect_after:
+ return RedirectResponse(url=f"{redirect_after}?gmail_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")
+ 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}")
+
+ # Broadcast completion event
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+ await broadcaster.broadcast({
+ "type": "gmail_oauth_complete",
+ "data": {"success": True, "email": email, "name": name, "mode": mode, "customer_id": customer_id},
+ })
+
+ return HTMLResponse(content=_callback_html(success=True, email=email), status_code=200)
+
+
+async def get_gmail_status():
+ """Get Gmail connection status for owner mode."""
+ auth_service = get_auth_service()
+ access_token = await auth_service.get_api_key("gmail_access_token")
+
+ if not access_token:
+ return {"connected": False, "email": None}
+
+ user_info_str = await auth_service.get_api_key("gmail_user_info")
+ email, name = None, None
+ if user_info_str:
+ parts = user_info_str.split(":", 1)
+ email = parts[0] if parts else None
+ name = parts[1] if len(parts) > 1 else None
+
+ return {"connected": True, "email": email, "name": name}
+
+
+async def gmail_logout():
+ """Disconnect Gmail (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"}
+
+
[email protected]("/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."""
+ 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 ""
+
+ if not client_id or not client_secret:
+ return {"success": False, "error": "Gmail not configured. Add Client ID and Secret."}
+
+ oauth = GmailOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri=settings.gmail_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"]}
+
+
[email protected]("/customer/{customer_id}/status")
+async def get_customer_gmail_status(customer_id: str):
+ """Get Gmail connection status for a customer."""
+ database = get_database()
+ connection = await database.get_gmail_connection(customer_id)
+ if not connection:
+ return {"connected": False, "customer_id": customer_id}
+ return {
+ "connected": connection.is_active,
+ "customer_id": customer_id,
+ "email": connection.email,
+ "name": connection.name,
+ "connected_at": connection.connected_at.isoformat() if connection.connected_at else None,
+ }
+
+
[email protected]("/customer/{customer_id}/disconnect")
+async def disconnect_customer_gmail(customer_id: str):
+ """Disconnect a customer's Gmail."""
+ database = get_database()
+ await database.delete_gmail_connection(customer_id)
+ logger.info(f"Gmail 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"
+ else:
+ title, message, color = "Connection Failed", error or "Failed to connect", "#ea4335"
+
+ return f"""<!DOCTYPE html>
+<html>
+<head><title>{title}</title>
+<style>
+*{{margin:0;padding:0;box-sizing:border-box}}
+body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:linear-gradient(135deg,#15202b,#1a1a2e);min-height:100vh;display:flex;align-items:center;justify-content:center;color:#fff}}
+.container{{text-align:center;padding:40px;background:rgba(255,255,255,0.05);border-radius:16px;border:1px solid rgba(255,255,255,0.1);max-width:400px}}
+.icon{{width:64px;height:64px;margin-bottom:20px;color:{color}}}
+h1{{font-size:24px;margin-bottom:12px;color:{color}}}
+p{{font-size:16px;color:rgba(255,255,255,0.8);margin-bottom:20px}}
+.close-text{{font-size:14px;color:rgba(255,255,255,0.5)}}
+</style></head>
+<body><div class="container">
+<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+{"<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'/>" if success else "<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z'/>"}
+</svg>
+<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 ""}}},'*')}}
+setTimeout(function(){{window.close()}},2000);
+</script></body></html>"""
diff --git a/server/routers/twitter.py b/server/routers/twitter.py
index befbabc6..8f4147b5 100644
--- a/server/routers/twitter.py
+++ b/server/routers/twitter.py
@@ -27,6 +27,11 @@ logger = get_logger(__name__)
router = APIRouter(prefix="/api/twitter", tags=["twitter"])
+def get_settings():
+ """Get application settings."""
+ return container.settings()
+
+
def get_auth_service():
"""Get auth service for API key storage."""
return container.auth_service()
@@ -45,9 +50,8 @@ def get_twitter_oauth() -> TwitterOAuth:
client_id = loop.run_until_complete(auth_service.get_api_key("twitter_client_id")) or ""
client_secret = loop.run_until_complete(auth_service.get_api_key("twitter_client_secret"))
- # Redirect URI is determined by the server host
- # Default to localhost for development
- redirect_uri = "http://localhost:3010/api/twitter/callback"
+ settings = get_settings()
+ redirect_uri = settings.twitter_redirect_uri
return TwitterOAuth(
client_id=client_id,
@@ -104,6 +108,7 @@ async def twitter_oauth_callback(
)
# Get stored client credentials to create OAuth instance
+ settings = get_settings()
auth_service = get_auth_service()
client_id = await auth_service.get_api_key("twitter_client_id") or ""
client_secret = await auth_service.get_api_key("twitter_client_secret")
@@ -111,7 +116,7 @@ async def twitter_oauth_callback(
oauth = TwitterOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri="http://localhost:3010/api/twitter/callback",
+ redirect_uri=settings.twitter_redirect_uri,
)
# Exchange code for tokens
@@ -211,13 +216,14 @@ async def get_twitter_status():
}
# Get stored client credentials
+ settings = get_settings()
client_id = await auth_service.get_api_key("twitter_client_id") or ""
client_secret = await auth_service.get_api_key("twitter_client_secret")
oauth = TwitterOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri="http://localhost:3010/api/twitter/callback",
+ redirect_uri=settings.twitter_redirect_uri,
)
# Verify token is still valid by getting user info
@@ -282,10 +288,11 @@ async def twitter_logout():
# Revoke tokens if we have them
if access_token or refresh_token:
+ settings = get_settings()
oauth = TwitterOAuth(
client_id=client_id,
client_secret=client_secret,
- redirect_uri="http://localhost:3010/api/twitter/callback",
+ redirect_uri=settings.twitter_redirect_uri,
)
if access_token:
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 2d2ce064..9c679785 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1202,6 +1202,129 @@ async def handle_twitter_logout(data: Dict[str, Any], websocket: WebSocket) -> D
return {"success": True, "message": "Twitter disconnected"}
+# ============================================================================
+# Gmail OAuth Handlers
+# ============================================================================
+
+@ws_handler()
+async def handle_gmail_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Initiate Gmail OAuth 2.0 flow.
+
+ Opens browser to Google authorization page. After user authorizes,
+ Google redirects to /api/gmail/callback which stores tokens.
+ """
+ import webbrowser
+ from services.gmail_oauth import GmailOAuth
+
+ 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")
+
+ 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."
+ }
+
+ oauth = GmailOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri=settings.gmail_redirect_uri,
+ )
+
+ auth_data = oauth.generate_authorization_url()
+
+ webbrowser.open(auth_data["url"])
+
+ return {
+ "success": True,
+ "message": "Opening Google authorization in browser...",
+ "state": auth_data["state"],
+ }
+
+
+@ws_handler()
+async def handle_gmail_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Check Gmail OAuth connection status.
+
+ Returns connection status and user info if connected.
+ """
+ from services.gmail_oauth import GmailOAuth
+
+ auth_service = container.auth_service()
+ settings = container.settings()
+
+ access_token = await auth_service.get_api_key("gmail_access_token")
+
+ if not access_token:
+ return {
+ "connected": False,
+ "email": None,
+ "name": None,
+ }
+
+ user_info_str = await auth_service.get_api_key("gmail_user_info")
+ email, name = None, None
+ if user_info_str:
+ parts = user_info_str.split(":", 1)
+ email = parts[0] if parts else None
+ name = parts[1] if len(parts) > 1 else None
+
+ # 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")
+
+ # Try to refresh if needed
+ if refresh_token and client_id and client_secret:
+ refreshed = GmailOAuth.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",
+ api_key=refreshed["access_token"],
+ models=[],
+ session_id="default"
+ )
+
+ return {
+ "connected": True,
+ "email": email,
+ "name": name,
+ }
+ except Exception as e:
+ logger.warning(f"Gmail token validation failed: {e}")
+ return {
+ "connected": False,
+ "email": None,
+ "name": None,
+ "error": str(e),
+ }
+
+
+@ws_handler()
+async def handle_gmail_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Disconnect Gmail 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")
+
+ return {"success": True, "message": "Gmail disconnected"}
+
+
@ws_handler("url")
async def handle_test_ai_proxy(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Test connectivity to an AI proxy server."""
@@ -2463,6 +2586,11 @@ 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,
+
# Android operations
"get_android_devices": handle_get_android_devices,
"execute_android_action": handle_execute_android_action,
diff --git a/server/services/ai.py b/server/services/ai.py
index 3a1ad398..7d6a5d9e 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2960,6 +2960,66 @@ class AIService:
return TwitterUserSchema
+ # Gmail Send tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailSend':
+ class GmailSendSchema(BaseModel):
+ """Send emails via Gmail. Supports text and HTML body types."""
+ to: str = Field(
+ description="Recipient email address(es), comma-separated for multiple"
+ )
+ subject: str = Field(
+ description="Email subject line"
+ )
+ body: str = Field(
+ description="Email body content"
+ )
+ cc: Optional[str] = Field(
+ default=None,
+ description="CC recipients, comma-separated"
+ )
+ bcc: Optional[str] = Field(
+ default=None,
+ description="BCC recipients, comma-separated"
+ )
+ body_type: str = Field(
+ default="text",
+ description="Body type: 'text' (plain text) or 'html'"
+ )
+
+ return GmailSendSchema
+
+ # Gmail Search tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailSearch':
+ class GmailSearchSchema(BaseModel):
+ """Search emails in Gmail inbox using Gmail query syntax."""
+ query: str = Field(
+ description="Gmail search query (same syntax as Gmail web). Examples: 'from:[email protected]', 'subject:meeting', 'is:unread', 'has:attachment'"
+ )
+ max_results: int = Field(
+ default=10,
+ description="Maximum number of messages to return (1-100)"
+ )
+ include_body: bool = Field(
+ default=False,
+ description="Whether to fetch full message body (slower but more complete)"
+ )
+
+ return GmailSearchSchema
+
+ # Gmail Read tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailRead':
+ class GmailReadSchema(BaseModel):
+ """Read a specific email message by its ID."""
+ message_id: str = Field(
+ description="The Gmail message ID to read"
+ )
+ format: str = Field(
+ default="full",
+ description="Format: 'full' (complete message), 'minimal' (IDs only), 'raw' (RFC 2822), 'metadata' (headers only)"
+ )
+
+ return GmailReadSchema
+
# 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/gmail_oauth.py
new file mode 100644
index 00000000..c8f3e3fe
--- /dev/null
+++ b/server/services/gmail_oauth.py
@@ -0,0 +1,253 @@
+"""
+Gmail OAuth 2.0 using google-auth-oauthlib library.
+
+Two access modes:
+1. Owner Mode - Your own Gmail (Credentials Modal)
+2. Customer Mode - Customer's Gmail (database storage)
+
+Docs: https://googleapis.dev/python/google-auth-oauthlib/latest/reference/google_auth_oauthlib.flow.html
+"""
+
+import json
+import secrets
+import time
+from typing import Any, Dict, List, Optional
+
+from google.auth.transport.requests import Request
+from google.oauth2.credentials import Credentials
+from google_auth_oauthlib.flow import Flow
+from googleapiclient.discovery import build
+
+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",
+]
+
+# 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."""
+
+ def __init__(
+ self,
+ client_id: str,
+ client_secret: str,
+ redirect_uri: str = "http://localhost:3010/api/gmail/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
+
+ # 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",
+ "redirect_uris": [redirect_uri],
+ }
+ }
+
+ def generate_authorization_url(
+ self,
+ state_data: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, str]:
+ """
+ Generate OAuth authorization URL.
+
+ Args:
+ state_data: Optional data (customer_id, mode, redirect_after)
+
+ Returns:
+ Dict with url and state
+ """
+ # Create Flow from client config
+ flow = Flow.from_client_config(
+ self.client_config,
+ scopes=self.scopes,
+ redirect_uri=self.redirect_uri,
+ )
+
+ # Generate authorization URL with offline access for refresh tokens
+ authorization_url, state = flow.authorization_url(
+ access_type="offline",
+ include_granted_scopes="true",
+ prompt="consent", # Force consent to get refresh token
+ )
+
+ # Store state data for callback verification
+ _oauth_states[state] = {
+ "created_at": time.time(),
+ "data": state_data or {"mode": "owner"},
+ }
+
+ logger.info("Generated Gmail OAuth URL", state=state[:8])
+
+ return {
+ "url": authorization_url,
+ "state": state,
+ }
+
+ def exchange_code(self, code: str, state: str) -> Dict[str, Any]:
+ """
+ Exchange authorization code for credentials.
+
+ Args:
+ code: Authorization code from callback
+ state: State for verification
+
+ Returns:
+ Dict with tokens and user info
+ """
+ # Verify state
+ oauth_state = _oauth_states.pop(state, None)
+ if not oauth_state:
+ return {"success": False, "error": "Invalid or expired state"}
+
+ state_data = oauth_state.get("data", {})
+
+ try:
+ # Create Flow and fetch token
+ flow = Flow.from_client_config(
+ self.client_config,
+ scopes=self.scopes,
+ redirect_uri=self.redirect_uri,
+ state=state,
+ )
+ flow.fetch_token(code=code)
+
+ # Get credentials from flow
+ creds = flow.credentials
+
+ # Get user info
+ user_info = self._get_user_info(creds)
+
+ logger.info("Gmail OAuth successful", email=user_info.get("email", "")[:20])
+
+ return {
+ "success": True,
+ "access_token": creds.token,
+ "refresh_token": creds.refresh_token,
+ "expires_in": 3600,
+ "token_uri": creds.token_uri,
+ "client_id": creds.client_id,
+ "client_secret": creds.client_secret,
+ "scopes": list(creds.scopes) if creds.scopes else self.scopes,
+ "state_data": state_data,
+ "email": user_info.get("email"),
+ "name": user_info.get("name"),
+ }
+
+ except Exception as e:
+ logger.error("Token exchange failed", error=str(e))
+ return {"success": False, "error": str(e)}
+
+ def _get_user_info(self, creds: Credentials) -> Dict[str, Any]:
+ """Get user info using credentials."""
+ try:
+ service = build("oauth2", "v2", credentials=creds)
+ user_info = service.userinfo().get().execute()
+ return {
+ "email": user_info.get("email"),
+ "name": user_info.get("name"),
+ "picture": user_info.get("picture"),
+ }
+ except Exception as e:
+ logger.error("Failed to get user info", error=str(e))
+ return {}
+
+ @staticmethod
+ def refresh_credentials(
+ refresh_token: str,
+ client_id: str,
+ client_secret: str,
+ token_uri: str = "https://oauth2.googleapis.com/token",
+ ) -> Dict[str, Any]:
+ """
+ Refresh expired credentials.
+
+ Args:
+ refresh_token: The refresh token
+ client_id: OAuth client ID
+ client_secret: OAuth client secret
+ token_uri: Token endpoint
+
+ Returns:
+ Dict with new access_token
+ """
+ try:
+ creds = Credentials(
+ token=None,
+ refresh_token=refresh_token,
+ token_uri=token_uri,
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+ creds.refresh(Request())
+
+ return {
+ "success": True,
+ "access_token": creds.token,
+ "expires_in": 3600,
+ }
+ except Exception as e:
+ logger.error("Token refresh failed", error=str(e))
+ return {"success": False, "error": str(e), "needs_reauth": True}
+
+ @staticmethod
+ def build_credentials(
+ access_token: str,
+ refresh_token: str,
+ client_id: str,
+ client_secret: str,
+ token_uri: str = "https://oauth2.googleapis.com/token",
+ scopes: Optional[List[str]] = None,
+ ) -> Credentials:
+ """
+ Build Credentials object from stored tokens.
+
+ Use this to create credentials for Gmail API calls.
+ """
+ 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,
+ )
+
+ @staticmethod
+ def build_gmail_service(creds: Credentials):
+ """Build Gmail API service from credentials."""
+ return build("gmail", "v1", credentials=creds)
+
+
+def cleanup_expired_states(max_age_seconds: int = 600):
+ """Remove expired OAuth states."""
+ current_time = time.time()
+ expired = [
+ state for state, data in _oauth_states.items()
+ if current_time - data["created_at"] > max_age_seconds
+ ]
+ for state in expired:
+ _oauth_states.pop(state, None)
+
+
+def get_pending_state(state: str) -> Optional[Dict[str, Any]]:
+ """Get pending state without removing it."""
+ return _oauth_states.get(state)
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index 248911d8..5b378638 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -31,6 +31,7 @@ from .android import (
from .code import (
handle_python_executor,
handle_javascript_executor,
+ handle_typescript_executor,
)
# HTTP handlers
@@ -73,6 +74,13 @@ from .twitter import (
handle_twitter_user,
)
+# Gmail handlers
+from .gmail import (
+ handle_gmail_send,
+ handle_gmail_search,
+ handle_gmail_read,
+)
+
# Social handlers (unified messaging)
from .social import (
handle_social_receive,
@@ -106,6 +114,7 @@ __all__ = [
# Code
'handle_python_executor',
'handle_javascript_executor',
+ 'handle_typescript_executor',
# HTTP
'handle_http_request',
'handle_webhook_response',
@@ -131,6 +140,10 @@ __all__ = [
'handle_twitter_send',
'handle_twitter_search',
'handle_twitter_user',
+ # Gmail
+ 'handle_gmail_send',
+ 'handle_gmail_search',
+ 'handle_gmail_read',
# Social
'handle_social_receive',
'handle_social_send',
diff --git a/server/services/handlers/code.py b/server/services/handlers/code.py
index 11e120bf..9c52adc3 100644
--- a/server/services/handlers/code.py
+++ b/server/services/handlers/code.py
@@ -3,11 +3,23 @@
import json
import time
from datetime import datetime
-from typing import Dict, Any
+from typing import Dict, Any, Optional
from core.logging import get_logger
+from services.nodejs_client import NodeJSClient
logger = get_logger(__name__)
+# Module-level client instance (initialized on first use)
+_nodejs_client: Optional[NodeJSClient] = None
+
+
+def get_nodejs_client(base_url: str, timeout: int) -> NodeJSClient:
+ """Get or create Node.js client instance."""
+ global _nodejs_client
+ if _nodejs_client is None:
+ _nodejs_client = NodeJSClient(base_url, timeout)
+ return _nodejs_client
+
async def handle_python_executor(
node_id: str,
@@ -121,11 +133,13 @@ async def handle_javascript_executor(
node_type: str,
parameters: Dict[str, Any],
context: Dict[str, Any],
- connected_outputs: Dict[str, Any] = None
+ connected_outputs: Dict[str, Any] = None,
+ nodejs_url: str = None,
+ nodejs_timeout: int = None
) -> Dict[str, Any]:
"""Handle JavaScript executor node execution.
- Executes JavaScript code using Node.js subprocess with sandboxing.
+ Executes JavaScript code via persistent Node.js server.
Args:
node_id: The node ID
@@ -133,20 +147,17 @@ async def handle_javascript_executor(
parameters: Resolved parameters
context: Execution context
connected_outputs: Outputs from connected nodes
+ nodejs_url: Node.js server URL (from settings)
+ nodejs_timeout: Request timeout in seconds (from settings)
Returns:
Execution result dict with output and console output
"""
- import subprocess
- import tempfile
- import os
-
start_time = time.time()
- console_output = ""
try:
code = parameters.get('code', '')
- timeout = int(parameters.get('timeout', 30))
+ timeout_ms = int(parameters.get('timeout', 30)) * 1000 # Convert to milliseconds
if not code.strip():
return {
@@ -162,117 +173,147 @@ async def handle_javascript_executor(
# Get input data from connected nodes
input_data = connected_outputs or {}
- # Wrapper script that provides input_data and captures output
- wrapper_code = f'''
-const input_data = {json.dumps(input_data)};
-let output = null;
-
-// Capture console.log
-const logs = [];
-const originalLog = console.log;
-const originalError = console.error;
-const originalWarn = console.warn;
-
-console.log = (...args) => {{
- logs.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));
-}};
-console.error = (...args) => {{
- logs.push('[ERROR] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));
-}};
-console.warn = (...args) => {{
- logs.push('[WARN] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));
-}};
-
-try {{
- {code}
-}} catch (e) {{
- console.error(e.message);
- throw e;
-}}
-
-// Output result
-console.log = originalLog;
-process.stdout.write(JSON.stringify({{
- __output__: output,
- __logs__: logs
-}}));
-'''
-
- # Write to temp file and execute with Node.js
- with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
- f.write(wrapper_code)
- temp_file = f.name
-
- try:
- result = subprocess.run(
- ['node', temp_file],
- capture_output=True,
- text=True,
- timeout=timeout,
- cwd=tempfile.gettempdir()
- )
-
- if result.returncode != 0:
- error_msg = result.stderr.strip() if result.stderr else "JavaScript execution failed"
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "javascriptExecutor",
- "error": error_msg,
- "console_output": result.stdout,
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat()
- }
-
- # Parse output
- stdout = result.stdout.strip()
- if stdout:
- output_data = json.loads(stdout)
- output = output_data.get('__output__')
- console_output = '\n'.join(output_data.get('__logs__', []))
- else:
- output = None
- console_output = ""
-
+ # Get Node.js client
+ client = get_nodejs_client(
+ nodejs_url or "http://localhost:3020",
+ nodejs_timeout or 30
+ )
+
+ # Execute via Node.js server
+ result = await client.execute(
+ code=code,
+ input_data=input_data,
+ timeout=timeout_ms,
+ language="javascript"
+ )
+
+ if result.get("success"):
return {
"success": True,
"node_id": node_id,
"node_type": "javascriptExecutor",
"result": {
- "output": output,
- "console_output": console_output,
+ "output": result.get("output"),
+ "console_output": result.get("console_output", ""),
"timestamp": datetime.now().isoformat()
},
- "console_output": console_output,
+ "console_output": result.get("console_output", ""),
"execution_time": time.time() - start_time,
"timestamp": datetime.now().isoformat()
}
- finally:
- # Clean up temp file
- try:
- os.unlink(temp_file)
- except:
- pass
-
- except subprocess.TimeoutExpired:
- logger.error("JavaScript execution timed out", node_id=node_id, timeout=timeout)
+ else:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "javascriptExecutor",
+ "error": result.get("error", "Unknown error"),
+ "console_output": result.get("console_output", ""),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ logger.error("JavaScript execution failed", node_id=node_id, error=str(e))
return {
"success": False,
"node_id": node_id,
"node_type": "javascriptExecutor",
- "error": f"Execution timed out after {timeout} seconds",
- "console_output": console_output,
+ "error": str(e),
+ "console_output": "",
"execution_time": time.time() - start_time,
"timestamp": datetime.now().isoformat()
}
+
+
+async def handle_typescript_executor(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+ connected_outputs: Dict[str, Any] = None,
+ nodejs_url: str = None,
+ nodejs_timeout: int = None
+) -> Dict[str, Any]:
+ """Handle TypeScript executor node execution.
+
+ Executes TypeScript code via persistent Node.js server.
+
+ Args:
+ node_id: The node ID
+ node_type: The node type (typescriptExecutor)
+ parameters: Resolved parameters
+ context: Execution context
+ connected_outputs: Outputs from connected nodes
+ nodejs_url: Node.js server URL (from settings)
+ nodejs_timeout: Request timeout in seconds (from settings)
+
+ Returns:
+ Execution result dict with output and console output
+ """
+ start_time = time.time()
+
+ try:
+ code = parameters.get('code', '')
+ timeout_ms = int(parameters.get('timeout', 30)) * 1000
+
+ if not code.strip():
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "typescriptExecutor",
+ "error": "No code provided",
+ "console_output": "",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ input_data = connected_outputs or {}
+
+ client = get_nodejs_client(
+ nodejs_url or "http://localhost:3020",
+ nodejs_timeout or 30
+ )
+
+ result = await client.execute(
+ code=code,
+ input_data=input_data,
+ timeout=timeout_ms,
+ language="typescript"
+ )
+
+ if result.get("success"):
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "typescriptExecutor",
+ "result": {
+ "output": result.get("output"),
+ "console_output": result.get("console_output", ""),
+ "timestamp": datetime.now().isoformat()
+ },
+ "console_output": result.get("console_output", ""),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ else:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "typescriptExecutor",
+ "error": result.get("error", "Unknown error"),
+ "console_output": result.get("console_output", ""),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
except Exception as e:
- logger.error("JavaScript execution failed", node_id=node_id, error=str(e))
+ logger.error("TypeScript execution failed", node_id=node_id, error=str(e))
return {
"success": False,
"node_id": node_id,
- "node_type": "javascriptExecutor",
+ "node_type": "typescriptExecutor",
"error": str(e),
- "console_output": console_output,
+ "console_output": "",
"execution_time": time.time() - start_time,
"timestamp": datetime.now().isoformat()
}
diff --git a/server/services/handlers/gmail.py b/server/services/handlers/gmail.py
new file mode 100644
index 00000000..e0f8277b
--- /dev/null
+++ b/server/services/handlers/gmail.py
@@ -0,0 +1,416 @@
+"""Gmail node handlers using Google API Python client."""
+
+import asyncio
+import base64
+import time
+from email.mime.text import MIMEText
+from email.mime.multipart import MIMEMultipart
+from typing import Dict, Any
+
+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_gmail_usage(
+ node_id: str,
+ action: str,
+ resource_count: int = 1,
+ workflow_id: str = None,
+ session_id: str = "default"
+) -> Dict[str, float]:
+ """Track Gmail API usage for analytics.
+
+ Note: Gmail API is free but rate limited (250 quota units/user/second).
+ We track for analytics purposes with $0 cost.
+
+ Args:
+ node_id: The node executing the Gmail action
+ action: Action name matching operation_map keys (send, search, read, etc.)
+ resource_count: Number of resources processed
+ workflow_id: Optional workflow context
+ session_id: Session for aggregation
+
+ Returns:
+ Cost breakdown dict (always 0 for Gmail)
+ """
+ from core.container import container
+
+ pricing = get_pricing_service()
+ cost_data = pricing.calculate_api_cost('gmail', action, resource_count)
+
+ db = container.database()
+ await db.save_api_usage_metric({
+ 'session_id': session_id,
+ 'node_id': node_id,
+ 'workflow_id': workflow_id,
+ 'service': 'gmail',
+ 'operation': cost_data.get('operation', action),
+ 'endpoint': action,
+ 'resource_count': resource_count,
+ 'cost': cost_data.get('total_cost', 0.0)
+ })
+
+ logger.debug(f"[Gmail] Tracked usage: {action} x{resource_count}")
+ return cost_data
+
+
+async def _get_gmail_service(
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+):
+ """Get authenticated Gmail service.
+
+ Supports two modes:
+ - Owner mode: Uses tokens from auth_service (Credentials Modal)
+ - Customer mode: Uses tokens from gmail_connections table
+
+ Args:
+ parameters: Node parameters (may include account_mode, customer_id)
+ context: Execution context
+
+ Returns:
+ Gmail API service object
+ """
+ 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_gmail_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Gmail connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Gmail connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_gmail_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")
+
+ if not access_token:
+ raise ValueError("Gmail 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 ""
+
+ 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("gmail", "v1", credentials=creds)
+
+ loop = asyncio.get_event_loop()
+ service = await loop.run_in_executor(None, build_service)
+
+ return service
+
+
+async def handle_gmail_send(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Gmail send operations.
+
+ Parameters:
+ to: Recipient email address(es), comma-separated
+ cc: CC recipients (optional)
+ bcc: BCC recipients (optional)
+ subject: Email subject
+ body: Email body content
+ body_type: 'text' or 'html' (default: 'text')
+ """
+ start_time = time.time()
+
+ try:
+ service = await _get_gmail_service(parameters, context)
+
+ to = parameters.get('to', '')
+ cc = parameters.get('cc', '')
+ bcc = parameters.get('bcc', '')
+ subject = parameters.get('subject', '')
+ body = parameters.get('body', '')
+ body_type = parameters.get('body_type', 'text')
+
+ if not to:
+ raise ValueError("Recipient email address (to) is required")
+ if not subject:
+ raise ValueError("Email subject is required")
+ if not body:
+ raise ValueError("Email body is required")
+
+ workflow_id = context.get('workflow_id')
+ session_id = context.get('session_id', 'default')
+
+ if body_type == 'html':
+ message = MIMEMultipart('alternative')
+ message.attach(MIMEText(body, 'html'))
+ else:
+ message = MIMEText(body, 'plain')
+
+ message['to'] = to
+ message['subject'] = subject
+ if cc:
+ message['cc'] = cc
+ if bcc:
+ message['bcc'] = bcc
+
+ raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')
+
+ def send_message():
+ return service.users().messages().send(
+ userId='me',
+ body={'raw': raw_message}
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, send_message)
+
+ await _track_gmail_usage(node_id, 'send', 1, workflow_id, session_id)
+
+ return {
+ "success": True,
+ "result": {
+ "message_id": result.get('id'),
+ "thread_id": result.get('threadId'),
+ "label_ids": result.get('labelIds', []),
+ "to": to,
+ "subject": subject,
+ },
+ "execution_time": time.time() - start_time
+ }
+
+ except Exception as e:
+ logger.error(f"Gmail send error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+async def handle_gmail_search(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Gmail search operations.
+
+ Parameters:
+ query: Gmail search query (same syntax as Gmail web)
+ max_results: Maximum number of messages to return (default: 10, max: 100)
+ include_body: Whether to fetch full message body (default: False)
+ """
+ start_time = time.time()
+
+ try:
+ service = await _get_gmail_service(parameters, context)
+
+ query = parameters.get('query', '')
+ max_results = min(parameters.get('max_results', 10), 100)
+ include_body = parameters.get('include_body', False)
+
+ if not query:
+ raise ValueError("Search query is required")
+
+ workflow_id = context.get('workflow_id')
+ session_id = context.get('session_id', 'default')
+
+ def search_messages():
+ return service.users().messages().list(
+ userId='me',
+ q=query,
+ maxResults=max_results
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, search_messages)
+
+ messages = result.get('messages', [])
+ formatted_messages = []
+
+ for msg in messages:
+ msg_id = msg.get('id')
+
+ def get_message(message_id):
+ format_type = 'full' if include_body else 'metadata'
+ return service.users().messages().get(
+ userId='me',
+ id=message_id,
+ format=format_type,
+ metadataHeaders=['From', 'To', 'Subject', 'Date']
+ ).execute()
+
+ msg_detail = await loop.run_in_executor(None, lambda mid=msg_id: get_message(mid))
+ formatted_messages.append(_format_message(msg_detail, include_body))
+
+ await _track_gmail_usage(node_id, 'search', len(formatted_messages), workflow_id, session_id)
+
+ return {
+ "success": True,
+ "result": {
+ "messages": formatted_messages,
+ "count": len(formatted_messages),
+ "query": query,
+ "result_size_estimate": result.get('resultSizeEstimate', 0),
+ },
+ "execution_time": time.time() - start_time
+ }
+
+ except Exception as e:
+ logger.error(f"Gmail search error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+async def handle_gmail_read(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Gmail read operations - read a specific message by ID.
+
+ Parameters:
+ message_id: The Gmail message ID to read
+ format: 'full', 'minimal', 'raw', or 'metadata' (default: 'full')
+ """
+ start_time = time.time()
+
+ try:
+ service = await _get_gmail_service(parameters, context)
+
+ message_id = parameters.get('message_id', '')
+ format_type = parameters.get('format', 'full')
+
+ if not message_id:
+ raise ValueError("message_id is required")
+
+ workflow_id = context.get('workflow_id')
+ session_id = context.get('session_id', 'default')
+
+ def get_message():
+ return service.users().messages().get(
+ userId='me',
+ id=message_id,
+ format=format_type
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, get_message)
+
+ await _track_gmail_usage(node_id, 'read', 1, workflow_id, session_id)
+
+ return {
+ "success": True,
+ "result": _format_message(result, include_body=(format_type == 'full')),
+ "execution_time": time.time() - start_time
+ }
+
+ except Exception as e:
+ logger.error(f"Gmail read error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+def _format_message(message: Dict[str, Any], include_body: bool = False) -> Dict[str, Any]:
+ """Format Gmail message to a cleaner structure."""
+ headers = {}
+ payload = message.get('payload', {})
+
+ for header in payload.get('headers', []):
+ name = header.get('name', '').lower()
+ value = header.get('value', '')
+ if name in ['from', 'to', 'subject', 'date', 'cc', 'bcc']:
+ headers[name] = value
+
+ formatted = {
+ "message_id": message.get('id'),
+ "thread_id": message.get('threadId'),
+ "from": headers.get('from', ''),
+ "to": headers.get('to', ''),
+ "cc": headers.get('cc', ''),
+ "subject": headers.get('subject', ''),
+ "date": headers.get('date', ''),
+ "snippet": message.get('snippet', ''),
+ "labels": message.get('labelIds', []),
+ "size_estimate": message.get('sizeEstimate', 0),
+ }
+
+ if include_body:
+ body = _extract_body(payload)
+ formatted['body'] = body
+
+ attachments = _extract_attachments(payload)
+ if attachments:
+ formatted['attachments'] = attachments
+
+ return formatted
+
+
+def _extract_body(payload: Dict[str, Any]) -> str:
+ """Extract email body from payload, handling multipart messages."""
+ body = ""
+
+ if 'body' in payload and payload['body'].get('data'):
+ body = base64.urlsafe_b64decode(payload['body']['data']).decode('utf-8', errors='ignore')
+ return body
+
+ parts = payload.get('parts', [])
+ for part in parts:
+ mime_type = part.get('mimeType', '')
+
+ if mime_type == 'text/plain':
+ if part.get('body', {}).get('data'):
+ body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8', errors='ignore')
+ break
+ elif mime_type == 'text/html' and not body:
+ if part.get('body', {}).get('data'):
+ body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8', errors='ignore')
+ elif mime_type.startswith('multipart/'):
+ nested_body = _extract_body(part)
+ if nested_body:
+ body = nested_body
+ break
+
+ return body
+
+
+def _extract_attachments(payload: Dict[str, Any]) -> list:
+ """Extract attachment information from payload."""
+ attachments = []
+ parts = payload.get('parts', [])
+
+ for part in parts:
+ filename = part.get('filename', '')
+ if filename:
+ attachments.append({
+ "filename": filename,
+ "mime_type": part.get('mimeType', ''),
+ "size": part.get('body', {}).get('size', 0),
+ "attachment_id": part.get('body', {}).get('attachmentId', ''),
+ })
+
+ if part.get('parts'):
+ nested = _extract_attachments(part)
+ attachments.extend(nested)
+
+ return attachments
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index f151720e..2c94096c 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -119,6 +119,18 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
if node_type == 'twitterUser':
return await _execute_twitter_user(tool_args, config.get('parameters', {}))
+ # Gmail Send (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailSend':
+ return await _execute_gmail_send(tool_args, config.get('parameters', {}))
+
+ # Gmail Search (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailSearch':
+ return await _execute_gmail_search(tool_args, config.get('parameters', {}))
+
+ # Gmail Read (dual-purpose: workflow node + AI tool)
+ if node_type == 'gmailRead':
+ return await _execute_gmail_read(tool_args, config.get('parameters', {}))
+
# Android toolkit - routes to connected service nodes
if node_type == 'androidTool':
return await _execute_android_toolkit(tool_args, config)
@@ -1202,6 +1214,75 @@ async def _execute_twitter_user(args: Dict[str, Any],
)
+async def _execute_gmail_send(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Gmail send action via Google API.
+
+ Args:
+ args: LLM-provided arguments (to, subject, body, cc, bcc, body_type)
+ node_params: Node parameters (may include account_mode, customer_id)
+
+ Returns:
+ Gmail API result with message_id and thread_id
+ """
+ from services.handlers.gmail import handle_gmail_send
+
+ parameters = {**node_params, **args}
+
+ return await handle_gmail_send(
+ node_id="tool_gmail_send",
+ node_type="gmailSend",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_gmail_search(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Gmail search via Google API.
+
+ Args:
+ args: LLM-provided arguments (query, max_results, include_body)
+ node_params: Node parameters (may include account_mode, customer_id)
+
+ Returns:
+ Search results with message list
+ """
+ from services.handlers.gmail import handle_gmail_search
+
+ parameters = {**node_params, **args}
+
+ return await handle_gmail_search(
+ node_id="tool_gmail_search",
+ node_type="gmailSearch",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_gmail_read(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Gmail read via Google API.
+
+ Args:
+ args: LLM-provided arguments (message_id, format)
+ node_params: Node parameters (may include account_mode, customer_id)
+
+ Returns:
+ Full message content
+ """
+ from services.handlers.gmail import handle_gmail_read
+
+ parameters = {**node_params, **args}
+
+ return await handle_gmail_read(
+ node_id="tool_gmail_read",
+ node_type="gmailRead",
+ 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 cd384da4..65527f99 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -25,7 +25,7 @@ from services import event_waiter
from services.handlers import (
handle_ai_agent, handle_chat_agent, handle_ai_chat_model, handle_simple_memory,
handle_android_service,
- handle_python_executor, handle_javascript_executor,
+ handle_python_executor, handle_javascript_executor, handle_typescript_executor,
handle_http_request, handle_webhook_response, handle_trigger_node,
handle_create_map, handle_add_locations, handle_nearby_places,
handle_text_generator, handle_file_handler,
@@ -37,6 +37,7 @@ from services.handlers import (
handle_text_chunker, handle_embedding_generator, handle_vector_store,
handle_task_manager,
handle_twitter_send, handle_twitter_search, handle_twitter_user,
+ handle_gmail_send, handle_gmail_search, handle_gmail_read,
)
if TYPE_CHECKING:
@@ -139,6 +140,10 @@ class NodeExecutor:
'twitterSend': handle_twitter_send,
'twitterSearch': handle_twitter_search,
'twitterUser': handle_twitter_user,
+ # Gmail
+ 'gmailSend': handle_gmail_send,
+ 'gmailSearch': handle_gmail_search,
+ 'gmailRead': handle_gmail_read,
# Social (unified messaging)
# Note: socialReceive handled in _dispatch with connected_outputs
'socialSend': handle_social_send,
@@ -304,7 +309,7 @@ class NodeExecutor:
return await handler(node_id, node_type, params, context)
# Special handlers needing connected outputs
- if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse', 'console', 'socialReceive'):
+ if node_type in ('pythonExecutor', 'javascriptExecutor', 'typescriptExecutor', 'webhookResponse', 'console', 'socialReceive'):
logger.debug(f"[_dispatch] Getting connected outputs for {node_type} node_id={node_id}")
outputs, source_nodes = await self._get_connected_outputs_with_info(context, node_id)
logger.debug(f"[_dispatch] Got {len(outputs)} outputs for {node_type}: keys={list(outputs.keys())}")
@@ -315,6 +320,7 @@ class NodeExecutor:
handlers = {
'pythonExecutor': handle_python_executor,
'javascriptExecutor': handle_javascript_executor,
+ 'typescriptExecutor': handle_typescript_executor,
'webhookResponse': handle_webhook_response,
}
return await handlers[node_type](node_id, node_type, params, context, outputs)
diff --git a/server/services/nodejs_client.py b/server/services/nodejs_client.py
new file mode 100644
index 00000000..c2ffb484
--- /dev/null
+++ b/server/services/nodejs_client.py
@@ -0,0 +1,90 @@
+"""HTTP client for Node.js code execution server."""
+
+from typing import Any, Dict, List, Optional
+import aiohttp
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+class NodeJSClient:
+ """Async HTTP client for Node.js executor service."""
+
+ def __init__(self, base_url: str, timeout: int = 30):
+ """Initialize client with base URL and timeout.
+
+ Args:
+ base_url: Base URL of Node.js server (e.g., http://127.0.0.1:3020)
+ timeout: Default request timeout in seconds
+ """
+ self._base_url = base_url.rstrip('/')
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
+
+ async def health_check(self) -> Dict[str, Any]:
+ """Check if Node.js server is healthy.
+
+ Returns:
+ Health status dict with status, service, node_version
+ """
+ async with aiohttp.ClientSession(timeout=self._timeout) as session:
+ async with session.get(f"{self._base_url}/health") as response:
+ return await response.json()
+
+ async def execute(
+ self,
+ code: str,
+ input_data: Optional[Dict[str, Any]] = None,
+ timeout: Optional[int] = None,
+ language: str = "javascript"
+ ) -> Dict[str, Any]:
+ """Execute JavaScript/TypeScript code.
+
+ Args:
+ code: Code to execute
+ input_data: Data available as input_data in code
+ timeout: Execution timeout in milliseconds
+ language: 'javascript' or 'typescript'
+
+ Returns:
+ Execution result with success, output, console_output, execution_time_ms
+ """
+ payload = {
+ "code": code,
+ "input_data": input_data or {},
+ "language": language,
+ }
+ if timeout is not None:
+ payload["timeout"] = timeout
+
+ async with aiohttp.ClientSession(timeout=self._timeout) as session:
+ async with session.post(
+ f"{self._base_url}/execute",
+ json=payload
+ ) as response:
+ return await response.json()
+
+ async def install_packages(self, packages: List[str]) -> Dict[str, Any]:
+ """Install npm packages.
+
+ Args:
+ packages: List of package names (e.g., ['lodash', '[email protected]'])
+
+ Returns:
+ Result with success and message
+ """
+ async with aiohttp.ClientSession(timeout=self._timeout) as session:
+ async with session.post(
+ f"{self._base_url}/packages/install",
+ json={"packages": packages}
+ ) as response:
+ return await response.json()
+
+ async def list_packages(self) -> Dict[str, Any]:
+ """List installed npm packages.
+
+ Returns:
+ Dict with success and packages dict
+ """
+ async with aiohttp.ClientSession(timeout=self._timeout) as session:
+ async with session.get(f"{self._base_url}/packages") as response:
+ return await response.json()
diff --git a/server/start.sh b/server/start.sh
new file mode 100644
index 00000000..e7a6fc2f
--- /dev/null
+++ b/server/start.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Start both Python and Node.js servers
+
+# Start Node.js executor in background
+cd /app/nodejs && npm start &
+
+# Start Python server (foreground)
+python -m uvicorn main:app --host 0.0.0.0 --port ${PORT:-3010}