Skip to content

Self-improving AI Employees for everyone

feat: Add Agent Teams pattern, Twitter integration, and pricing service

trohitge20c75e0b250
diff --git a/CLAUDE.md b/CLAUDE.md
index 9f3c303e..e8b52360 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -15,6 +15,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Dual-Purpose Tool Guide](./docs-internal/dual_purpose_tool_node_creation.md)** | Guide for nodes that work as both workflow nodes AND AI Agent tools (e.g., whatsappSend) |
| **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute via LangGraph |
| **[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) |
| **[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 |
@@ -58,6 +59,7 @@ server/services/
├── workflow.py # Facade (~460 lines) - thin coordinator
├── node_executor.py # Single node execution with registry pattern
├── parameter_resolver.py # Template variable resolution
+├── agent_team.py # AgentTeamService for multi-agent coordination
├── deployment/ # Event-driven deployment lifecycle
│ ├── __init__.py
│ ├── state.py # DeploymentState, TriggerInfo dataclasses
@@ -87,7 +89,7 @@ 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 tables
+└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage, TokenUsageMetric, CompactionEvent, SessionTokenState, UserSettings, ProviderDefaults, AgentTeam, TeamMember, TeamTask, AgentMessage tables
```
### Polyglot Server Integration (Optional)
@@ -290,14 +292,14 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **77 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 12 specialized agents + 11 skills + 3 dedicated tools + 6 dual-purpose tools + 16 Android + 3 WhatsApp + 2 Social + 3 Location + 2 Code + 5 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow)
-- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (86 message handlers)
+- **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)
+- **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
## Architecture Refactoring
The project was completely refactored from schema-based node definitions to explicit INodeProperties interface system inspired by n8n architecture. Key changes:
- **Pure INodeProperties System**: Removed all backward compatibility layers
-- **75 Implemented Node Components**: AI models, agents, skills, location services, Android automation, WhatsApp, social, code execution, HTTP/Webhook utilities, document processing, chat, and schedulers
+- **79 Implemented Node Components**: AI models, agents, skills, location services, Android automation, WhatsApp, Twitter/X, social, code execution, HTTP/Webhook utilities, document processing, chat, and schedulers
- **WebSocket-First Communication**: 86 WebSocket message handlers replace most REST API calls
- **Resource-Operation Pattern**: Organized by functional categories (AI, Location, Android, WhatsApp)
- **TypeScript-First**: Full type safety with proper interface alignment
@@ -320,6 +322,7 @@ The project was completely refactored from schema-based node definitions to expl
- `src/nodeDefinitions/androidServiceNodes.ts` - 16 Android service nodes (monitoring, apps, automation, sensors, media)
- `src/nodeDefinitions/locationNodes.ts` - Google Maps and location services
- `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/utilityNodes.ts` - HTTP, Webhook, chatTrigger, and console nodes
@@ -437,11 +440,11 @@ React Flow edges use dynamic Dracula colors via `getEdgeStyles(theme.dracula)`:
### WebSocket-First Architecture
The project uses WebSocket as the primary communication method between frontend and backend, replacing most REST API calls:
- `src/contexts/WebSocketContext.tsx` - Central WebSocket context with request/response pattern
-- `server/routers/websocket.py` - WebSocket endpoint with 86 message handlers
+- `server/routers/websocket.py` - WebSocket endpoint with 87 message handlers
- `server/services/status_broadcaster.py` - Connection management and broadcasting
## Implemented Node Types
-The following 75 nodes are currently implemented and functional:
+The following 79 nodes are currently implemented and functional:
### AI Chat Models (6 nodes)
- **openaiChatModel**: OpenAI GPT models with response format options. O-series models (o1, o3, o4) support reasoning effort parameter.
@@ -479,6 +482,11 @@ server/skills/
├── android/ # Android device control skills
│ ├── personality/SKILL.md
│ └── skill/SKILL.md
+├── social_agent/ # Social media platform skills
+│ ├── twitter-send-skill/SKILL.md # Post tweets, reply, retweet, like/unlike, delete
+│ ├── twitter-search-skill/SKILL.md # Search tweets with query operators
+│ ├── twitter-user-skill/SKILL.md # User profile and followers/following lookup
+│ └── whatsapp-send-skill/SKILL.md # WhatsApp messaging skill
└── autonomous/ # Autonomous agent patterns (Code Mode research)
├── code-mode-skill/SKILL.md # Generate code instead of tool calls (81-98% token savings)
├── agentic-loop-skill/SKILL.md # OBSERVE-THINK-ACT-REFLECT-DECIDE pattern
@@ -610,7 +618,7 @@ if skill_type == 'masterSkill':
- **currentTimeTool**: Get current date/time with timezone support
- **webSearchTool**: Web search via DuckDuckGo (free, uses `ddgs` library) or Serper API with configurable max results
-### Specialized AI Agents (12 nodes)
+### Specialized AI Agents (13 nodes)
Specialized agents are AI Agents pre-configured for specific domains. They inherit full AI Agent functionality (provider, model, prompt, system message, thinking/reasoning) while being tailored for specific capabilities. All specialized agents route to `handle_chat_agent` in the backend and support the same input handles. Node colors use centralized dracula theme constants imported from `client/src/styles/theme.ts`.
**Input Handles:**
@@ -632,7 +640,8 @@ Specialized agents are AI Agents pre-configured for specific domains. They inher
- **payments_agent**: Payments Agent - AI agent for payment processing. Connect payment, invoice, and financial tool nodes.
- **consumer_agent**: Consumer Agent - AI agent for consumer interactions. Connect customer support, product, and order management tools.
- **autonomous_agent**: Autonomous Agent - AI agent for autonomous operations using Code Mode patterns. Uses agentic loops, progressive discovery, error recovery, and multi-tool orchestration for 81-98% token savings. Connect autonomous skills via Master Skill.
-- **orchestrator_agent**: Orchestrator Agent - AI agent for coordinating multiple agents in complex multi-agent workflows. Delegates tasks to specialized agents and synthesizes their results.
+- **orchestrator_agent**: Orchestrator Agent - Team lead agent for coordinating multiple agents. Connect specialized agents via `input-teammates` handle; they become `delegate_to_*` tools the AI can invoke.
+- **ai_employee**: AI Employee - Team lead agent similar to orchestrator_agent. Connect specialized agents via `input-teammates` handle for intelligent task delegation.
**Backend Routing:**
Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and routed to `handle_chat_agent`:
@@ -641,10 +650,29 @@ Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and routed to `hand
SPECIALIZED_AGENT_TYPES = {
'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
- 'autonomous_agent', 'orchestrator_agent'
+ 'autonomous_agent', 'orchestrator_agent', 'ai_employee'
}
```
+**Team Lead Types (Agent Teams Pattern):**
+Team leads (`orchestrator_agent`, `ai_employee`) have a special `input-teammates` handle. Agents connected to this handle become delegation tools:
+```python
+# In handlers/ai.py
+TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}
+
+# Teammates become delegate_to_* tools automatically
+if node_type in TEAM_LEAD_TYPES:
+ teammates = await _collect_teammate_connections(node_id, context, database)
+ if teammates:
+ for tm in teammates:
+ tool_data.append({
+ 'node_id': tm['node_id'],
+ 'node_type': tm['node_type'], # e.g., 'coding_agent'
+ 'label': tm['label'],
+ })
+ # AI now has delegate_to_coding_agent, delegate_to_web_agent, etc.
+```
+
**Direct Android Service Tools:**
Android service nodes (batteryMonitor, wifiAutomation, etc.) can be connected directly to any agent's `input-tools` handle. The backend maps camelCase node types to snake_case service IDs:
```python
@@ -741,6 +769,72 @@ Unified social messaging nodes for multi-platform communication. Supports WhatsA
- **socialReceive**: Normalizes messages from platform triggers into unified format. Multiple outputs: Message, Media, Contact, Metadata. Filters by channel, message type, sender.
- **socialSend**: **Dual-purpose node** - Send messages to any supported platform. Works as workflow node OR AI Agent tool. Supports text, image, video, audio, document, sticker, location, contact, poll, buttons, list message types.
+### Twitter/X Nodes (4 nodes)
+Twitter/X integration using the official XDK Python SDK with OAuth 2.0 PKCE authentication.
+
+- **twitterSend**: **Dual-purpose node** - Post tweets, reply, retweet, like/unlike, and delete tweets. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Actions: `tweet`, `reply`, `retweet`, `like`, `unlike`, `delete`. Parameters: action, text (280 char max), tweet_id, reply_to_id.
+- **twitterSearch**: **Dual-purpose node** - Search recent tweets using query operators. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Supports X API v2 query syntax: keywords, hashtags (#), mentions (@), from:user, to:user, -exclude, OR, lang:, has:links, has:media, is:retweet, -is:retweet.
+- **twitterUser**: **Dual-purpose node** - Look up user profiles and social connections. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Operations: `me` (get authenticated user), `by_username`, `by_id`, `followers`, `following`.
+- **twitterReceive**: Event-driven trigger that waits for incoming Twitter events (mentions, DMs, timeline updates). Group: `['social', 'trigger']`. Polling-based since X API free tier lacks webhooks.
+
+#### Twitter OAuth 2.0 Authentication
+Authentication is handled via OAuth 2.0 PKCE flow in the Credentials Modal:
+1. User clicks "Login with Twitter" button
+2. Backend generates PKCE code challenge and authorization URL
+3. Browser opens Twitter authorization page
+4. User grants permission, Twitter redirects with auth code
+5. Backend exchanges code for access_token + refresh_token
+6. Tokens stored in database via auth_service
+
+**Key Files:**
+| File | Description |
+|------|-------------|
+| `server/services/twitter_oauth.py` | OAuth 2.0 PKCE flow implementation |
+| `server/routers/twitter.py` | OAuth callback endpoint, token exchange |
+| `server/services/handlers/twitter.py` | Node handlers using XDK SDK |
+| `client/src/nodeDefinitions/twitterNodes.ts` | 4 node definitions |
+| `client/src/components/CredentialsModal.tsx` | Twitter panel with OAuth button |
+| `server/skills/social_agent/twitter-*-skill/` | 3 Twitter skills for AI agents |
+
+**XDK SDK API Patterns:**
+```python
+from xdk import Client
+
+# Create client with OAuth 2.0 user token
+client = Client(access_token=access_token)
+
+# Post tweet
+client.posts.create(body={"text": "Hello world!"})
+
+# Reply to tweet
+client.posts.create(body={"text": "Reply", "reply": {"in_reply_to_tweet_id": "123"}})
+
+# Retweet
+client.users.repost_post(user_id, body={"tweet_id": "123"})
+
+# Like/Unlike
+client.users.like_post(user_id, body={"tweet_id": "123"})
+client.users.unlike_post(user_id, tweet_id="123")
+
+# Delete
+client.posts.delete(tweet_id)
+
+# Search
+client.posts.search_recent(query="...", max_results=100, tweet_fields=["author_id", "created_at"])
+
+# User lookup
+client.users.get_me(user_fields=["created_at", "description"])
+client.users.get_by_usernames(usernames=["user1"], user_fields=["description"])
+client.users.get_followers(user_id, max_results=100, user_fields=["created_at"])
+```
+
+**Environment Variables:**
+```bash
+TWITTER_CLIENT_ID=your_client_id
+TWITTER_CLIENT_SECRET=your_client_secret
+TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback
+```
+
### Workflow Nodes (2 nodes)
- **start**: Manual workflow trigger to start workflow execution
- **taskTrigger**: Event-driven trigger that fires when a delegated child agent completes its task (success or error). Filters by task_id, agent_name, status (all/completed/error), and parent_node_id. Output includes task_id, status, agent_name, result/error, workflow_id.
@@ -749,12 +843,13 @@ Unified social messaging nodes for multi-platform communication. Supports WhatsA
- **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`).
-### Utility Nodes (5 nodes)
+### Utility Nodes (6 nodes)
- **httpRequest**: Make HTTP requests to external APIs (GET, POST, PUT, DELETE, PATCH) with configurable headers, body, and timeout
- **webhookTrigger**: Event-driven trigger that waits for incoming HTTP requests at `/webhook/{path}` with method filtering and authentication options
- **webhookResponse**: Send custom response back to webhook caller with configurable status code, body, and content type
- **chatTrigger**: Trigger node that receives messages from the Console Panel chat interface
- **console**: Console output node for logging workflow execution data
+- **teamMonitor**: Real-time monitoring of Agent Team operations. Connect to AI Employee or Orchestrator to display team status, active tasks, and event stream
### Document Processing Nodes (6 nodes)
RAG pipeline nodes for document ingestion, processing, and vector storage. Supports multiple providers and backends.
@@ -966,7 +1061,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
## Current Status
✅ **INodeProperties System**: Fully implemented with 75 functional node components
-✅ **WebSocket-First Architecture**: 86 message handlers replacing REST APIs
+✅ **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
✅ **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
@@ -1707,12 +1802,16 @@ The system supports specialized agent variants that inherit from the base AI Age
| Consumer | `consumer_agent` | cart | purple |
| Autonomous | `autonomous_agent` | target | purple |
| Orchestrator | `orchestrator_agent` | conductor | cyan |
+| AI Employee | `ai_employee` | briefcase | purple |
All specialized agents share the same handle configuration:
- **Left**: `input-main` (Input, 30%), `input-memory` (Memory, 55%), `input-task` (Task, 85%)
- **Bottom**: `input-skill` (Skill, 25%), `input-tools` (Tool, 75%)
- **Top**: `output-top` (Output)
+**Team Lead Agents** (`orchestrator_agent`, `ai_employee`) have an additional handle:
+- **Bottom**: `input-teammates` (Teammates, 50%) - Connect specialized agents here for delegation
+
The `AIAgentNode.tsx` component uses `AGENT_CONFIGS` to render all agent types with their specific icons, titles, and theme colors.
## Architecture Patterns
@@ -2595,17 +2694,18 @@ I don't have access to real-time weather data...
- **Window + Archive**: Short-term (recent messages) + long-term (semantic retrieval) memory pattern
- **Auto-Save**: AI Agent automatically saves updated markdown content to node parameters
-## Memory Compaction and Token Tracking
+## Memory Compaction, Token Tracking, and Cost Calculation
### Overview
-The compaction service enables automatic memory compaction and token tracking for specialized agents. It uses a hybrid approach: native compaction APIs for Anthropic/OpenAI, with tracking for all providers. Inspired by Claude Code's compaction pattern with a default 100,000 token threshold.
+The compaction service enables automatic memory compaction, token tracking, and **cost calculation** for all LLM providers. Cost is calculated using official pricing (per 1M tokens) and stored alongside token metrics. The Credentials Modal displays per-provider usage and costs.
### Architecture
```
AI Agent Execution
↓
-CompactionService.track() → Save token metrics to DB
- ↓ → Update cumulative session state
+CompactionService.track() → PricingService.calculate_cost()
+ ↓ → Save token metrics + cost to DB
+ ↓ → Update cumulative state + cost
↓ → Check if threshold exceeded
↓
If needs_compaction:
@@ -2649,23 +2749,25 @@ compaction_control = {
| File | Description |
|------|-------------|
| `server/services/compaction.py` | CompactionService with track(), record(), stats(), configure(), compact_context() methods |
+| `server/services/pricing.py` | PricingService with official pricing registry for all 6 providers |
| `server/services/ai.py` | `_track_token_usage()` with automatic compaction triggering |
-| `server/models/database.py` | TokenUsageMetric, CompactionEvent, SessionTokenState tables |
-| `server/core/database.py` | CRUD methods for token metrics and compaction events |
+| `server/models/database.py` | TokenUsageMetric, CompactionEvent, SessionTokenState tables (with cost fields) |
+| `server/core/database.py` | CRUD methods for token metrics, compaction events, and `get_provider_usage_summary()` |
| `server/core/config.py` | compaction_enabled, compaction_threshold settings |
| `server/core/container.py` | Dependency injection for compaction_service |
| `server/main.py` | Wires AI service to compaction service at startup |
-| `server/routers/websocket.py` | get_compaction_stats, configure_compaction handlers |
-| `client/src/components/parameterPanel/MiddleSection.tsx` | Token Usage UI with editable threshold |
+| `server/routers/websocket.py` | get_compaction_stats, configure_compaction, get_provider_usage_summary handlers |
+| `client/src/hooks/useApiKeys.ts` | `getProviderUsageSummary()` hook method |
+| `client/src/components/CredentialsModal.tsx` | Usage & Costs collapsible section per provider |
### Database Models
-**TokenUsageMetric** - Per-execution token usage:
+**TokenUsageMetric** - Per-execution token usage and cost:
```python
class TokenUsageMetric(SQLModel, table=True):
session_id: str # Memory session identifier
node_id: str # Agent node ID
- provider: str # openai, anthropic, gemini, groq, etc.
+ provider: str # openai, anthropic, gemini, groq, cerebras, openrouter
model: str # Model name
input_tokens: int # Input token count
output_tokens: int # Output token count
@@ -2673,6 +2775,11 @@ class TokenUsageMetric(SQLModel, table=True):
cache_creation_tokens: int # Anthropic cache creation
cache_read_tokens: int # Anthropic cache read
reasoning_tokens: int # OpenAI o-series reasoning
+ # Cost fields (USD)
+ input_cost: float # Cost for input tokens
+ output_cost: float # Cost for output tokens
+ cache_cost: float # Cost for cache tokens
+ total_cost: float # Total cost
```
**SessionTokenState** - Cumulative state per session:
@@ -2683,6 +2790,10 @@ class SessionTokenState(SQLModel, table=True):
custom_threshold: int # Per-session threshold override
compaction_count: int # Number of compactions
last_compaction_at: datetime # Last compaction timestamp
+ # Cumulative cost fields (USD)
+ cumulative_input_cost: float
+ cumulative_output_cost: float
+ cumulative_total_cost: float
```
**CompactionEvent** - Compaction history:
@@ -2714,7 +2825,7 @@ result = await svc.track(
model="claude-3-5-sonnet",
usage={"input_tokens": 5000, "output_tokens": 1000, "total_tokens": 6000}
)
-# result: {"total": 6000, "threshold": 100000, "needs_compaction": False}
+# result: {"total": 6000, "total_cost": 0.021, "threshold": 100000, "needs_compaction": False}
# Record compaction event after native API handles it
await svc.record(
@@ -2741,6 +2852,41 @@ await svc.configure("user-123", threshold=50000, enabled=True)
|---------|-------------|
| `get_compaction_stats` | Get token statistics for a session |
| `configure_compaction` | Update threshold/enabled settings for a session |
+| `get_provider_usage_summary` | Get aggregated usage and cost by provider for Credentials Modal |
+
+### PricingService
+
+Calculates cost based on official pricing (USD per 1M tokens):
+
+```python
+from services.pricing import get_pricing_service
+
+pricing = get_pricing_service()
+
+# Calculate cost for token usage
+cost = pricing.calculate_cost(
+ provider="anthropic",
+ model="claude-3-5-sonnet",
+ input_tokens=5000,
+ output_tokens=1000,
+ cache_read_tokens=500
+)
+# cost: {"input_cost": 0.015, "output_cost": 0.015, "cache_cost": 0.00015, "total_cost": 0.03015}
+
+# Get pricing for a model (supports partial matching)
+pricing_info = pricing.get_pricing("anthropic", "claude-3-5-sonnet-20241022")
+# pricing_info: ModelPricing(input_per_mtok=3.0, output_per_mtok=15.0, cache_read_per_mtok=0.30)
+```
+
+**Supported Providers & Pricing** (February 2026):
+| Provider | Example Models | Input $/MTok | Output $/MTok |
+|----------|---------------|--------------|---------------|
+| OpenAI | gpt-5, gpt-4o, o3 | 1.25-15.00 | 10.00-60.00 |
+| Anthropic | claude-opus-4.6, claude-sonnet-4 | 3.00-5.00 | 15.00-25.00 |
+| Gemini | gemini-2.5-pro, gemini-2.0-flash | 0.10-1.25 | 0.40-10.00 |
+| Groq | llama-4-scout, qwen3-32b | 0.05-0.59 | 0.08-0.79 |
+| Cerebras | llama-3.1-70b | 0.10-0.60 | 0.10-0.60 |
+| OpenRouter | Pass-through | Varies | Varies |
### Configuration
@@ -4087,7 +4233,7 @@ This function:
- **Performance**: Fast HMR updates and clean TypeScript compilation
- **AI Architecture**: 5-layer system with factory pattern and secure credential management
- **Android Architecture**: Factory-based node creation with ADB integration for device automation
-- **WebSocket-First Architecture**: 86 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations
+- **WebSocket-First Architecture**: 87 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations
- **WebSocket Hooks**: Dedicated React hooks (useWhatsApp, useExecution, useApiKeys, useAndroidOperations, useParameterPanel) for clean component integration
- **WebSocket Support**: Persistent remote Android device connections via WebSocket proxy with background tasks
- Connection stays alive across multiple API requests until switched to local ADB
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index d9e9ed93..149b41e7 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -18,6 +18,7 @@ import ModelNode from './components/ModelNode';
import SquareNode from './components/SquareNode';
import TriggerNode from './components/TriggerNode';
import ToolkitNode from './components/ToolkitNode';
+import TeamMonitorNode from './components/TeamMonitorNode';
import ConditionalEdge from './components/ConditionalEdge';
import NodeContextMenu from './components/ui/NodeContextMenu';
import { nodeDefinitions } from './nodeDefinitions';
@@ -65,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', 'chatTrigger', 'taskTrigger'];
+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'chatTrigger', 'taskTrigger'];
// Pre-register specialized agent nodes explicitly to ensure they're always available
// This handles cases where nodeDefinitions iteration order might miss them
@@ -90,6 +91,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (type === 'whatsappSend' || type === 'whatsappDb') {
// WhatsApp action nodes use SquareNode (whatsappReceive is a trigger)
types[type] = SquareNode;
+ } else if (type === 'twitterSend' || type === 'twitterSearch' || type === 'twitterUser') {
+ // Twitter action nodes use SquareNode (twitterReceive is a trigger)
+ types[type] = SquareNode;
} else if (ANDROID_SERVICE_NODE_TYPES.includes(type)) {
// Android service nodes use SquareNode component
types[type] = SquareNode;
@@ -103,9 +107,12 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
// Code execution nodes use SquareNode component
types[type] = SquareNode;
} else if (UTILITY_NODE_TYPES.includes(type)) {
- // Utility nodes (HTTP, Webhooks) use SquareNode component
- // Note: webhookTrigger is already handled as trigger above
+ // Utility nodes (HTTP, Webhooks, Team Monitor) use SquareNode component
+ // Note: webhookTrigger and chatTrigger are already handled as triggers above
types[type] = SquareNode;
+ } else if (type === 'teamMonitor') {
+ // Team Monitor node uses custom component with live display
+ types[type] = TeamMonitorNode;
} else if (SPECIALIZED_AGENT_TYPES.includes(type)) {
// Specialized agent nodes use AIAgentNode (rectangular card with bottom handles)
types[type] = AIAgentNode;
@@ -651,8 +658,8 @@ const DashboardContent: React.FC = () => {
if (!currentWorkflow) return;
// Check if there's at least one trigger node (workflow entry points)
- // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger, chatTrigger, taskTrigger
- const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, twitterReceive, workflowTrigger, chatTrigger, taskTrigger
+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));
if (!hasTriggerNode) {
alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, Chat Trigger, etc.) to begin deployment.');
diff --git a/client/src/ParameterPanel.tsx b/client/src/ParameterPanel.tsx
index d9f91e5c..e1875875 100644
--- a/client/src/ParameterPanel.tsx
+++ b/client/src/ParameterPanel.tsx
@@ -116,9 +116,10 @@ const ParameterPanel: React.FC = () => {
const canExecute = selectedNode && nodeDefinition &&
ExecutionService.isNodeTypeSupported(nodeDefinition.name);
- // Check if this is a Start node or Skill node (only show middle section)
+ // Check if this is a Start node, Skill node, or Monitor node (only show middle section)
const isStartNode = nodeDefinition?.name === 'start';
const isSkillNode = nodeDefinition?.name && SKILL_NODE_TYPES.includes(nodeDefinition.name);
+ const isMonitorNode = nodeDefinition?.name === 'teamMonitor';
if (!selectedNode || !nodeDefinition) {
return null;
@@ -190,8 +191,8 @@ const ParameterPanel: React.FC = () => {
{/* Buttons: Run, Save, Cancel */}
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
- {/* Run Button */}
- {canExecute && (
+ {/* Run Button - hide for monitor nodes since they show live data */}
+ {canExecute && !isMonitorNode && (
<button
style={actionButtonStyle(theme.dracula.green, isExecuting)}
onClick={handleRun}
@@ -292,8 +293,8 @@ const ParameterPanel: React.FC = () => {
onParameterChange={handleParameterChange}
executionResults={executionResults}
onClearResults={handleClearResults}
- showInputSection={!isStartNode && !isSkillNode}
- showOutputSection={!isStartNode && !isSkillNode}
+ showInputSection={!isStartNode && !isSkillNode && !isMonitorNode}
+ showOutputSection={!isStartNode && !isSkillNode && !isMonitorNode}
isLoadingParameters={isLoading}
/>
</Modal>
diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsx
index 5c347498..501760ba 100644
--- a/client/src/components/AIAgentNode.tsx
+++ b/client/src/components/AIAgentNode.tsx
@@ -70,7 +70,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
chatAgent: {
@@ -87,7 +87,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
socialReceive: {
@@ -135,7 +135,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
coding_agent: {
@@ -152,7 +152,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
web_agent: {
@@ -169,7 +169,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
task_agent: {
@@ -186,7 +186,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
social_agent: {
@@ -203,7 +203,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
travel_agent: {
@@ -220,7 +220,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
tool_agent: {
@@ -237,7 +237,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
productivity_agent: {
@@ -254,7 +254,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
payments_agent: {
@@ -271,7 +271,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
consumer_agent: {
@@ -288,7 +288,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
autonomous_agent: {
@@ -305,7 +305,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
height: 200,
},
orchestrator_agent: {
@@ -314,15 +314,34 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
subtitle: 'Agent Coordination',
themeColorKey: 'cyan',
bottomHandles: [
- { id: 'input-skill', label: 'Skill', position: '25%' },
- { id: 'input-tools', label: 'Tool', position: '75%' },
+ { id: 'input-skill', label: 'Skill', position: '20%' },
+ { id: 'input-tools', label: 'Tool', position: '50%' },
+ { id: 'input-teammates', label: 'Team', position: '80%' },
],
leftHandles: [
{ id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
+ width: 300,
+ height: 200,
+ },
+ ai_employee: {
+ icon: <span style={{ fontSize: '28px' }}>👥</span>,
+ title: 'AI Employee',
+ subtitle: 'Team Orchestration',
+ themeColorKey: 'purple',
+ bottomHandles: [
+ { id: 'input-skill', label: 'Skill', position: '20%' },
+ { id: 'input-tools', label: 'Tool', position: '50%' },
+ { id: 'input-teammates', label: 'Team', position: '80%' },
+ ],
+ leftHandles: [
+ { id: 'input-memory', label: 'Memory', position: '65%' },
+ { id: 'input-task', label: 'Task', position: '85%' },
+ ],
+ topOutputHandle: { id: 'output-top', label: 'Output' },
+ width: 300,
height: 200,
},
};
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index 041cdd13..a4457c65 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -5,17 +5,20 @@
*/
import React, { useState, useEffect, useCallback } from 'react';
-import { Button, Tag, Alert, Descriptions, Space, InputNumber, Switch, Input } from 'antd';
+import { Button, Tag, Alert, Descriptions, Space, InputNumber, Switch, Input, Collapse, Statistic, Spin } from 'antd';
import {
CheckCircleOutlined,
SafetyOutlined,
+ ReloadOutlined,
+ DollarOutlined,
+ TwitterOutlined,
} from '@ant-design/icons';
import Modal from './ui/Modal';
import QRCodeDisplay from './ui/QRCodeDisplay';
import ApiKeyInput from './ui/ApiKeyInput';
-import { useApiKeys, ProviderDefaults } from '../hooks/useApiKeys';
+import { useApiKeys, ProviderDefaults, ProviderUsageSummary } from '../hooks/useApiKeys';
import { useAppTheme } from '../hooks/useAppTheme';
-import { useWhatsAppStatus, useAndroidStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
+import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
import { useWhatsApp } from '../hooks/useWhatsApp';
import {
OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,
@@ -44,6 +47,10 @@ const WhatsAppIcon = () => (
</svg>
);
+const XIcon = () => (
+ <TwitterOutlined style={{ fontSize: 20, color: '#000000' }} />
+);
+
// ============================================================================
// TYPES & DATA
// ============================================================================
@@ -57,7 +64,7 @@ interface CredentialItem {
Icon?: React.FC<{ size?: number }>;
CustomIcon?: React.FC;
isSpecial?: boolean;
- panelType?: 'whatsapp' | 'android';
+ panelType?: 'whatsapp' | 'android' | 'twitter';
}
interface Category {
@@ -84,6 +91,7 @@ const CATEGORIES: Category[] = [
label: 'Social Media',
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' },
],
},
{
@@ -114,9 +122,10 @@ interface Props {
const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const theme = useAppTheme();
- const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, getProviderDefaults, saveProviderDefaults, isConnected } = useApiKeys();
+ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, getProviderDefaults, saveProviderDefaults, getProviderUsageSummary, isConnected } = useApiKeys();
const whatsappStatus = useWhatsAppStatus();
const androidStatus = useAndroidStatus();
+ const twitterStatus = useTwitterStatus();
// Tag style helper - consistent theming for status tags
@@ -143,6 +152,11 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const [defaultsLoading, setDefaultsLoading] = useState<Record<string, boolean>>({});
const [defaultsDirty, setDefaultsDirty] = useState<Record<string, boolean>>({});
+ // Usage & Costs state
+ const [usageSummary, setUsageSummary] = useState<ProviderUsageSummary[]>([]);
+ const [usageLoading, setUsageLoading] = useState(false);
+ const [usageExpanded, setUsageExpanded] = useState(false);
+
// Load stored keys and proxy URLs
const loadKeys = useCallback(async () => {
const allItems = CATEGORIES.flatMap(c => c.items);
@@ -218,6 +232,27 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
setDefaultsLoading(l => ({ ...l, [provider]: false }));
};
+ // Load usage summary when expanded
+ const loadUsageSummary = useCallback(async () => {
+ if (!isConnected) return;
+ setUsageLoading(true);
+ try {
+ const summary = await getProviderUsageSummary();
+ setUsageSummary(summary);
+ } catch (error) {
+ console.warn('Error loading usage summary:', error);
+ } finally {
+ setUsageLoading(false);
+ }
+ }, [getProviderUsageSummary, isConnected]);
+
+ // Load usage when section is expanded
+ useEffect(() => {
+ if (usageExpanded && isConnected) {
+ loadUsageSummary();
+ }
+ }, [usageExpanded, isConnected, loadUsageSummary]);
+
const handleValidate = async (id: string) => {
const key = keys[id];
if (!key?.trim()) return;
@@ -251,6 +286,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
if (item.panelType === 'android') {
return { connected: androidStatus.paired, label: androidStatus.paired ? 'Paired' : 'Not Paired' };
}
+ if (item.panelType === 'twitter') {
+ return { connected: twitterStatus.connected, label: twitterStatus.connected ? `@${twitterStatus.username}` : 'Not Connected' };
+ }
return null;
};
@@ -374,6 +412,13 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const [whatsappLoading, setWhatsappLoading] = useState<string | null>(null);
const [whatsappError, setWhatsappError] = useState<string | null>(null);
+ // Twitter state
+ const [twitterClientId, setTwitterClientId] = useState('');
+ const [twitterClientSecret, setTwitterClientSecret] = useState('');
+ const [twitterCredentialsStored, setTwitterCredentialsStored] = useState<boolean | null>(null);
+ const [twitterLoading, setTwitterLoading] = useState<string | null>(null);
+ const [twitterError, setTwitterError] = useState<string | null>(null);
+
// Rate limit state
const [rateLimitConfig, setRateLimitConfig] = useState<RateLimitConfig | null>(null);
const [rateLimitStats, setRateLimitStats] = useState<RateLimitStats | null>(null);
@@ -394,6 +439,85 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [visible, hasStoredKey, getStoredApiKey]);
+ // Load Twitter credentials on mount
+ useEffect(() => {
+ if (visible) {
+ // Check if client_id is stored
+ hasStoredKey('twitter_client_id').then(async (has) => {
+ setTwitterCredentialsStored(has);
+ if (has) {
+ const clientId = await getStoredApiKey('twitter_client_id');
+ const clientSecret = await getStoredApiKey('twitter_client_secret');
+ if (clientId) setTwitterClientId(clientId);
+ if (clientSecret) setTwitterClientSecret(clientSecret);
+ }
+ });
+ }
+ }, [visible, hasStoredKey, getStoredApiKey]);
+
+ // Twitter handlers
+ const handleTwitterSaveCredentials = async () => {
+ if (!twitterClientId.trim()) {
+ setTwitterError('Client ID is required');
+ return;
+ }
+ setTwitterLoading('save');
+ setTwitterError(null);
+ try {
+ await saveApiKey('twitter_client_id', twitterClientId.trim());
+ if (twitterClientSecret.trim()) {
+ await saveApiKey('twitter_client_secret', twitterClientSecret.trim());
+ }
+ setTwitterCredentialsStored(true);
+ } catch (err: any) {
+ setTwitterError(err.message || 'Failed to save credentials');
+ } finally {
+ setTwitterLoading(null);
+ }
+ };
+
+ const handleTwitterLogin = async () => {
+ setTwitterLoading('login');
+ setTwitterError(null);
+ try {
+ const response = await sendRequest('twitter_oauth_login', {});
+ if (!response.success) {
+ setTwitterError(response.error || 'Failed to start OAuth');
+ }
+ } catch (err: any) {
+ setTwitterError(err.message || 'Failed to start OAuth');
+ } finally {
+ setTwitterLoading(null);
+ }
+ };
+
+ const handleTwitterLogout = async () => {
+ setTwitterLoading('logout');
+ setTwitterError(null);
+ try {
+ const response = await sendRequest('twitter_logout', {});
+ if (!response.success) {
+ setTwitterError(response.error || 'Failed to disconnect');
+ }
+ } catch (err: any) {
+ setTwitterError(err.message || 'Failed to disconnect');
+ } finally {
+ setTwitterLoading(null);
+ }
+ };
+
+ const handleTwitterRefreshStatus = async () => {
+ setTwitterLoading('refresh');
+ setTwitterError(null);
+ try {
+ await sendRequest('twitter_oauth_status', {});
+ } catch (err: any) {
+ setTwitterError(err.message || 'Failed to refresh status');
+ } finally {
+ setTwitterLoading(null);
+ }
+ };
+
// Android handlers
const handleAndroidSaveKey = async () => {
if (!androidApiKey.trim()) return;
@@ -1077,6 +1201,202 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
);
}
+ // Twitter panel
+ if (selectedItem.panelType === 'twitter') {
+ return (
+ <div style={{ padding: theme.spacing.xl, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
+ <Descriptions
+ title={<Space><XIcon /> Twitter/X</Space>}
+ bordered
+ column={1}
+ size="small"
+ style={{
+ marginBottom: theme.spacing.xl,
+ background: theme.colors.backgroundAlt,
+ 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(twitterStatus.connected ? 'success' : 'error')}>
+ {twitterStatus.connected ? 'Connected' : 'Not Connected'}
+ </Tag>
+ </Descriptions.Item>
+ <Descriptions.Item label="API Credentials">
+ <Tag style={getTagStyle(twitterCredentialsStored ? 'success' : 'error')}>
+ {twitterCredentialsStored === null ? 'Checking...' : twitterCredentialsStored ? 'Configured' : 'Not configured'}
+ </Tag>
+ </Descriptions.Item>
+ {twitterStatus.connected && twitterStatus.username && (
+ <Descriptions.Item label="Account">
+ <Space>
+ {twitterStatus.profile_image_url && (
+ <img
+ src={twitterStatus.profile_image_url}
+ alt={twitterStatus.username}
+ style={{ width: 24, height: 24, borderRadius: '50%' }}
+ />
+ )}
+ <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.sm }}>@{twitterStatus.username}</span>
+ {twitterStatus.name && <span style={{ color: theme.colors.textSecondary }}>({twitterStatus.name})</span>}
+ </Space>
+ </Descriptions.Item>
+ )}
+ </Descriptions>
+
+ {/* API Credentials Input - Only show if not connected */}
+ {!twitterStatus.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,
+ }}>
+ Twitter API Credentials
+ </label>
+ <div style={{ marginBottom: theme.spacing.md }}>
+ <Input
+ value={twitterClientId}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTwitterClientId(e.target.value)}
+ placeholder="Client ID (from X Developer Portal)"
+ style={{
+ marginBottom: theme.spacing.sm,
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ color: theme.colors.text,
+ fontFamily: 'monospace',
+ fontSize: theme.fontSize.sm,
+ }}
+ />
+ <Input.Password
+ value={twitterClientSecret}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTwitterClientSecret(e.target.value)}
+ placeholder="Client Secret (optional for PKCE)"
+ style={{
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ color: theme.colors.text,
+ fontFamily: 'monospace',
+ fontSize: theme.fontSize.sm,
+ }}
+ />
+ </div>
+ <Button
+ onClick={handleTwitterSaveCredentials}
+ loading={twitterLoading === 'save'}
+ disabled={!twitterClientId.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 the X Developer Portal. Create an app with OAuth 2.0 enabled.
+ <br />
+ Callback URL: <code style={{ fontSize: theme.fontSize.xs, color: theme.dracula.cyan }}>http://localhost:3010/api/twitter/callback</code>
+ </div>
+ </div>
+ )}
+
+ {twitterError && (
+ <Alert type="error" message={twitterError} showIcon style={{ marginBottom: theme.spacing.lg }} />
+ )}
+
+ {/* 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,
+ }}>
+ {twitterStatus.connected ? (
+ <>Your Twitter account is connected. You can now use Twitter nodes in your workflows.</>
+ ) : twitterCredentialsStored ? (
+ <>Click Login with Twitter to authorize. A browser window will open for authentication.</>
+ ) : (
+ <>Enter your Twitter 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}`,
+ }}>
+ {!twitterStatus.connected ? (
+ <Button
+ onClick={handleTwitterLogin}
+ loading={twitterLoading === 'login'}
+ disabled={!twitterCredentialsStored}
+ style={{
+ backgroundColor: `${theme.dracula.green}25`,
+ borderColor: `${theme.dracula.green}60`,
+ color: theme.dracula.green,
+ }}
+ >
+ Login with Twitter
+ </Button>
+ ) : (
+ <Button
+ onClick={handleTwitterLogout}
+ loading={twitterLoading === 'logout'}
+ style={{
+ backgroundColor: `${theme.dracula.pink}25`,
+ borderColor: `${theme.dracula.pink}60`,
+ color: theme.dracula.pink,
+ }}
+ >
+ Disconnect
+ </Button>
+ )}
+ <Button
+ onClick={handleTwitterRefreshStatus}
+ loading={twitterLoading === '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;
@@ -1369,6 +1689,131 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
</div>
)}
+ {/* Usage & Costs Section - Only for AI providers */}
+ {CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === item.id) && (
+ <div style={{ marginBottom: theme.spacing.xl }}>
+ <Collapse
+ ghost
+ onChange={(keys) => setUsageExpanded(keys.includes('usage'))}
+ items={[{
+ key: 'usage',
+ label: (
+ <span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>
+ <DollarOutlined style={{ marginRight: theme.spacing.sm }} />
+ Usage & Costs
+ </span>
+ ),
+ children: usageLoading ? (
+ <div style={{ textAlign: 'center', padding: theme.spacing.lg }}>
+ <Spin size="small" />
+ </div>
+ ) : (() => {
+ const providerData = usageSummary.find(p => p.provider === item.id);
+ if (!providerData || providerData.execution_count === 0) {
+ return (
+ <Alert
+ message={`No usage data yet for ${item.name}`}
+ type="info"
+ showIcon
+ style={{ marginBottom: theme.spacing.md }}
+ />
+ );
+ }
+ return (
+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>
+ {/* Summary Stats */}
+ <div style={{ display: 'flex', gap: theme.spacing.lg, flexWrap: 'wrap' }}>
+ <Statistic
+ title="Total Tokens"
+ value={providerData.total_tokens}
+ valueStyle={{ color: theme.dracula.cyan, fontSize: theme.fontSize.lg }}
+ />
+ <Statistic
+ title="Total Cost"
+ value={providerData.total_cost}
+ precision={4}
+ prefix="$"
+ valueStyle={{ color: theme.dracula.green, fontSize: theme.fontSize.lg }}
+ />
+ <Statistic
+ title="Executions"
+ value={providerData.execution_count}
+ valueStyle={{ color: theme.dracula.purple, fontSize: theme.fontSize.lg }}
+ />
+ </div>
+
+ {/* Token Breakdown */}
+ <Descriptions size="small" column={2} bordered>
+ <Descriptions.Item label="Input Tokens">
+ {providerData.total_input_tokens.toLocaleString()}
+ <span style={{ color: theme.dracula.green, marginLeft: 8 }}>
+ (${providerData.total_input_cost.toFixed(4)})
+ </span>
+ </Descriptions.Item>
+ <Descriptions.Item label="Output Tokens">
+ {providerData.total_output_tokens.toLocaleString()}
+ <span style={{ color: theme.dracula.green, marginLeft: 8 }}>
+ (${providerData.total_output_cost.toFixed(4)})
+ </span>
+ </Descriptions.Item>
+ {providerData.total_cache_cost > 0 && (
+ <Descriptions.Item label="Cache Cost" span={2}>
+ <span style={{ color: theme.dracula.green }}>
+ ${providerData.total_cache_cost.toFixed(4)}
+ </span>
+ </Descriptions.Item>
+ )}
+ </Descriptions>
+
+ {/* Model Breakdown */}
+ {providerData.models.length > 1 && (
+ <div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted, marginBottom: theme.spacing.sm }}>
+ By Model
+ </div>
+ <div style={{
+ maxHeight: 120,
+ overflow: 'auto',
+ backgroundColor: theme.colors.backgroundAlt,
+ borderRadius: theme.borderRadius.sm,
+ padding: theme.spacing.sm,
+ }}>
+ {providerData.models.map((model, idx) => (
+ <div key={idx} style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ padding: `${theme.spacing.xs} 0`,
+ fontSize: theme.fontSize.sm,
+ borderBottom: idx < providerData.models.length - 1 ? `1px solid ${theme.colors.border}` : 'none',
+ }}>
+ <span style={{ fontFamily: 'monospace', fontSize: theme.fontSize.xs, color: theme.colors.text }}>
+ {model.model}
+ </span>
+ <span style={{ color: theme.dracula.green }}>
+ ${model.total_cost.toFixed(4)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <Button
+ size="small"
+ icon={<ReloadOutlined />}
+ onClick={loadUsageSummary}
+ loading={usageLoading}
+ >
+ Refresh
+ </Button>
+ </Space>
+ );
+ })()
+ }]}
+ />
+ </div>
+ )}
+
{/* Models list */}
{models[item.id]?.length > 0 && (
<div style={{ marginBottom: theme.spacing.xl }}>
diff --git a/client/src/components/TeamMonitorNode.tsx b/client/src/components/TeamMonitorNode.tsx
new file mode 100644
index 00000000..4ec56d5d
--- /dev/null
+++ b/client/src/components/TeamMonitorNode.tsx
@@ -0,0 +1,282 @@
+import React, { useState, useEffect, useCallback, useMemo } from 'react';
+import { Handle, Position, NodeProps, useEdges, useNodes } from 'reactflow';
+import { NodeData } from '../types/NodeTypes';
+import { useAppStore } from '../store/useAppStore';
+import { nodeDefinitions } from '../nodeDefinitions';
+import { useAppTheme } from '../hooks/useAppTheme';
+import { useWebSocket } from '../contexts/WebSocketContext';
+
+// AI Employee node types that can have teams
+const TEAM_LEAD_TYPES = ['ai_employee', 'orchestrator_agent'];
+
+interface TeamTask {
+ id: string;
+ title: string;
+ status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped';
+ assigned_to?: string;
+}
+
+interface TeamMember {
+ agent_node_id: string;
+ agent_type: string;
+ status: string;
+}
+
+interface TeamStatus {
+ team_id: string;
+ members: TeamMember[];
+ tasks: {
+ total: number;
+ completed: number;
+ active: number;
+ pending: number;
+ failed: number;
+ };
+ active_tasks: TeamTask[];
+}
+
+const TeamMonitorNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
+ const theme = useAppTheme();
+ const { setSelectedNode } = useAppStore();
+ const { sendMessage, subscribeToMessage } = useWebSocket();
+ const edges = useEdges();
+ const nodes = useNodes();
+
+ const [teamStatus, setTeamStatus] = useState<TeamStatus | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];
+ const nodeColor = definition?.defaults?.color || '#8b5cf6';
+
+ // Find connected AI Employee/Orchestrator node to get workflow context
+ const connectedTeamLead = useMemo(() => {
+ // Find edges where this node is the target (input)
+ const incomingEdges = edges.filter(e => e.target === id);
+ for (const edge of incomingEdges) {
+ const sourceNode = nodes.find(n => n.id === edge.source);
+ if (sourceNode && TEAM_LEAD_TYPES.includes(sourceNode.type || '')) {
+ return sourceNode;
+ }
+ }
+ return null;
+ }, [edges, nodes, id]);
+
+ // Fetch team status
+ const fetchTeamStatus = useCallback(async () => {
+ // Use explicit teamId from data, or get from connected node's workflow context
+ const teamId = data?.teamId;
+ if (!teamId && !connectedTeamLead) return;
+
+ setIsLoading(true);
+ try {
+ // Request team status - backend will find the active team for the workflow
+ const response = await sendMessage('get_team_status', {
+ team_id: teamId,
+ team_lead_node_id: connectedTeamLead?.id
+ });
+ if (response?.status) {
+ setTeamStatus({
+ team_id: response.status.team_id || teamId || '',
+ members: response.status.members || [],
+ tasks: {
+ total: response.status.task_count || 0,
+ completed: response.status.completed_count || 0,
+ active: response.status.active_count || 0,
+ pending: response.status.pending_count || 0,
+ failed: response.status.failed_count || 0,
+ },
+ active_tasks: response.status.active_tasks || [],
+ });
+ }
+ } catch (error) {
+ console.error('Failed to fetch team status:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [data?.teamId, connectedTeamLead, sendMessage]);
+
+ // Subscribe to team events for real-time updates
+ useEffect(() => {
+ const unsubscribe = subscribeToMessage('team_event', (message: any) => {
+ // Refresh on any team event if we have a connected team lead
+ if (message.data?.team_id === data?.teamId ||
+ message.data?.team_id === teamStatus?.team_id ||
+ connectedTeamLead) {
+ fetchTeamStatus();
+ }
+ });
+ return () => unsubscribe?.();
+ }, [data?.teamId, teamStatus?.team_id, connectedTeamLead, subscribeToMessage, fetchTeamStatus]);
+
+ // Auto-refresh when connected to a team lead
+ useEffect(() => {
+ const interval = data?.refreshInterval || 2000;
+ if (interval > 0 && (data?.teamId || connectedTeamLead)) {
+ fetchTeamStatus();
+ const timer = setInterval(fetchTeamStatus, interval);
+ return () => clearInterval(timer);
+ }
+ }, [data?.refreshInterval, data?.teamId, connectedTeamLead, fetchTeamStatus]);
+
+ const handleClick = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });
+ };
+
+ const getStatusColor = (status: string) => {
+ switch (status) {
+ case 'completed': return theme.dracula.green;
+ case 'in_progress': return theme.dracula.cyan;
+ case 'failed': return theme.dracula.red;
+ case 'pending': return theme.dracula.orange;
+ default: return theme.colors.textSecondary;
+ }
+ };
+
+ return (
+ <div
+ onClick={handleClick}
+ style={{
+ width: 200,
+ minHeight: 120,
+ borderRadius: 8,
+ background: theme.isDarkMode
+ ? `linear-gradient(135deg, ${nodeColor}15 0%, ${theme.colors.background} 100%)`
+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}08 100%)`,
+ border: `2px solid ${selected ? theme.colors.focus : nodeColor + '60'}`,
+ fontFamily: 'system-ui, -apple-system, sans-serif',
+ fontSize: 10,
+ overflow: 'hidden',
+ }}
+ >
+ {/* Header */}
+ <div style={{
+ padding: '6px 8px',
+ borderBottom: `1px solid ${theme.colors.border}`,
+ background: `${nodeColor}20`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: 6,
+ }}>
+ <span style={{ fontSize: 14 }}>📊</span>
+ <span style={{ fontWeight: 600, color: theme.colors.text, fontSize: 11 }}>
+ {data?.label || 'Team Monitor'}
+ </span>
+ </div>
+
+ {/* Stats Grid */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: 2,
+ padding: '6px 4px',
+ borderBottom: `1px solid ${theme.colors.border}`,
+ }}>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ fontSize: 12, fontWeight: 'bold', color: theme.dracula.purple }}>
+ {teamStatus?.members?.length || 0}
+ </div>
+ <div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Team</div>
+ </div>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ fontSize: 12, fontWeight: 'bold', color: theme.dracula.cyan }}>
+ {teamStatus?.tasks?.total || 0}
+ </div>
+ <div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Tasks</div>
+ </div>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ fontSize: 12, fontWeight: 'bold', color: theme.dracula.green }}>
+ {teamStatus?.tasks?.completed || 0}
+ </div>
+ <div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Done</div>
+ </div>
+ <div style={{ textAlign: 'center' }}>
+ <div style={{ fontSize: 12, fontWeight: 'bold', color: theme.dracula.orange }}>
+ {teamStatus?.tasks?.active || 0}
+ </div>
+ <div style={{ fontSize: 8, color: theme.colors.textSecondary }}>Active</div>
+ </div>
+ </div>
+
+ {/* Active Tasks */}
+ <div style={{ padding: '4px 6px', maxHeight: 80, overflow: 'auto' }}>
+ {!data?.teamId && !connectedTeamLead ? (
+ <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 8, fontSize: 9 }}>
+ Connect to AI Employee
+ </div>
+ ) : isLoading && !teamStatus ? (
+ <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 8, fontSize: 9 }}>
+ Loading...
+ </div>
+ ) : teamStatus?.active_tasks && teamStatus.active_tasks.length > 0 ? (
+ teamStatus.active_tasks.slice(0, 3).map((task) => (
+ <div key={task.id} style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 4,
+ padding: '2px 0',
+ fontSize: 9,
+ }}>
+ <span style={{
+ width: 6,
+ height: 6,
+ borderRadius: '50%',
+ backgroundColor: getStatusColor(task.status),
+ flexShrink: 0,
+ }} />
+ <span style={{
+ color: theme.colors.text,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ flex: 1,
+ }}>
+ {task.title}
+ </span>
+ </div>
+ ))
+ ) : (
+ <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 4, fontSize: 9 }}>
+ No active tasks
+ </div>
+ )}
+ </div>
+
+ {/* Input Handle */}
+ <Handle
+ id="input-team"
+ type="target"
+ position={Position.Left}
+ isConnectable={isConnectable}
+ style={{
+ left: -6,
+ top: '50%',
+ width: 10,
+ height: 10,
+ backgroundColor: theme.isDarkMode ? theme.colors.background : '#ffffff',
+ border: `2px solid ${nodeColor}`,
+ borderRadius: '50%',
+ }}
+ />
+
+ {/* Output Handle */}
+ <Handle
+ id="output-main"
+ type="source"
+ position={Position.Right}
+ isConnectable={isConnectable}
+ style={{
+ right: -6,
+ top: '50%',
+ width: 10,
+ height: 10,
+ backgroundColor: nodeColor,
+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ borderRadius: '50%',
+ }}
+ />
+ </div>
+ );
+};
+
+export default TeamMonitorNode;
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index 65f2fb7c..c793c5a0 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -252,6 +252,31 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
body: 'string',
json: 'object'
},
+ // Twitter node output schemas
+ twitter: {
+ tweet_id: 'string',
+ text: 'string',
+ author_id: 'string',
+ created_at: 'string',
+ action: 'string'
+ },
+ twitterSearch: {
+ tweets: [{
+ id: 'string',
+ text: 'string',
+ author_id: 'string',
+ created_at: 'string'
+ }],
+ count: 'number',
+ query: 'string'
+ },
+ twitterUser: {
+ id: 'string',
+ username: 'string',
+ name: 'string',
+ profile_image_url: 'string',
+ verified: 'boolean'
+ },
httpRequest: {
status: 'number',
data: 'any',
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 9590ad3e..33a61273 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -90,6 +90,15 @@ export interface WhatsAppStatus {
timestamp?: number;
}
+export interface TwitterStatus {
+ connected: boolean;
+ username: string | null;
+ user_id: string | null;
+ name?: string;
+ profile_image_url?: string;
+ verified?: boolean;
+}
+
// WhatsApp Rate Limit types (from Go RPC schema)
export interface RateLimitConfig {
enabled: boolean;
@@ -203,6 +212,7 @@ interface WebSocketContextValue {
androidStatus: AndroidStatus;
setAndroidStatus: React.Dispatch<React.SetStateAction<AndroidStatus>>;
whatsappStatus: WhatsAppStatus;
+ twitterStatus: TwitterStatus;
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
@@ -322,6 +332,12 @@ const defaultWhatsAppStatus: WhatsAppStatus = {
pairing: false
};
+const defaultTwitterStatus: TwitterStatus = {
+ connected: false,
+ username: null,
+ user_id: null,
+};
+
const WebSocketContext = createContext<WebSocketContextValue | null>(null);
// WebSocket URL (convert http to ws)
@@ -355,6 +371,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [reconnecting, setReconnecting] = useState(false);
const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);
const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);
+ const [twitterStatus, setTwitterStatus] = useState<TwitterStatus>(defaultTwitterStatus);
const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
@@ -469,6 +486,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
if (data) {
if (data.android) setAndroidStatus(data.android);
if (data.whatsapp) setWhatsappStatus(data.whatsapp);
+ if (data.twitter) setTwitterStatus(data.twitter);
if (data.api_keys) setApiKeyStatuses(data.api_keys);
// Node statuses from initial_status - group by workflow_id (n8n pattern)
if (data.nodes) {
@@ -523,6 +541,19 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
setWhatsappStatus(data || defaultWhatsAppStatus);
break;
+ case 'twitter_oauth_complete':
+ // Handle Twitter OAuth completion broadcast from backend
+ if (data?.success) {
+ setTwitterStatus({
+ connected: true,
+ username: data.username || null,
+ user_id: data.user_id || 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) {
@@ -1959,6 +1990,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
androidStatus,
setAndroidStatus,
whatsappStatus,
+ twitterStatus,
whatsappMessages,
lastWhatsAppMessage,
apiKeyStatuses,
@@ -2089,6 +2121,12 @@ export const useWhatsAppStatus = (): WhatsAppStatus => {
return whatsappStatus;
};
+// Hook specifically for Twitter status
+export const useTwitterStatus = (): TwitterStatus => {
+ const { twitterStatus } = useWebSocket();
+ return twitterStatus;
+};
+
// Hook specifically for deployment status
export const useDeploymentStatus = (): DeploymentStatus => {
const { deploymentStatus } = useWebSocket();
diff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.ts
index 979cf16b..c6867c73 100644
--- a/client/src/hooks/useApiKeys.ts
+++ b/client/src/hooks/useApiKeys.ts
@@ -23,6 +23,31 @@ export interface ProviderDefaults {
reasoning_format: 'parsed' | 'hidden';
}
+export interface ModelUsageSummary {
+ model: string;
+ input_tokens: number;
+ output_tokens: number;
+ total_tokens: number;
+ input_cost: number;
+ output_cost: number;
+ cache_cost: number;
+ total_cost: number;
+ execution_count: number;
+}
+
+export interface ProviderUsageSummary {
+ provider: string;
+ total_input_tokens: number;
+ total_output_tokens: number;
+ total_tokens: number;
+ total_input_cost: number;
+ total_output_cost: number;
+ total_cache_cost: number;
+ total_cost: number;
+ execution_count: number;
+ models: ModelUsageSummary[];
+}
+
export interface UseApiKeysResult {
// Validate and store API key
validateApiKey: (provider: string, apiKey: string) => Promise<ApiKeyValidationResult>;
@@ -52,6 +77,9 @@ export interface UseApiKeysResult {
getProviderDefaults: (provider: string) => Promise<ProviderDefaults>;
saveProviderDefaults: (provider: string, defaults: ProviderDefaults) => Promise<boolean>;
+ // Provider usage summary
+ getProviderUsageSummary: () => Promise<ProviderUsageSummary[]>;
+
// State
isValidating: boolean;
validationError: string | null;
@@ -280,6 +308,21 @@ export const useApiKeys = (): UseApiKeysResult => {
}
}, [sendRequest, isConnected]);
+ /**
+ * Get aggregated usage and cost summary by provider
+ */
+ const getProviderUsageSummary = useCallback(async (): Promise<ProviderUsageSummary[]> => {
+ if (!isConnected) return [];
+
+ try {
+ const response = await sendRequest<{ providers: ProviderUsageSummary[] }>('get_provider_usage_summary', {});
+ return response?.providers || [];
+ } catch (error) {
+ console.warn('Error fetching provider usage summary:', error);
+ return [];
+ }
+ }, [sendRequest, isConnected]);
+
return {
validateApiKey,
saveApiKey,
@@ -291,6 +334,7 @@ export const useApiKeys = (): UseApiKeysResult => {
getAiModels,
getProviderDefaults,
saveProviderDefaults,
+ getProviderUsageSummary,
isValidating,
validationError,
isConnected
diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.ts
index 879d441f..84bc42ae 100644
--- a/client/src/nodeDefinitions.ts
+++ b/client/src/nodeDefinitions.ts
@@ -17,6 +17,7 @@ import { utilityNodes, UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes
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';
// ============================================================================
// MAIN NODE REGISTRY - Combining all modular definitions
@@ -38,7 +39,8 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {
...utilityNodes,
...skillNodes,
...documentNodes,
- ...socialNodes
+ ...socialNodes,
+ ...twitterNodes
};
// ============================================================================
@@ -110,5 +112,9 @@ export const SOCIAL_NODES = [
...SOCIAL_NODE_TYPES
];
+export const TWITTER_NODES = [
+ ...TWITTER_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/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.ts
index 6a79721f..50f63009 100644
--- a/client/src/nodeDefinitions/specializedAgentNodes.ts
+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts
@@ -342,9 +342,65 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {
subtitle: 'Agent Coordination',
description: 'AI Agent specialized for orchestrating multiple agents. Coordinates complex multi-agent workflows by delegating tasks to specialized agents and synthesizing their results.',
defaults: { name: 'Orchestrator Agent', color: dracula.cyan },
- inputs: AI_AGENT_INPUTS,
+ inputs: [
+ ...AI_AGENT_INPUTS,
+ { name: 'teammates', displayName: 'Team', type: 'main' as NodeConnectionType, description: 'Connect teammate agents for team mode' }
+ ],
outputs: AI_AGENT_OUTPUTS,
- properties: AI_AGENT_PROPERTIES
+ properties: [
+ ...AI_AGENT_PROPERTIES,
+ {
+ displayName: 'Team Mode',
+ name: 'teamMode',
+ type: 'options',
+ options: [
+ { name: 'Disabled', value: '' },
+ { name: 'Parallel', value: 'parallel' },
+ { name: 'Sequential', value: 'sequential' }
+ ],
+ default: '',
+ description: 'Enable team mode to coordinate connected teammate agents'
+ }
+ ]
+ },
+
+ // AI Employee - Team lead node for coordinating multiple agents
+ ai_employee: {
+ displayName: 'AI Employee',
+ name: 'ai_employee',
+ icon: '👥',
+ group: ['agent', 'ai'],
+ version: 1,
+ subtitle: 'Team Orchestration',
+ description: 'AI Employee for coordinating multiple AI agents. Connect teammate agents to enable shared task lists, messaging, and coordinated execution.',
+ defaults: { name: 'AI Employee', color: dracula.purple },
+ inputs: [
+ ...AI_AGENT_INPUTS,
+ { name: 'teammates', displayName: 'Team', type: 'main' as NodeConnectionType, description: 'Connect teammate agents' }
+ ],
+ outputs: AI_AGENT_OUTPUTS,
+ properties: [
+ ...AI_AGENT_PROPERTIES,
+ {
+ displayName: 'Team Mode',
+ name: 'teamMode',
+ type: 'options',
+ options: [
+ { name: 'Parallel', value: 'parallel' },
+ { name: 'Sequential', value: 'sequential' }
+ ],
+ default: 'parallel',
+ description: 'How teammates process tasks'
+ },
+ {
+ displayName: 'Max Concurrent',
+ name: 'maxConcurrent',
+ type: 'number',
+ default: 5,
+ typeOptions: { minValue: 1, maxValue: 20 },
+ description: 'Maximum concurrent task executions'
+ }
+ ]
}
};
@@ -353,4 +409,4 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {
// ============================================================================
// List of specialized agent node types for identification
-export const SPECIALIZED_AGENT_TYPES = ['android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent'];
+export const SPECIALIZED_AGENT_TYPES = ['android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee'];
diff --git a/client/src/nodeDefinitions/twitterNodes.ts b/client/src/nodeDefinitions/twitterNodes.ts
new file mode 100644
index 00000000..a3d9e3c4
--- /dev/null
+++ b/client/src/nodeDefinitions/twitterNodes.ts
@@ -0,0 +1,441 @@
+// Twitter/X Node Definitions - X API v2 integration via OAuth 2.0
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+
+// ============================================================================
+// TWITTER ICONS (SVG Data URIs) - X Brand black color
+// ============================================================================
+
+// Twitter/X Logo - Official X logo (white fill for dark backgrounds)
+export const TWITTER_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23FFFFFF'%3E%3Cpath d='M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z'/%3E%3C/svg%3E";
+
+// All Twitter nodes use the X logo
+const TWITTER_SEND_ICON = TWITTER_ICON;
+const TWITTER_RECEIVE_ICON = TWITTER_ICON;
+const TWITTER_SEARCH_ICON = TWITTER_ICON;
+const TWITTER_USER_ICON = TWITTER_ICON;
+
+// ============================================================================
+// TWITTER NODES
+// ============================================================================
+
+export const twitterNodes: Record<string, INodeTypeDescription> = {
+ // Twitter Send - Post tweets, reply, retweet, like
+ twitterSend: {
+ displayName: 'Twitter Send',
+ name: 'twitterSend',
+ icon: TWITTER_SEND_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Post to Twitter/X',
+ description: 'Post tweets, reply, retweet, like, or delete tweets on Twitter/X',
+ defaults: { name: 'Twitter Send', color: '#000000' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Tweet input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Tweet result'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== ACTION =====
+ {
+ displayName: 'Action',
+ name: 'action',
+ type: 'options',
+ options: [
+ { name: 'Post Tweet', value: 'tweet' },
+ { name: 'Reply to Tweet', value: 'reply' },
+ { name: 'Retweet', value: 'retweet' },
+ { name: 'Quote Tweet', value: 'quote' },
+ { name: 'Like Tweet', value: 'like' },
+ { name: 'Unlike Tweet', value: 'unlike' },
+ { name: 'Delete Tweet', value: 'delete' }
+ ],
+ default: 'tweet',
+ description: 'Action to perform on Twitter'
+ },
+
+ // ===== TWEET TEXT (for tweet, reply, quote) =====
+ {
+ displayName: 'Tweet Text',
+ name: 'text',
+ type: 'string',
+ default: '',
+ required: true,
+ typeOptions: { rows: 4 },
+ description: 'Tweet content (max 280 characters)',
+ placeholder: "What's happening?",
+ displayOptions: {
+ show: { action: ['tweet', 'reply', 'quote'] }
+ }
+ },
+
+ // ===== TWEET ID (for reply, retweet, quote, like, unlike, delete) =====
+ {
+ displayName: 'Tweet ID',
+ name: 'tweet_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '1234567890123456789',
+ description: 'ID of the tweet to interact with',
+ displayOptions: {
+ show: { action: ['reply', 'retweet', 'quote', 'like', 'unlike', 'delete'] }
+ }
+ },
+
+ // ===== MEDIA (for tweet, reply, quote) =====
+ {
+ displayName: 'Include Media',
+ name: 'include_media',
+ type: 'boolean',
+ default: false,
+ description: 'Attach images or videos to the tweet',
+ displayOptions: {
+ show: { action: ['tweet', 'reply', 'quote'] }
+ }
+ },
+ {
+ displayName: 'Media URLs',
+ name: 'media_urls',
+ type: 'string',
+ default: '',
+ placeholder: 'https://example.com/image1.jpg, https://example.com/image2.jpg',
+ description: 'Comma-separated URLs of media to attach (max 4 images or 1 video)',
+ displayOptions: {
+ show: { action: ['tweet', 'reply', 'quote'], include_media: [true] }
+ }
+ },
+
+ // ===== POLL (for tweet) =====
+ {
+ displayName: 'Include Poll',
+ name: 'include_poll',
+ type: 'boolean',
+ default: false,
+ description: 'Create a poll with this tweet',
+ displayOptions: {
+ show: { action: ['tweet'] }
+ }
+ },
+ {
+ displayName: 'Poll Options',
+ name: 'poll_options',
+ type: 'string',
+ default: '',
+ placeholder: 'Option 1, Option 2, Option 3',
+ description: 'Comma-separated poll options (2-4 options, max 25 chars each)',
+ displayOptions: {
+ show: { action: ['tweet'], include_poll: [true] }
+ }
+ },
+ {
+ displayName: 'Poll Duration (minutes)',
+ name: 'poll_duration',
+ type: 'number',
+ default: 1440,
+ typeOptions: { minValue: 5, maxValue: 10080 },
+ description: 'Poll duration in minutes (5 min - 7 days)',
+ displayOptions: {
+ show: { action: ['tweet'], include_poll: [true] }
+ }
+ }
+ ]
+ },
+
+ // Twitter Receive - Trigger on mentions, searches, timeline updates
+ twitterReceive: {
+ displayName: 'Twitter Receive',
+ name: 'twitterReceive',
+ icon: TWITTER_RECEIVE_ICON,
+ group: ['social', 'trigger'],
+ version: 1,
+ subtitle: 'On Twitter Event',
+ description: 'Trigger workflow on Twitter mentions, search results, or timeline updates (polling-based)',
+ defaults: { name: 'Twitter Receive', color: '#1DA1F2' },
+ inputs: [],
+ outputs: [{
+ name: 'main',
+ displayName: 'Tweet',
+ type: 'main' as NodeConnectionType,
+ description: 'Received tweet data (tweet_id, text, author_id, author_username, created_at, metrics)'
+ }],
+ properties: [
+ // ===== TRIGGER TYPE =====
+ {
+ displayName: 'Trigger On',
+ name: 'trigger_type',
+ type: 'options',
+ options: [
+ { name: 'Mentions', value: 'mentions' },
+ { name: 'Search Results', value: 'search' },
+ { name: 'User Timeline', value: 'timeline' }
+ ],
+ default: 'mentions',
+ description: 'What events should trigger this workflow'
+ },
+
+ // ===== SEARCH QUERY (for search trigger) =====
+ {
+ displayName: 'Search Query',
+ name: 'search_query',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'from:elonmusk OR #AI',
+ description: 'Twitter search query (supports operators like from:, to:, #, -)',
+ displayOptions: {
+ show: { trigger_type: ['search'] }
+ }
+ },
+
+ // ===== USER ID (for timeline trigger) =====
+ {
+ displayName: 'User ID',
+ name: 'user_id',
+ type: 'string',
+ default: '',
+ placeholder: '12345678',
+ description: 'Twitter user ID to monitor (leave empty for authenticated user)',
+ displayOptions: {
+ show: { trigger_type: ['timeline'] }
+ }
+ },
+
+ // ===== OPTIONS =====
+ {
+ displayName: 'Filter Retweets',
+ name: 'filter_retweets',
+ type: 'boolean',
+ default: true,
+ description: 'Exclude retweets from results'
+ },
+ {
+ displayName: 'Filter Replies',
+ name: 'filter_replies',
+ type: 'boolean',
+ default: false,
+ description: 'Exclude replies from results'
+ },
+ {
+ displayName: 'Poll Interval (seconds)',
+ name: 'poll_interval',
+ type: 'number',
+ default: 60,
+ typeOptions: { minValue: 15, maxValue: 3600 },
+ description: 'How often to check for new tweets (15s - 1 hour)'
+ }
+ ]
+ },
+
+ // Twitter Search - Search recent tweets
+ twitterSearch: {
+ displayName: 'Twitter Search',
+ name: 'twitterSearch',
+ icon: TWITTER_SEARCH_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Search Tweets',
+ description: 'Search recent tweets on Twitter/X using the Search API',
+ defaults: { name: 'Twitter Search', color: '#1DA1F2' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Search input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Search results'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== SEARCH QUERY =====
+ {
+ displayName: 'Search Query',
+ name: 'query',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '#AI lang:en -is:retweet',
+ description: 'Twitter search query with operators'
+ },
+
+ // ===== RESULT OPTIONS =====
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 10,
+ typeOptions: { minValue: 10, maxValue: 100 },
+ description: 'Maximum number of tweets to return (10-100)'
+ },
+ {
+ displayName: 'Sort Order',
+ name: 'sort_order',
+ type: 'options',
+ options: [
+ { name: 'Recent', value: 'recency' },
+ { name: 'Relevance', value: 'relevancy' }
+ ],
+ default: 'recency',
+ description: 'Sort order for results'
+ },
+
+ // ===== TIME FILTERS =====
+ {
+ displayName: 'Start Time',
+ name: 'start_time',
+ type: 'string',
+ default: '',
+ placeholder: '2024-01-01T00:00:00Z',
+ description: 'Start time for search (ISO 8601 format, optional)'
+ },
+ {
+ displayName: 'End Time',
+ name: 'end_time',
+ type: 'string',
+ default: '',
+ placeholder: '2024-01-31T23:59:59Z',
+ description: 'End time for search (ISO 8601 format, optional)'
+ },
+
+ // ===== INCLUDE OPTIONS =====
+ {
+ displayName: 'Include Metrics',
+ name: 'include_metrics',
+ type: 'boolean',
+ default: true,
+ description: 'Include tweet engagement metrics (likes, retweets, replies)'
+ },
+ {
+ displayName: 'Include Author Info',
+ name: 'include_author',
+ type: 'boolean',
+ default: true,
+ description: 'Include author details (username, name, profile)'
+ }
+ ]
+ },
+
+ // Twitter User - User lookup and profile operations (dual-purpose: workflow + AI tool)
+ twitterUser: {
+ displayName: 'Twitter User',
+ name: 'twitterUser',
+ icon: TWITTER_USER_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'User Operations',
+ description: 'Look up Twitter users, get profile info, followers, following',
+ defaults: { name: 'Twitter User', color: '#1DA1F2' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'User lookup input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'User data'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent input-tools handle'
+ }
+ ],
+ properties: [
+ // ===== OPERATION =====
+ {
+ displayName: 'Operation',
+ name: 'operation',
+ type: 'options',
+ options: [
+ { name: 'Get My Profile', value: 'me' },
+ { name: 'Lookup by Username', value: 'by_username' },
+ { name: 'Lookup by ID', value: 'by_id' },
+ { name: 'Get Followers', value: 'followers' },
+ { name: 'Get Following', value: 'following' }
+ ],
+ default: 'me',
+ description: 'User operation to perform'
+ },
+
+ // ===== USERNAME (for by_username) =====
+ {
+ displayName: 'Username',
+ name: 'username',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'elonmusk',
+ description: 'Twitter username (without @)',
+ displayOptions: {
+ show: { operation: ['by_username'] }
+ }
+ },
+
+ // ===== USER ID (for by_id, followers, following) =====
+ {
+ displayName: 'User ID',
+ name: 'user_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '44196397',
+ description: 'Twitter user ID',
+ displayOptions: {
+ show: { operation: ['by_id', 'followers', 'following'] }
+ }
+ },
+
+ // ===== PAGINATION (for followers, following) =====
+ {
+ displayName: 'Max Results',
+ name: 'max_results',
+ type: 'number',
+ default: 100,
+ typeOptions: { minValue: 1, maxValue: 1000 },
+ description: 'Maximum number of users to return',
+ displayOptions: {
+ show: { operation: ['followers', 'following'] }
+ }
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const TWITTER_NODE_TYPES = ['twitterSend', 'twitterReceive', 'twitterSearch', 'twitterUser'];
diff --git a/client/src/nodeDefinitions/utilityNodes.ts b/client/src/nodeDefinitions/utilityNodes.ts
index 37ab176e..91befabb 100644
--- a/client/src/nodeDefinitions/utilityNodes.ts
+++ b/client/src/nodeDefinitions/utilityNodes.ts
@@ -278,7 +278,51 @@ export const utilityNodes: Record<string, INodeTypeDescription> = {
description: 'Output format for the log'
}
]
+ },
+
+ teamMonitor: {
+ displayName: 'Team Monitor',
+ name: 'teamMonitor',
+ icon: '📊',
+ group: ['utility', 'agent'],
+ version: 1,
+ description: 'Monitor agent team operations, tasks, and messages in real-time',
+ defaults: { name: 'Team Monitor', color: '#8b5cf6' },
+ inputs: [{ name: 'team', displayName: 'Team', type: 'main' as NodeConnectionType, description: 'Connect to AI Employee or Orchestrator Agent node' }],
+ outputs: [{ name: 'main', displayName: 'Events', type: 'main' as NodeConnectionType, description: 'task_completed, task_failed, message_received, team_status' }],
+ properties: [
+ {
+ displayName: 'Auto-Refresh Interval',
+ name: 'refreshInterval',
+ type: 'number',
+ default: 1000,
+ typeOptions: { minValue: 100, maxValue: 10000 },
+ description: 'Refresh interval in milliseconds (0 = WebSocket only)'
+ },
+ {
+ displayName: 'Show Task History',
+ name: 'showTaskHistory',
+ type: 'boolean',
+ default: true,
+ description: 'Display completed/failed tasks in history'
+ },
+ {
+ displayName: 'Show Messages',
+ name: 'showMessages',
+ type: 'boolean',
+ default: true,
+ description: 'Display inter-agent messages'
+ },
+ {
+ displayName: 'Max History Items',
+ name: 'maxHistoryItems',
+ type: 'number',
+ default: 50,
+ typeOptions: { minValue: 10, maxValue: 200 },
+ description: 'Maximum items to show in history'
+ }
+ ]
}
};
-export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse', 'chatTrigger', 'console'];
+export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse', 'chatTrigger', 'console', 'teamMonitor'];
diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.ts
index 7302e961..bf1c6ba4 100644
--- a/client/src/services/executionService.ts
+++ b/client/src/services/executionService.ts
@@ -5,6 +5,7 @@ import { CODE_NODE_TYPES } from '../nodeDefinitions/codeNodes';
import { UTILITY_NODE_TYPES } from '../nodeDefinitions/utilityNodes';
import { DOCUMENT_NODE_TYPES } from '../nodeDefinitions/documentNodes';
import { SPECIALIZED_AGENT_TYPES } from '../nodeDefinitions/specializedAgentNodes';
+import { TWITTER_NODE_TYPES } from '../nodeDefinitions/twitterNodes';
import { Node, Edge } from 'reactflow';
import { INodeExecutionData } from '../types/INodeProperties';
import { API_CONFIG } from '../config/api';
@@ -223,7 +224,9 @@ export class ExecutionService {
// Utility Nodes (HTTP, Webhooks)
...UTILITY_NODE_TYPES,
// Document Processing Nodes
- ...DOCUMENT_NODE_TYPES
+ ...DOCUMENT_NODE_TYPES,
+ // Twitter/X Nodes
+ ...TWITTER_NODE_TYPES
];
return supportedTypes.includes(nodeType);
diff --git a/docs-internal/agent_teams.md b/docs-internal/agent_teams.md
new file mode 100644
index 00000000..fe537a96
--- /dev/null
+++ b/docs-internal/agent_teams.md
@@ -0,0 +1,227 @@
+# Agent Teams Pattern
+
+This document describes the Claude SDK Agent Teams pattern implementation in MachinaOs, enabling multi-agent coordination through AI Employee and Orchestrator nodes.
+
+## Overview
+
+The Agent Teams pattern allows a "team lead" agent to coordinate multiple specialized agents. Instead of blindly delegating to all connected agents, the team lead uses its AI capabilities to decide when and how to delegate based on the user's request.
+
+## Team Lead Node Types
+
+Two node types support the Agent Teams pattern:
+
+| Node Type | Display Name | Description |
+|-----------|--------------|-------------|
+| `orchestrator_agent` | Orchestrator Agent | Coordinates multiple agents for complex workflows |
+| `ai_employee` | AI Employee | Team lead for intelligent task delegation |
+
+Both are defined in `TEAM_LEAD_TYPES` in `server/services/handlers/ai.py`.
+
+## Architecture
+
+```
+ ┌─────────────────┐
+ │ AI Employee │
+ │ (Team Lead) │
+ └────────┬────────┘
+ │ input-teammates
+ ┌─────────────────┼─────────────────┐
+ │ │ │
+ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
+ │ Web Agent │ │Coding Agent │ │ Task Agent │
+ └─────────────┘ └─────────────┘ └─────────────┘
+```
+
+### How It Works
+
+1. **User sends prompt** to AI Employee (e.g., "Write a Python script and search the web for documentation")
+
+2. **Team lead collects teammates** via `input-teammates` handle using `_collect_teammate_connections()`
+
+3. **Teammates become delegation tools** - each connected agent becomes a `delegate_to_*` tool:
+ - `coding_agent` → `delegate_to_coding_agent` tool
+ - `web_agent` → `delegate_to_web_agent` tool
+ - `task_agent` → `delegate_to_task_agent` tool
+
+4. **AI decides whether to delegate** - the team lead's LLM analyzes the request and decides:
+ - For "hi" or simple questions → responds directly (no delegation)
+ - For complex tasks → uses appropriate delegation tools
+
+5. **Delegated agents execute** via the standard `_execute_delegated_agent()` flow in `handlers/tools.py`
+
+## Input Handles
+
+Team lead agents have an additional handle compared to standard specialized agents:
+
+| Handle | Position | Description |
+|--------|----------|-------------|
+| `input-main` | Left 30% | Main data input |
+| `input-memory` | Left 55% | Memory node connection |
+| `input-task` | Left 85% | Task completion events |
+| `input-skill` | Bottom 25% | Skill nodes |
+| `input-teammates` | Bottom 50% | **Specialized agents for delegation** |
+| `input-tools` | Bottom 75% | Tool nodes |
+| `output-top` | Top | Output |
+
+## Backend Implementation
+
+### Handler Logic (`server/services/handlers/ai.py`)
+
+```python
+TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}
+
+async def handle_chat_agent(...):
+ # Collect standard connections
+ memory_data, skill_data, tool_data, input_data, task_data = await _collect_agent_connections(...)
+
+ # Team lead detection - add teammates as delegation tools
+ if node_type in TEAM_LEAD_TYPES:
+ teammates = await _collect_teammate_connections(node_id, context, database)
+
+ if teammates:
+ tool_data = tool_data or []
+ for tm in teammates:
+ tool_data.append({
+ 'node_id': tm['node_id'],
+ 'node_type': tm['node_type'],
+ 'label': tm['label'],
+ 'parameters': tm.get('parameters', {}),
+ })
+ logger.info(f"[Teams] Added {len(teammates)} teammates as delegation tools")
+
+ # Standard execution - AI has delegate_to_* tools available
+ return await ai_service.execute_chat_agent(...)
+```
+
+### Teammate Collection (`_collect_teammate_connections`)
+
+```python
+async def _collect_teammate_connections(node_id, context, database):
+ """Collect agents connected via input-teammates handle."""
+ teammates = []
+
+ for edge in edges:
+ if edge.get('target') != node_id:
+ continue
+ if edge.get('targetHandle') != 'input-teammates':
+ continue
+
+ source_node = next((n for n in nodes if n.get('id') == edge.get('source')), None)
+ if source_node and source_node.get('type') in AI_AGENT_TYPES:
+ params = await database.get_node_parameters(source_node['id'])
+ teammates.append({
+ 'node_id': source_node['id'],
+ 'node_type': source_node['type'],
+ 'label': source_node.get('data', {}).get('label'),
+ 'parameters': params
+ })
+
+ return teammates
+```
+
+## Delegation Tools
+
+When teammates are connected, the AI service builds delegation tools via `_build_tool_from_node()`:
+
+```python
+# Tool name mapping in ai.py
+DEFAULT_TOOL_NAMES = {
+ 'coding_agent': 'delegate_to_coding_agent',
+ 'web_agent': 'delegate_to_web_agent',
+ 'task_agent': 'delegate_to_task_agent',
+ # ... etc
+}
+
+# Schema for delegation
+class DelegateToAgentSchema(BaseModel):
+ task: str = Field(description="The task to delegate")
+ context: Optional[str] = Field(description="Additional context")
+```
+
+The AI receives tools like:
+- `delegate_to_coding_agent(task="Write a Python script...")`
+- `delegate_to_web_agent(task="Search for React documentation...")`
+
+## Team Tracking Service
+
+The `AgentTeamService` (`server/services/agent_team.py`) provides optional team tracking:
+
+```python
+class AgentTeamService:
+ async def create_team(team_lead_node_id, teammate_node_ids, workflow_id, config)
+ async def add_task(team_id, title, description, created_by, priority)
+ async def claim_task(team_id, task_id, agent_node_id)
+ async def complete_task(team_id, task_id, result)
+ async def fail_task(team_id, task_id, error)
+ async def get_team_status(team_id)
+```
+
+### Database Tables
+
+| Table | Description |
+|-------|-------------|
+| `agent_teams` | Team metadata (id, workflow_id, team_lead_node_id, status) |
+| `team_members` | Team membership (agent_node_id, role, status) |
+| `team_tasks` | Shared task list with dependencies |
+| `agent_messages` | Inter-agent communication |
+
+## Team Monitor Node
+
+The `teamMonitor` node displays real-time team operations:
+
+- **Stats Grid**: Member count, task counts (total/done/active/pending)
+- **Active Tasks Panel**: Currently executing tasks
+- **Event Stream**: Real-time log of task completions and messages
+
+Connect Team Monitor to a team lead's output to visualize team activity.
+
+## Example Workflow
+
+```
+┌─────────────┐ ┌─────────────────┐ ┌─────────────┐
+│Chat Trigger │────▶│ AI Employee │────▶│Team Monitor │
+└─────────────┘ └────────┬────────┘ └─────────────┘
+ │ input-teammates
+ ┌──────────────┼──────────────┐
+ │ │ │
+ ┌──────▼──────┐ ┌─────▼─────┐ ┌──────▼──────┐
+ │ Coding Agent│ │ Web Agent │ │ Task Agent │
+ │ + Python │ │ + HTTP │ │ │
+ └─────────────┘ └───────────┘ └─────────────┘
+```
+
+**User says**: "Search for React best practices and write a summary script"
+
+**AI Employee decides**:
+1. Calls `delegate_to_web_agent(task="Search for React best practices")`
+2. Waits for result via `check_delegated_tasks`
+3. Calls `delegate_to_coding_agent(task="Write a Python script to summarize: {web_result}")`
+4. Synthesizes final response
+
+**User says**: "Hello!"
+
+**AI Employee decides**: Responds directly with greeting (no delegation needed)
+
+## Key Files
+
+| File | Description |
+|------|-------------|
+| `server/services/handlers/ai.py` | `TEAM_LEAD_TYPES`, `_collect_teammate_connections()`, team mode detection |
+| `server/services/agent_team.py` | `AgentTeamService` for team tracking |
+| `server/services/handlers/tools.py` | `_execute_delegated_agent()` for actual delegation |
+| `server/services/ai.py` | `_build_tool_from_node()` builds delegate_to_* tools |
+| `client/src/nodeDefinitions/specializedAgentNodes.ts` | `ai_employee` and `orchestrator_agent` definitions |
+| `client/src/components/AIAgentNode.tsx` | Agent node rendering with `input-teammates` handle |
+| `client/src/components/TeamMonitorNode.tsx` | Team monitoring UI |
+
+## Design Decisions
+
+1. **AI-Driven Delegation**: The team lead's AI decides when to delegate, not automatic forwarding to all teammates
+
+2. **Tool-Based Pattern**: Teammates become `delegate_to_*` tools, leveraging existing LangGraph tool calling
+
+3. **Fire-and-Forget**: Delegated agents run as background tasks; team lead can check status via `check_delegated_tasks`
+
+4. **API Key Inheritance**: Teammates inherit provider/model from team lead if not configured; API keys injected via standard `_inject_api_keys` flow
+
+5. **Standard Execution Path**: Team leads use the same `execute_chat_agent` flow as other agents, just with additional delegation tools
diff --git a/docs-internal/dual_purpose_tool_node_creation.md b/docs-internal/dual_purpose_tool_node_creation.md
index 893b2d8d..17454938 100644
--- a/docs-internal/dual_purpose_tool_node_creation.md
+++ b/docs-internal/dual_purpose_tool_node_creation.md
@@ -94,7 +94,7 @@ Nodes that work BOTH as workflow nodes AND as AI tools.
- NOT in `AI_TOOL_TYPES` (would break workflow execution)
- Dynamically excluded when connected to `input-tools` handle
-**Examples:** `whatsappSend`, `whatsappDb`, `httpRequest`, `pythonExecutor`, `javascriptExecutor`, `addLocations`, `showNearbyPlaces`
+**Examples:** `whatsappSend`, `whatsappDb`, `twitterSend`, `twitterSearch`, `twitterUser`, `httpRequest`, `pythonExecutor`, `javascriptExecutor`, `addLocations`, `showNearbyPlaces`
### Comparison Table
@@ -696,6 +696,301 @@ Query WhatsApp database - contacts, groups, messages.
---
+## Complete Example: Twitter/X Nodes
+
+The `twitterSend`, `twitterSearch`, and `twitterUser` nodes are examples of dual-purpose tools using OAuth 2.0 authentication and the XDK Python SDK.
+
+### Frontend Definition (twitterNodes.ts)
+
+```typescript
+twitterSend: {
+ displayName: 'Twitter Send',
+ name: 'twitterSend',
+ icon: TWITTER_ICON,
+ group: ['social', 'tool'], // Include 'tool' for dual-purpose
+ version: 1,
+ subtitle: 'Post to Twitter/X',
+ description: 'Post tweets, reply, retweet, like/unlike, delete',
+ defaults: { name: 'Twitter Send', color: '#000000' },
+
+ // Main input for workflow
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Trigger input'
+ }],
+
+ // Both outputs
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Action result'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+
+ properties: [
+ {
+ displayName: 'Action',
+ name: 'action',
+ type: 'options',
+ default: 'tweet',
+ options: [
+ { name: 'Post Tweet', value: 'tweet' },
+ { name: 'Reply', value: 'reply' },
+ { name: 'Retweet', value: 'retweet' },
+ { name: 'Like', value: 'like' },
+ { name: 'Unlike', value: 'unlike' },
+ { name: 'Delete', value: 'delete' }
+ ]
+ },
+ {
+ displayName: 'Text',
+ name: 'text',
+ type: 'string',
+ typeOptions: { rows: 4 },
+ default: '',
+ description: 'Tweet text (max 280 characters)',
+ displayOptions: { show: { action: ['tweet', 'reply'] } }
+ },
+ {
+ displayName: 'Tweet ID',
+ name: 'tweet_id',
+ type: 'string',
+ default: '',
+ description: 'Target tweet ID',
+ displayOptions: { show: { action: ['retweet', 'like', 'unlike', 'delete'] } }
+ },
+ {
+ displayName: 'Reply To ID',
+ name: 'reply_to_id',
+ type: 'string',
+ default: '',
+ description: 'Tweet ID to reply to',
+ displayOptions: { show: { action: ['reply'] } }
+ }
+ ]
+}
+```
+
+### Backend Schema (ai.py)
+
+```python
+if node_type == 'twitterSend':
+ class TwitterSendSchema(BaseModel):
+ """Post tweets, reply, retweet, like/unlike, and delete on Twitter/X."""
+ action: str = Field(
+ default="tweet",
+ description="Action: 'tweet', 'reply', 'retweet', 'like', 'unlike', 'delete'"
+ )
+ text: Optional[str] = Field(
+ default=None,
+ description="Tweet text (max 280 chars). Required for 'tweet' and 'reply'"
+ )
+ tweet_id: Optional[str] = Field(
+ default=None,
+ description="Target tweet ID. Required for 'retweet', 'like', 'unlike', 'delete'"
+ )
+ reply_to_id: Optional[str] = Field(
+ default=None,
+ description="Tweet ID to reply to. Required for 'reply'"
+ )
+ return TwitterSendSchema
+
+if node_type == 'twitterSearch':
+ class TwitterSearchSchema(BaseModel):
+ """Search recent tweets on Twitter/X."""
+ query: str = Field(
+ description="Search query (supports operators: from:, to:, #, @, OR, -exclude, lang:, has:links, has:media)"
+ )
+ max_results: int = Field(
+ default=10,
+ description="Maximum results (10-100)"
+ )
+ return TwitterSearchSchema
+
+if node_type == 'twitterUser':
+ class TwitterUserSchema(BaseModel):
+ """Look up Twitter/X user profiles and social connections."""
+ operation: str = Field(
+ default="me",
+ description="Operation: 'me', 'by_username', 'by_id', 'followers', 'following'"
+ )
+ username: Optional[str] = Field(
+ default=None,
+ description="Twitter username without @ (for 'by_username')"
+ )
+ user_id: Optional[str] = Field(
+ default=None,
+ description="Twitter user ID (for 'by_id', 'followers', 'following')"
+ )
+ max_results: int = Field(
+ default=100,
+ description="Max results for followers/following (1-1000)"
+ )
+ return TwitterUserSchema
+```
+
+### Backend Handler (tools.py)
+
+```python
+async def _execute_twitter_send(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter send actions."""
+ from services.handlers.twitter import handle_twitter_send
+
+ parameters = {
+ 'action': args.get('action', 'tweet'),
+ 'text': args.get('text', ''),
+ 'tweet_id': args.get('tweet_id', ''),
+ 'reply_to_id': args.get('reply_to_id', ''),
+ }
+
+ action = parameters['action']
+ if action in ('tweet', 'reply') and not parameters['text']:
+ return {"error": "Text is required for tweet/reply actions"}
+ if action in ('retweet', 'like', 'unlike', 'delete') and not parameters['tweet_id']:
+ return {"error": "tweet_id is required for this action"}
+ if action == 'reply' and not parameters['reply_to_id']:
+ return {"error": "reply_to_id is required for reply action"}
+
+ result = await handle_twitter_send(
+ node_id="tool_twitter_send",
+ node_type="twitterSend",
+ parameters=parameters,
+ context={}
+ )
+
+ if result.get('success'):
+ return {"success": True, "action": action, "result": result.get('result', {})}
+ return {"error": result.get('error', 'Twitter action failed')}
+
+
+async def _execute_twitter_search(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter search."""
+ from services.handlers.twitter import handle_twitter_search
+
+ parameters = {
+ 'query': args.get('query', ''),
+ 'max_results': min(args.get('max_results', 10), 100),
+ }
+
+ if not parameters['query']:
+ return {"error": "Search query is required"}
+
+ result = await handle_twitter_search(
+ node_id="tool_twitter_search",
+ node_type="twitterSearch",
+ parameters=parameters,
+ context={}
+ )
+
+ if result.get('success'):
+ return result.get('result', {})
+ return {"error": result.get('error', 'Search failed')}
+
+
+async def _execute_twitter_user(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter user lookup."""
+ from services.handlers.twitter import handle_twitter_user
+
+ parameters = {
+ 'operation': args.get('operation', 'me'),
+ 'username': args.get('username', ''),
+ 'user_id': args.get('user_id', ''),
+ 'max_results': min(args.get('max_results', 100), 1000),
+ }
+
+ operation = parameters['operation']
+ if operation == 'by_username' and not parameters['username']:
+ return {"error": "Username is required for by_username operation"}
+ if operation == 'by_id' and not parameters['user_id']:
+ return {"error": "user_id is required for by_id operation"}
+
+ result = await handle_twitter_user(
+ node_id="tool_twitter_user",
+ node_type="twitterUser",
+ parameters=parameters,
+ context={}
+ )
+
+ if result.get('success'):
+ return result.get('result', {})
+ return {"error": result.get('error', 'User lookup failed')}
+```
+
+### XDK SDK Authentication Pattern
+
+Twitter nodes use OAuth 2.0 PKCE authentication stored via `auth_service`:
+
+```python
+# In server/services/handlers/twitter.py
+async def _get_twitter_client() -> Client:
+ """Get authenticated Twitter client from stored OAuth 2.0 credentials."""
+ from core.container import container
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("twitter_access_token")
+ if not access_token:
+ raise ValueError("Twitter not connected. Please authenticate via Credentials.")
+ # OAuth 2.0 user token (not bearer_token which is app-only)
+ return Client(access_token=access_token)
+```
+
+### Skill Documentation (SKILL.md)
+
+```markdown
+---
+name: twitter-send-skill
+description: Post tweets, reply, retweet, like/unlike, delete on Twitter/X.
+allowed-tools: twitter_send
+metadata:
+ author: machina
+ version: "1.0"
+ category: social
+---
+
+# Twitter Send Tool
+
+## twitter_send
+
+Post and interact with tweets on Twitter/X.
+
+### Parameters
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| action | string | Yes | 'tweet', 'reply', 'retweet', 'like', 'unlike', 'delete' |
+| text | string | If tweet/reply | Tweet text (max 280 chars) |
+| tweet_id | string | If retweet/like/unlike/delete | Target tweet ID |
+| reply_to_id | string | If reply | Tweet ID to reply to |
+
+### Examples
+
+**Post a tweet:**
+```json
+{"action": "tweet", "text": "Hello from AI!"}
+```
+
+**Reply to a tweet:**
+```json
+{"action": "reply", "text": "Great point!", "reply_to_id": "1234567890"}
+```
+
+**Like a tweet:**
+```json
+{"action": "like", "tweet_id": "1234567890"}
+```
+```
+
+---
+
## Checklist
### Frontend
diff --git a/docs-internal/memory_compaction.md b/docs-internal/memory_compaction.md
index c44eb22e..d0c77238 100644
--- a/docs-internal/memory_compaction.md
+++ b/docs-internal/memory_compaction.md
@@ -1,11 +1,12 @@
-# Memory Compaction and Token Tracking Service
+# Memory Compaction, Token Tracking, and Cost Calculation Service
## Overview
-The compaction service enables automatic memory compaction and token tracking for MachinaOs specialized agents. It uses a hybrid approach leveraging native provider APIs (Anthropic, OpenAI) when available, with comprehensive token tracking for all providers.
+The compaction service enables automatic memory compaction, token tracking, and **cost calculation** for MachinaOs specialized agents. It uses a hybrid approach leveraging native provider APIs (Anthropic, OpenAI) when available, with comprehensive token and cost tracking for all providers.
**Inspired by:** Claude Code's compaction pattern from the Anthropic SDK
**Default Threshold:** 100,000 tokens (configurable per session)
+**Cost Calculation:** Official pricing from each provider (per 1M tokens)
## Architecture
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 4f4302a6..8d89a889 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -26,22 +26,25 @@ This guide explains how to create new nodes for MachinaOs, covering frontend def
## Node Types Overview
-MachinaOs supports 58 nodes across 15 categories:
+MachinaOs supports 79 nodes across 16 categories:
| Category | Visual Component | Example Nodes | Count |
|----------|-----------------|---------------|-------|
-| **Workflow** | StartNode | start | 1 |
+| **Workflow** | StartNode | start, taskTrigger | 2 |
| **Scheduler** | SquareNode | timer, cronScheduler | 2 |
| **AI Chat Models** | SquareNode | openaiChatModel, anthropicChatModel, geminiChatModel, openrouterChatModel, groqChatModel, cerebrasChatModel | 6 |
| **AI Agents** | AIAgentNode | aiAgent, chatAgent | 2 |
+| **Specialized Agents** | AIAgentNode | android_agent, coding_agent, web_agent, task_agent, social_agent, travel_agent, tool_agent, productivity_agent, payments_agent, consumer_agent, autonomous_agent, orchestrator_agent | 12 |
| **AI Memory** | SquareNode | simpleMemory | 1 |
-| **AI Skills** | SquareNode | claudeSkill, whatsappSkill, memorySkill, mapsSkill, httpSkill, schedulerSkill, androidSkill, codeSkill, customSkill | 9 |
+| **AI Skills** | SquareNode | masterSkill, customSkill + 9 individual skills | 11 |
| **AI Tools** | SquareNode | calculatorTool, currentTimeTool, webSearchTool, androidTool | 4 |
-| **Triggers** | TriggerNode | whatsappReceive, webhookTrigger, chatTrigger | 3 |
-| **Android** | SquareNode | batteryMonitor, wifiAutomation, location, cameraControl (16 services + 1 setup) | 17 |
-| **WhatsApp** | SquareNode | whatsappSend, whatsappConnect, whatsappReceive, whatsappDb | 4 |
+| **Triggers** | TriggerNode | whatsappReceive, webhookTrigger, chatTrigger, twitterReceive | 4 |
+| **Android** | SquareNode | batteryMonitor, wifiAutomation, location, cameraControl (16 services) | 16 |
+| **WhatsApp** | SquareNode | whatsappSend, whatsappReceive, whatsappDb | 3 |
+| **Twitter/X** | SquareNode | twitterSend, twitterSearch, twitterUser, twitterReceive | 4 |
+| **Social** | SquareNode | socialReceive, socialSend | 2 |
| **Location/Maps** | SquareNode | createMap, addLocations, showNearbyPlaces | 3 |
-| **Utility** | SquareNode | httpRequest, webhookResponse, console | 3 |
+| **Utility** | SquareNode | httpRequest, webhookTrigger, webhookResponse, chatTrigger, console | 5 |
| **Code** | SquareNode | pythonExecutor, javascriptExecutor | 2 |
| **Chat** | SquareNode | chatSend, chatHistory | 2 |
| **Document** | SquareNode | httpScraper, fileDownloader, documentParser, textChunker, embeddingGenerator, vectorStore | 6 |
diff --git a/server/constants.py b/server/constants.py
index d2380bf5..4efa88a2 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -34,6 +34,7 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset([
'consumer_agent',
'autonomous_agent',
'orchestrator_agent',
+ 'ai_employee',
])
AI_MEMORY_TYPES: FrozenSet[str] = frozenset([
@@ -148,6 +149,24 @@ WHATSAPP_TYPES: FrozenSet[str] = frozenset([
'whatsappDb',
])
+# =============================================================================
+# TWITTER NODE TYPES
+# =============================================================================
+
+TWITTER_TYPES: FrozenSet[str] = frozenset([
+ 'twitterSend',
+ 'twitterReceive',
+ 'twitterSearch',
+ 'twitterUser',
+])
+
+# Dual-purpose Twitter nodes (workflow node + AI tool)
+TWITTER_TOOL_TYPES: FrozenSet[str] = frozenset([
+ 'twitterSend',
+ 'twitterSearch',
+ 'twitterUser',
+])
+
# =============================================================================
# SOCIAL NODE TYPES (unified messaging)
# =============================================================================
@@ -207,6 +226,7 @@ WORKFLOW_CONTROL_TYPES: FrozenSet[str] = frozenset([
EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset([
'webhookTrigger',
'whatsappReceive',
+ 'twitterReceive',
'workflowTrigger',
'chatTrigger',
'taskTrigger',
diff --git a/server/core/database.py b/server/core/database.py
index fb6d8d98..3c81fdad 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -12,7 +12,8 @@ from core.config import Settings
from models.database import (
NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput,
ConversationMessage, ToolSchema, UserSkill, ChatMessage, UserSettings,
- TokenUsageMetric, CompactionEvent, SessionTokenState, ProviderDefaults
+ TokenUsageMetric, CompactionEvent, SessionTokenState, ProviderDefaults,
+ AgentTeam, TeamMember, TeamTask, AgentMessage
)
from models.cache import CacheEntry # SQLite-backed cache for Redis alternative
from models.auth import User # Import User model to ensure table creation
@@ -87,6 +88,29 @@ class Database:
"ALTER TABLE user_settings ADD COLUMN examples_loaded BOOLEAN DEFAULT 0"
))
logger.info("Added examples_loaded column to user_settings")
+
+ # Migrate token_usage_metrics table - add cost columns
+ result = await conn.execute(text("PRAGMA table_info(token_usage_metrics)"))
+ columns = {row[1] for row in result.fetchall()}
+
+ for col in ["input_cost", "output_cost", "cache_cost", "total_cost"]:
+ if col not in columns:
+ await conn.execute(text(
+ f"ALTER TABLE token_usage_metrics ADD COLUMN {col} REAL DEFAULT 0.0"
+ ))
+ logger.info(f"Added {col} column to token_usage_metrics")
+
+ # Migrate session_token_states table - add cumulative cost columns
+ result = await conn.execute(text("PRAGMA table_info(session_token_states)"))
+ columns = {row[1] for row in result.fetchall()}
+
+ for col in ["cumulative_input_cost", "cumulative_output_cost", "cumulative_total_cost"]:
+ if col not in columns:
+ await conn.execute(text(
+ f"ALTER TABLE session_token_states ADD COLUMN {col} REAL DEFAULT 0.0"
+ ))
+ logger.info(f"Added {col} column to session_token_states")
+
except Exception as e:
logger.warning(f"Migration check failed (table may not exist yet): {e}")
@@ -1568,7 +1592,12 @@ class Database:
reasoning_tokens=metric.get("reasoning_tokens", 0),
iteration=metric.get("iteration", 1),
execution_id=metric.get("execution_id"),
- created_at=datetime.now(timezone.utc)
+ created_at=datetime.now(timezone.utc),
+ # Cost fields
+ input_cost=metric.get("input_cost", 0.0),
+ output_cost=metric.get("output_cost", 0.0),
+ cache_cost=metric.get("cache_cost", 0.0),
+ total_cost=metric.get("total_cost", 0.0)
)
session.add(entry)
await session.commit()
@@ -1614,6 +1643,97 @@ class Database:
logger.error("Failed to get token metrics", session_id=session_id, error=str(e))
return []
+ async def get_provider_usage_summary(self) -> List[Dict[str, Any]]:
+ """Get aggregated token usage and cost by provider.
+
+ Returns a list of provider summaries with:
+ - provider: Provider name (openai, anthropic, etc.)
+ - total_input_tokens: Sum of input tokens
+ - total_output_tokens: Sum of output tokens
+ - total_tokens: Sum of all tokens
+ - total_input_cost: Sum of input costs (USD)
+ - total_output_cost: Sum of output costs (USD)
+ - total_cost: Sum of all costs (USD)
+ - execution_count: Number of executions
+ - models: Breakdown by model (list of dicts)
+ """
+ try:
+ async with self.get_session() as session:
+ from sqlalchemy import func
+
+ # First get per-model breakdown
+ model_stmt = (
+ select(
+ TokenUsageMetric.provider,
+ TokenUsageMetric.model,
+ func.sum(TokenUsageMetric.input_tokens).label("input_tokens"),
+ func.sum(TokenUsageMetric.output_tokens).label("output_tokens"),
+ func.sum(TokenUsageMetric.total_tokens).label("total_tokens"),
+ func.sum(TokenUsageMetric.input_cost).label("input_cost"),
+ func.sum(TokenUsageMetric.output_cost).label("output_cost"),
+ func.sum(TokenUsageMetric.cache_cost).label("cache_cost"),
+ func.sum(TokenUsageMetric.total_cost).label("total_cost"),
+ func.count().label("execution_count")
+ )
+ .group_by(TokenUsageMetric.provider, TokenUsageMetric.model)
+ .order_by(TokenUsageMetric.provider, TokenUsageMetric.model)
+ )
+ result = await session.execute(model_stmt)
+ rows = result.all()
+
+ # Aggregate by provider
+ providers: Dict[str, Dict] = {}
+ for row in rows:
+ provider = row.provider or "unknown"
+ if provider not in providers:
+ providers[provider] = {
+ "provider": provider,
+ "total_input_tokens": 0,
+ "total_output_tokens": 0,
+ "total_tokens": 0,
+ "total_input_cost": 0.0,
+ "total_output_cost": 0.0,
+ "total_cache_cost": 0.0,
+ "total_cost": 0.0,
+ "execution_count": 0,
+ "models": []
+ }
+
+ p = providers[provider]
+ p["total_input_tokens"] += row.input_tokens or 0
+ p["total_output_tokens"] += row.output_tokens or 0
+ p["total_tokens"] += row.total_tokens or 0
+ p["total_input_cost"] += float(row.input_cost or 0)
+ p["total_output_cost"] += float(row.output_cost or 0)
+ p["total_cache_cost"] += float(row.cache_cost or 0)
+ p["total_cost"] += float(row.total_cost or 0)
+ p["execution_count"] += row.execution_count or 0
+
+ p["models"].append({
+ "model": row.model,
+ "input_tokens": row.input_tokens or 0,
+ "output_tokens": row.output_tokens or 0,
+ "total_tokens": row.total_tokens or 0,
+ "input_cost": round(float(row.input_cost or 0), 6),
+ "output_cost": round(float(row.output_cost or 0), 6),
+ "cache_cost": round(float(row.cache_cost or 0), 6),
+ "total_cost": round(float(row.total_cost or 0), 6),
+ "execution_count": row.execution_count or 0
+ })
+
+ # Round provider totals
+ for p in providers.values():
+ p["total_input_cost"] = round(p["total_input_cost"], 6)
+ p["total_output_cost"] = round(p["total_output_cost"], 6)
+ p["total_cache_cost"] = round(p["total_cache_cost"], 6)
+ p["total_cost"] = round(p["total_cost"], 6)
+
+ return list(providers.values())
+
+ except Exception as e:
+ logger.error("Failed to get provider usage summary", error=str(e))
+ return []
+
# ============================================================================
# Session Token State
# ============================================================================
@@ -1786,4 +1906,324 @@ class Database:
]
except Exception as e:
logger.error("Failed to get compaction history", session_id=session_id, error=str(e))
- return []
\ No newline at end of file
+ return []
+
+ # ============================================================================
+ # Agent Teams - CRUD Operations
+ # ============================================================================
+
+ async def create_team(self, team_id: str, workflow_id: str, team_lead_node_id: str,
+ config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
+ """Create a new agent team."""
+ try:
+ async with self.get_session() as session:
+ team = AgentTeam(
+ id=team_id, workflow_id=workflow_id, team_lead_node_id=team_lead_node_id,
+ config=config or {}, created_at=datetime.now(timezone.utc)
+ )
+ session.add(team)
+ await session.commit()
+ logger.info(f"[Teams] Created team {team_id}")
+ return {"id": team.id, "workflow_id": team.workflow_id, "status": team.status}
+ except Exception as e:
+ logger.error(f"Failed to create team: {e}")
+ return None
+
+ async def get_team(self, team_id: str) -> Optional[Dict[str, Any]]:
+ """Get team by ID."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(select(AgentTeam).where(AgentTeam.id == team_id))
+ team = result.scalar_one_or_none()
+ if not team:
+ return None
+ return {
+ "id": team.id, "workflow_id": team.workflow_id, "team_lead_node_id": team.team_lead_node_id,
+ "status": team.status, "config": team.config,
+ "created_at": team.created_at.isoformat() if team.created_at else None
+ }
+ except Exception as e:
+ logger.error(f"Failed to get team: {e}")
+ return None
+
+ async def update_team_status(self, team_id: str, status: str) -> bool:
+ """Update team status."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(select(AgentTeam).where(AgentTeam.id == team_id))
+ team = result.scalar_one_or_none()
+ if not team:
+ return False
+ team.status = status
+ if status in ("completed", "failed", "dissolved"):
+ team.completed_at = datetime.now(timezone.utc)
+ await session.commit()
+ return True
+ except Exception as e:
+ logger.error(f"Failed to update team status: {e}")
+ return False
+
+ async def add_team_member(self, team_id: str, agent_node_id: str, agent_type: str,
+ role: str = "teammate", agent_label: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ """Add member to team."""
+ try:
+ async with self.get_session() as session:
+ member = TeamMember(
+ team_id=team_id, agent_node_id=agent_node_id, agent_type=agent_type,
+ agent_label=agent_label, role=role, joined_at=datetime.now(timezone.utc)
+ )
+ session.add(member)
+ await session.commit()
+ return {"id": member.id, "agent_node_id": agent_node_id, "role": role}
+ except Exception as e:
+ logger.error(f"Failed to add team member: {e}")
+ return None
+
+ async def get_team_members(self, team_id: str) -> List[Dict[str, Any]]:
+ """Get all team members."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(TeamMember).where(TeamMember.team_id == team_id)
+ )
+ return [
+ {"id": m.id, "agent_node_id": m.agent_node_id, "agent_type": m.agent_type,
+ "agent_label": m.agent_label, "role": m.role, "status": m.status}
+ for m in result.scalars().all()
+ ]
+ except Exception as e:
+ logger.error(f"Failed to get team members: {e}")
+ return []
+
+ async def update_member_status(self, team_id: str, agent_node_id: str, status: str) -> bool:
+ """Update member status (idle, working, offline)."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(TeamMember).where(
+ TeamMember.team_id == team_id, TeamMember.agent_node_id == agent_node_id
+ )
+ )
+ member = result.scalar_one_or_none()
+ if not member:
+ return False
+ member.status = status
+ await session.commit()
+ return True
+ except Exception as e:
+ logger.error(f"Failed to update member status: {e}")
+ return False
+
+ async def add_team_task(self, task_id: str, team_id: str, title: str, created_by: str,
+ description: Optional[str] = None, priority: int = 3,
+ depends_on: Optional[List[str]] = None) -> Optional[Dict[str, Any]]:
+ """Add task to team's shared list."""
+ try:
+ async with self.get_session() as session:
+ task = TeamTask(
+ id=task_id, team_id=team_id, title=title, description=description,
+ priority=priority, created_by=created_by,
+ depends_on={"task_ids": depends_on} if depends_on else None,
+ created_at=datetime.now(timezone.utc)
+ )
+ session.add(task)
+ await session.commit()
+ return {"id": task.id, "title": title, "status": "pending"}
+ except Exception as e:
+ logger.error(f"Failed to add team task: {e}")
+ return None
+
+ async def get_team_tasks(self, team_id: str, status: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Get team tasks, optionally filtered by status."""
+ try:
+ async with self.get_session() as session:
+ query = select(TeamTask).where(TeamTask.team_id == team_id)
+ if status:
+ query = query.where(TeamTask.status == status)
+ query = query.order_by(TeamTask.priority.asc(), TeamTask.created_at.asc())
+ result = await session.execute(query)
+ return [
+ {"id": t.id, "title": t.title, "description": t.description, "status": t.status,
+ "priority": t.priority, "assigned_to": t.assigned_to, "progress": t.progress,
+ "depends_on": t.depends_on.get("task_ids", []) if t.depends_on else []}
+ for t in result.scalars().all()
+ ]
+ except Exception as e:
+ logger.error(f"Failed to get team tasks: {e}")
+ return []
+
+ async def claim_task(self, task_id: str, agent_node_id: str) -> Optional[Dict[str, Any]]:
+ """Claim a pending task. Returns None if already claimed."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(TeamTask).where(
+ TeamTask.id == task_id, TeamTask.status == "pending", TeamTask.assigned_to.is_(None)
+ )
+ )
+ task = result.scalar_one_or_none()
+ if not task:
+ return None
+ task.assigned_to = agent_node_id
+ task.status = "in_progress"
+ task.started_at = datetime.now(timezone.utc)
+ await session.commit()
+ return {"id": task.id, "title": task.title, "assigned_to": agent_node_id}
+ except Exception as e:
+ logger.error(f"Failed to claim task: {e}")
+ return None
+
+ async def complete_task(self, task_id: str, result_data: Optional[Dict[str, Any]] = None) -> bool:
+ """Mark task as completed."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(select(TeamTask).where(TeamTask.id == task_id))
+ task = result.scalar_one_or_none()
+ if not task:
+ return False
+ task.status = "completed"
+ task.result = result_data
+ task.progress = 100
+ task.completed_at = datetime.now(timezone.utc)
+ await session.commit()
+ return True
+ except Exception as e:
+ logger.error(f"Failed to complete task: {e}")
+ return False
+
+ async def fail_task(self, task_id: str, error: str) -> bool:
+ """Mark task as failed."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(select(TeamTask).where(TeamTask.id == task_id))
+ task = result.scalar_one_or_none()
+ if not task:
+ return False
+ task.error = error
+ task.retry_count += 1
+ if task.retry_count < task.max_retries:
+ task.status = "pending"
+ task.assigned_to = None
+ else:
+ task.status = "failed"
+ task.completed_at = datetime.now(timezone.utc)
+ await session.commit()
+ return True
+ except Exception as e:
+ logger.error(f"Failed to fail task: {e}")
+ return False
+
+ async def get_claimable_tasks(self, team_id: str) -> List[Dict[str, Any]]:
+ """Get pending tasks with resolved dependencies."""
+ try:
+ async with self.get_session() as session:
+ result = await session.execute(select(TeamTask).where(TeamTask.team_id == team_id))
+ tasks = result.scalars().all()
+ completed_ids = {t.id for t in tasks if t.status == "completed"}
+ claimable = []
+ for t in tasks:
+ if t.status != "pending" or t.assigned_to:
+ continue
+ deps = t.depends_on.get("task_ids", []) if t.depends_on else []
+ if all(d in completed_ids for d in deps):
+ claimable.append({"id": t.id, "title": t.title, "priority": t.priority})
+ return claimable
+ except Exception as e:
+ logger.error(f"Failed to get claimable tasks: {e}")
+ return []
+
+ async def add_agent_message(self, team_id: str, from_agent: str, content: str,
+ message_type: str = "direct", to_agent: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ """Add message between agents."""
+ try:
+ async with self.get_session() as session:
+ msg = AgentMessage(
+ team_id=team_id, from_agent=from_agent, to_agent=to_agent,
+ message_type=message_type, content=content, created_at=datetime.now(timezone.utc)
+ )
+ session.add(msg)
+ await session.commit()
+ return {"id": msg.id, "from_agent": from_agent, "to_agent": to_agent}
+ except Exception as e:
+ logger.error(f"Failed to add agent message: {e}")
+ return None
+
+ async def get_agent_messages(self, team_id: str, agent_node_id: Optional[str] = None,
+ unread_only: bool = False) -> List[Dict[str, Any]]:
+ """Get messages for team or specific agent."""
+ try:
+ async with self.get_session() as session:
+ from sqlalchemy import or_
+ query = select(AgentMessage).where(AgentMessage.team_id == team_id)
+ if agent_node_id:
+ query = query.where(or_(
+ AgentMessage.to_agent == agent_node_id,
+ AgentMessage.to_agent.is_(None)
+ ))
+ if unread_only:
+ query = query.where(AgentMessage.read == False)
+ query = query.order_by(AgentMessage.created_at.asc()).limit(100)
+ result = await session.execute(query)
+ return [
+ {"id": m.id, "from_agent": m.from_agent, "to_agent": m.to_agent,
+ "message_type": m.message_type, "content": m.content, "read": m.read,
+ "created_at": m.created_at.isoformat() if m.created_at else None}
+ for m in result.scalars().all()
+ ]
+ except Exception as e:
+ logger.error(f"Failed to get agent messages: {e}")
+ return []
+
+ async def mark_messages_read(self, team_id: str, agent_node_id: str) -> int:
+ """Mark all messages as read for an agent."""
+ try:
+ async with self.get_session() as session:
+ from sqlalchemy import or_
+ result = await session.execute(
+ select(AgentMessage).where(
+ AgentMessage.team_id == team_id,
+ AgentMessage.read == False,
+ or_(AgentMessage.to_agent == agent_node_id, AgentMessage.to_agent.is_(None))
+ )
+ )
+ messages = result.scalars().all()
+ for m in messages:
+ m.read = True
+ await session.commit()
+ return len(messages)
+ except Exception as e:
+ logger.error(f"Failed to mark messages read: {e}")
+ return 0
+
+ async def get_team_stats(self, team_id: str) -> Dict[str, Any]:
+ """Get team statistics."""
+ try:
+ async with self.get_session() as session:
+ # Get counts in simple queries
+ team_result = await session.execute(select(AgentTeam).where(AgentTeam.id == team_id))
+ team = team_result.scalar_one_or_none()
+ if not team:
+ return {"error": "Team not found"}
+
+ members_result = await session.execute(select(TeamMember).where(TeamMember.team_id == team_id))
+ members = members_result.scalars().all()
+
+ tasks_result = await session.execute(select(TeamTask).where(TeamTask.team_id == team_id))
+ tasks = tasks_result.scalars().all()
+
+ return {
+ "team_id": team_id,
+ "status": team.status,
+ "member_count": len(members),
+ "task_total": len(tasks),
+ "task_pending": sum(1 for t in tasks if t.status == "pending"),
+ "task_in_progress": sum(1 for t in tasks if t.status == "in_progress"),
+ "task_completed": sum(1 for t in tasks if t.status == "completed"),
+ "task_failed": sum(1 for t in tasks if t.status == "failed"),
+ "members": [{"id": m.agent_node_id, "type": m.agent_type, "status": m.status} for m in members],
+ "active_tasks": [{"id": t.id, "title": t.title, "assigned_to": t.assigned_to, "progress": t.progress}
+ for t in tasks if t.status == "in_progress"]
+ }
+ except Exception as e:
+ logger.error(f"Failed to get team stats: {e}")
+ return {"error": str(e)}
\ No newline at end of file
diff --git a/server/main.py b/server/main.py
index e36664ca..f930b791 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
+from routers import workflow, database, maps, nodejs_compat, android, websocket, webhook, auth, twitter
# Initialize settings and logging
settings = Settings()
@@ -61,6 +61,7 @@ async def lifespan(app: FastAPI):
"routers.websocket",
"routers.webhook",
"routers.auth",
+ "routers.twitter",
"middleware.auth"
])
@@ -122,6 +123,12 @@ async def lifespan(app: FastAPI):
compaction_svc.set_ai_service(container.ai_service())
logger.info("Compaction service initialized")
+ # Initialize agent team service
+ from services.agent_team import init_agent_team_service
+ from services.status_broadcaster import get_status_broadcaster
+ init_agent_team_service(container.database(), get_status_broadcaster())
+ logger.info("Agent team service initialized")
+
# Record startup time for health reporting
set_startup_time()
@@ -268,6 +275,7 @@ app.include_router(maps.router)
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.get("/health")
diff --git a/server/models/database.py b/server/models/database.py
index b31850f9..9567a18d 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -1,7 +1,7 @@
"""SQLModel database models and tables."""
from datetime import datetime, timezone
-from typing import Optional, Dict, Any
+from typing import Optional, Dict, Any, List
from sqlmodel import SQLModel, Field, Column, DateTime, JSON
from sqlalchemy import func
@@ -315,6 +315,11 @@ class TokenUsageMetric(SQLModel, table=True):
iteration: int = Field(default=1)
execution_id: Optional[str] = Field(default=None, max_length=255)
created_at: Optional[datetime] = Field(default=None)
+ # Cost fields (USD)
+ input_cost: float = Field(default=0.0)
+ output_cost: float = Field(default=0.0)
+ cache_cost: float = Field(default=0.0)
+ total_cost: float = Field(default=0.0)
class CompactionEvent(SQLModel, table=True):
@@ -356,4 +361,109 @@ class SessionTokenState(SQLModel, table=True):
compaction_count: int = Field(default=0)
custom_threshold: Optional[int] = Field(default=None)
compaction_enabled: bool = Field(default=True)
- updated_at: Optional[datetime] = Field(default=None)
\ No newline at end of file
+ updated_at: Optional[datetime] = Field(default=None)
+ # Cumulative cost fields (USD)
+ cumulative_input_cost: float = Field(default=0.0)
+ cumulative_output_cost: float = Field(default=0.0)
+ cumulative_total_cost: float = Field(default=0.0)
+
+
+# =============================================================================
+# Agent Teams - Claude SDK Agent Teams Pattern
+# =============================================================================
+
+
+class AgentTeam(SQLModel, table=True):
+ """Agent team for multi-agent collaboration.
+
+ Implements Claude SDK Agent Teams pattern where a team lead coordinates
+ multiple teammate agents working on shared tasks.
+ """
+
+ __tablename__ = "agent_teams"
+
+ id: str = Field(primary_key=True, max_length=255)
+ workflow_id: str = Field(index=True, max_length=255)
+ team_lead_node_id: str = Field(max_length=255)
+ status: str = Field(default="active", max_length=20) # active, completed, failed, dissolved
+ config: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
+ created_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+ completed_at: Optional[datetime] = Field(default=None)
+
+
+class TeamMember(SQLModel, table=True):
+ """Agent team membership.
+
+ Tracks which agents belong to which team and their current status.
+ """
+
+ __tablename__ = "team_members"
+
+ id: Optional[int] = Field(default=None, primary_key=True)
+ team_id: str = Field(index=True, max_length=255)
+ agent_node_id: str = Field(index=True, max_length=255)
+ agent_type: str = Field(max_length=100) # orchestrator_agent, android_agent, etc.
+ agent_label: Optional[str] = Field(default=None, max_length=255) # User-defined label
+ role: str = Field(default="teammate", max_length=20) # team_lead, teammate
+ status: str = Field(default="idle", max_length=20) # idle, working, offline
+ capabilities: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
+ joined_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+
+
+class TeamTask(SQLModel, table=True):
+ """Shared task in agent team task list.
+
+ Tasks are created by the team lead and claimed by teammates.
+ Supports dependencies between tasks.
+ """
+
+ __tablename__ = "team_tasks"
+
+ id: str = Field(primary_key=True, max_length=255)
+ team_id: str = Field(index=True, max_length=255)
+ title: str = Field(max_length=500)
+ description: Optional[str] = Field(default=None, max_length=5000)
+ status: str = Field(default="pending", max_length=20) # pending, in_progress, completed, failed, skipped
+ priority: int = Field(default=3) # 1-5, lower = higher priority
+ created_by: str = Field(max_length=255) # agent_node_id
+ assigned_to: Optional[str] = Field(default=None, max_length=255)
+ depends_on: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # List of task_ids
+ result: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
+ error: Optional[str] = Field(default=None, max_length=2000)
+ retry_count: int = Field(default=0)
+ max_retries: int = Field(default=3)
+ progress: int = Field(default=0) # 0-100 percentage
+ created_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+ started_at: Optional[datetime] = Field(default=None)
+ completed_at: Optional[datetime] = Field(default=None)
+
+
+class AgentMessage(SQLModel, table=True):
+ """Inter-agent messages within a team.
+
+ Supports direct messages between agents and broadcasts to all team members.
+ """
+
+ __tablename__ = "agent_messages"
+
+ id: Optional[int] = Field(default=None, primary_key=True)
+ team_id: str = Field(index=True, max_length=255)
+ from_agent: str = Field(max_length=255) # node_id
+ to_agent: Optional[str] = Field(default=None, max_length=255) # None = broadcast
+ message_type: str = Field(max_length=50) # direct, broadcast, task_assignment, task_update, task_complete
+ content: str = Field(max_length=10000)
+ extra_data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
+ read: bool = Field(default=False)
+ created_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
\ No newline at end of file
diff --git a/server/pyproject.toml b/server/pyproject.toml
index bfce9978..1f580cd1 100644
--- a/server/pyproject.toml
+++ b/server/pyproject.toml
@@ -54,6 +54,9 @@ dependencies = [
# Web Search
"ddgs>=9.0.0",
+
+ # Twitter/X API
+ "xdk>=0.1.0",
]
[project.optional-dependencies]
diff --git a/server/requirements.txt b/server/requirements.txt
index 4799ccdc..b116a1cc 100644
--- a/server/requirements.txt
+++ b/server/requirements.txt
@@ -71,6 +71,9 @@ email-validator>=2.0.0
# Timezone support
pytz>=2024.1
+# Twitter/X API
+xdk>=0.1.0
+
# Document Processing Nodes
beautifulsoup4>=4.12.0
langchain-text-splitters>=0.3.0
diff --git a/server/routers/twitter.py b/server/routers/twitter.py
new file mode 100644
index 00000000..befbabc6
--- /dev/null
+++ b/server/routers/twitter.py
@@ -0,0 +1,390 @@
+"""
+Twitter/X OAuth 2.0 callback and API routes.
+
+OAuth flow:
+1. Frontend calls WebSocket 'twitter_oauth_login' handler
+2. Backend generates authorization URL, opens browser
+3. User authorizes on Twitter
+4. Twitter redirects to /api/twitter/callback with code
+5. Backend exchanges code for tokens, stores them via auth_service
+6. Frontend polls WebSocket 'twitter_oauth_status' for completion
+
+Tokens stored as API keys with provider prefixes:
+- twitter_access_token: OAuth access token (expires in 2 hours)
+- twitter_refresh_token: OAuth refresh token (for token renewal)
+"""
+
+from typing import Optional
+
+from fastapi import APIRouter, Query
+from fastapi.responses import HTMLResponse
+
+from core.container import container
+from core.logging import get_logger
+from services.twitter_oauth import TwitterOAuth, get_pending_state
+
+logger = get_logger(__name__)
+router = APIRouter(prefix="/api/twitter", tags=["twitter"])
+
+
+def get_auth_service():
+ """Get auth service for API key storage."""
+ return container.auth_service()
+
+
+def get_twitter_oauth() -> TwitterOAuth:
+ """Create TwitterOAuth instance from stored credentials."""
+ auth_service = get_auth_service()
+ # Twitter client_id and client_secret are stored as API keys
+ # These are configured in the Credentials Modal
+ import asyncio
+ loop = asyncio.get_event_loop()
+
+ # Get stored Twitter app credentials (client_id, client_secret)
+ # These are stored via the Credentials Modal with provider='twitter'
+ 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"
+
+ return TwitterOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri=redirect_uri,
+ )
+
+
[email protected]("/callback")
+async def twitter_oauth_callback(
+ code: Optional[str] = Query(None),
+ state: Optional[str] = Query(None),
+ error: Optional[str] = Query(None),
+ error_description: Optional[str] = Query(None),
+):
+ """
+ Handle Twitter OAuth callback.
+
+ Twitter redirects here after user authorizes (or denies) the app.
+ We exchange the code for tokens and store them via auth_service.
+ """
+ # Handle authorization denied
+ if error:
+ logger.warning(f"Twitter 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("Twitter OAuth callback missing code or state")
+ return HTMLResponse(
+ content=_callback_html(
+ success=False,
+ error="Missing authorization code or state parameter",
+ ),
+ status_code=400,
+ )
+
+ # Verify state exists (CSRF protection)
+ pending_state = get_pending_state(state)
+ if not pending_state:
+ logger.error("Twitter OAuth callback with invalid/expired state")
+ return HTMLResponse(
+ content=_callback_html(
+ success=False,
+ error="Invalid or expired authorization state. Please try again.",
+ ),
+ status_code=400,
+ )
+
+ # Get stored client credentials to create OAuth instance
+ 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")
+
+ oauth = TwitterOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+ # Exchange code for tokens
+ result = await oauth.exchange_code(code=code, state=state)
+
+ if not result.get("success"):
+ logger.error(f"Twitter token exchange failed: {result.get('error')}")
+ return HTMLResponse(
+ content=_callback_html(
+ success=False,
+ error=result.get("error", "Token exchange failed"),
+ ),
+ status_code=400,
+ )
+
+ # Get user info to display and store
+ access_token = result.get("access_token")
+ refresh_token = result.get("refresh_token")
+ user_info = await oauth.get_user_info(access_token)
+
+ if not user_info.get("success"):
+ logger.warning(f"Failed to get Twitter user info: {user_info.get('error')}")
+ username = "Unknown"
+ else:
+ username = user_info.get("username", "Unknown")
+
+ # Store tokens in database via auth_service (same pattern as other API keys)
+ # Access token stored with provider='twitter_access_token'
+ await auth_service.store_api_key(
+ provider="twitter_access_token",
+ api_key=access_token,
+ models=[], # No models for OAuth tokens
+ session_id="default"
+ )
+
+ # Refresh token stored with provider='twitter_refresh_token'
+ if refresh_token:
+ await auth_service.store_api_key(
+ provider="twitter_refresh_token",
+ api_key=refresh_token,
+ models=[],
+ session_id="default"
+ )
+
+ # Store user info for display purposes
+ if user_info.get("success"):
+ await auth_service.store_api_key(
+ provider="twitter_user_info",
+ api_key=f"{user_info.get('id')}:{username}:{user_info.get('name', '')}",
+ models=[],
+ session_id="default"
+ )
+
+ # Broadcast completion event to frontend
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+
+ await broadcaster.broadcast({
+ "type": "twitter_oauth_complete",
+ "data": {
+ "success": True,
+ "username": username,
+ "user_id": user_info.get("id"),
+ "name": user_info.get("name"),
+ "profile_image_url": user_info.get("profile_image_url"),
+ }
+ })
+
+ logger.info(f"Twitter OAuth successful for @{username}")
+
+ return HTMLResponse(
+ content=_callback_html(
+ success=True,
+ username=username,
+ ),
+ status_code=200,
+ )
+
+
+async def get_twitter_status():
+ """
+ Get Twitter connection status.
+
+ Returns whether the user is authenticated with Twitter.
+ """
+ auth_service = get_auth_service()
+
+ # Try to get stored access token
+ access_token = await auth_service.get_api_key("twitter_access_token")
+
+ if not access_token:
+ return {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ }
+
+ # Get stored client credentials
+ 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",
+ )
+
+ # Verify token is still valid by getting user info
+ user_info = await oauth.get_user_info(access_token)
+
+ if not user_info.get("success"):
+ # Token may be expired, try to refresh
+ refresh_token = await auth_service.get_api_key("twitter_refresh_token")
+ if refresh_token:
+ refresh_result = await oauth.refresh_access_token(refresh_token)
+ if refresh_result.get("success"):
+ # Store new tokens via auth_service
+ await auth_service.store_api_key(
+ provider="twitter_access_token",
+ api_key=refresh_result["access_token"],
+ models=[],
+ session_id="default"
+ )
+ if refresh_result.get("refresh_token"):
+ await auth_service.store_api_key(
+ provider="twitter_refresh_token",
+ api_key=refresh_result["refresh_token"],
+ models=[],
+ session_id="default"
+ )
+
+ # Retry user info
+ user_info = await oauth.get_user_info(refresh_result["access_token"])
+
+ if not user_info.get("success"):
+ return {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ "error": user_info.get("error"),
+ }
+
+ return {
+ "connected": True,
+ "username": user_info.get("username"),
+ "user_id": user_info.get("id"),
+ "name": user_info.get("name"),
+ "profile_image_url": user_info.get("profile_image_url"),
+ "verified": user_info.get("verified"),
+ }
+
+
+async def twitter_logout():
+ """
+ Disconnect Twitter by revoking tokens and clearing stored credentials.
+ """
+ auth_service = get_auth_service()
+
+ # Get stored tokens
+ access_token = await auth_service.get_api_key("twitter_access_token")
+ refresh_token = await auth_service.get_api_key("twitter_refresh_token")
+
+ # Get client credentials for revocation
+ client_id = await auth_service.get_api_key("twitter_client_id") or ""
+ client_secret = await auth_service.get_api_key("twitter_client_secret")
+
+ # Revoke tokens if we have them
+ if access_token or refresh_token:
+ oauth = TwitterOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+ if access_token:
+ await oauth.revoke_token(access_token, "access_token")
+
+ if refresh_token:
+ await oauth.revoke_token(refresh_token, "refresh_token")
+
+ # Clear stored credentials via auth_service
+ await auth_service.remove_api_key("twitter_access_token")
+ await auth_service.remove_api_key("twitter_refresh_token")
+ await auth_service.remove_api_key("twitter_user_info")
+
+ logger.info("Twitter disconnected and tokens revoked")
+
+ return {"success": True, "message": "Twitter disconnected"}
+
+
+def _callback_html(success: bool, username: str = None, error: str = None) -> str:
+ """Generate callback HTML page that closes itself and notifies parent."""
+ if success:
+ title = "Twitter Connected"
+ message = f"Successfully connected as @{username}!"
+ color = "#00ba7c" # Green
+ icon = "check-circle"
+ else:
+ title = "Connection Failed"
+ message = error or "Failed to connect to Twitter"
+ color = "#f4212e" # Red
+ icon = "x-circle"
+
+ 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 0%, #1a1a2e 100%);
+ 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>
+ // Notify parent window and close
+ if (window.opener) {{
+ window.opener.postMessage({{
+ type: 'twitter_oauth_callback',
+ success: {str(success).lower()},
+ {"username: '" + username + "'," if username else ""}
+ {"error: '" + error.replace("'", "\\'") + "'," if error else ""}
+ }}, '*');
+ }}
+ // Close after 2 seconds
+ setTimeout(function() {{ window.close(); }}, 2000);
+ </script>
+</body>
+</html>
+"""
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 44992416..8f8a2db7 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1045,6 +1045,163 @@ async def handle_claude_oauth_status(data: Dict[str, Any], websocket: WebSocket)
return get_claude_credentials()
+# ============================================================================
+# Twitter OAuth Handlers
+# ============================================================================
+
+@ws_handler()
+async def handle_twitter_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Initiate Twitter OAuth 2.0 with PKCE flow.
+
+ Opens browser to Twitter authorization page. After user authorizes,
+ Twitter redirects to /api/twitter/callback which stores tokens.
+ """
+ import webbrowser
+ from services.twitter_oauth import TwitterOAuth
+
+ auth_service = container.auth_service()
+
+ # Get stored client credentials (configured via Credentials Modal)
+ client_id = await auth_service.get_api_key("twitter_client_id")
+ client_secret = await auth_service.get_api_key("twitter_client_secret")
+
+ if not client_id:
+ return {
+ "success": False,
+ "error": "Twitter Client ID not configured. Add your Twitter API credentials first."
+ }
+
+ # Create OAuth instance and generate authorization URL
+ oauth = TwitterOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+ auth_data = oauth.generate_authorization_url()
+
+ # Open browser to authorization URL
+ webbrowser.open(auth_data["url"])
+
+ return {
+ "success": True,
+ "message": "Opening Twitter authorization in browser...",
+ "state": auth_data["state"],
+ }
+
+
+@ws_handler()
+async def handle_twitter_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Check Twitter OAuth connection status.
+
+ Returns connection status and user info if connected.
+ """
+ from services.twitter_oauth import TwitterOAuth
+
+ auth_service = container.auth_service()
+
+ # Check for stored access token
+ access_token = await auth_service.get_api_key("twitter_access_token")
+
+ if not access_token:
+ return {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ }
+
+ # Get client credentials for API calls
+ 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",
+ )
+
+ # Verify token by getting user info
+ user_info = await oauth.get_user_info(access_token)
+
+ if not user_info.get("success"):
+ # Try to refresh token
+ refresh_token = await auth_service.get_api_key("twitter_refresh_token")
+ if refresh_token:
+ refresh_result = await oauth.refresh_access_token(refresh_token)
+ if refresh_result.get("success"):
+ # Store new tokens
+ await auth_service.store_api_key(
+ provider="twitter_access_token",
+ api_key=refresh_result["access_token"],
+ models=[],
+ session_id="default"
+ )
+ if refresh_result.get("refresh_token"):
+ await auth_service.store_api_key(
+ provider="twitter_refresh_token",
+ api_key=refresh_result["refresh_token"],
+ models=[],
+ session_id="default"
+ )
+ # Retry user info
+ user_info = await oauth.get_user_info(refresh_result["access_token"])
+
+ if not user_info.get("success"):
+ return {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ "error": user_info.get("error"),
+ }
+
+ return {
+ "connected": True,
+ "username": user_info.get("username"),
+ "user_id": user_info.get("id"),
+ "name": user_info.get("name"),
+ "profile_image_url": user_info.get("profile_image_url"),
+ "verified": user_info.get("verified"),
+ }
+
+
+@ws_handler()
+async def handle_twitter_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """
+ Disconnect Twitter by revoking tokens and clearing stored credentials.
+ """
+ from services.twitter_oauth import TwitterOAuth
+
+ auth_service = container.auth_service()
+
+ # Get stored tokens
+ access_token = await auth_service.get_api_key("twitter_access_token")
+ refresh_token = await auth_service.get_api_key("twitter_refresh_token")
+ client_id = await auth_service.get_api_key("twitter_client_id") or ""
+ client_secret = await auth_service.get_api_key("twitter_client_secret")
+
+ # Revoke tokens if we have them
+ if access_token or refresh_token:
+ oauth = TwitterOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+ if access_token:
+ await oauth.revoke_token(access_token, "access_token")
+ if refresh_token:
+ await oauth.revoke_token(refresh_token, "refresh_token")
+
+ # Clear stored credentials
+ await auth_service.remove_api_key("twitter_access_token")
+ await auth_service.remove_api_key("twitter_refresh_token")
+ await auth_service.remove_api_key("twitter_user_info")
+
+ return {"success": True, "message": "Twitter 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."""
@@ -2059,6 +2216,149 @@ async def handle_configure_compaction(data: Dict[str, Any], websocket: WebSocket
return {"success": success}
+@ws_handler()
+async def handle_get_provider_usage_summary(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get aggregated token usage and cost by provider for Credentials Modal."""
+ database = container.database()
+ providers = await database.get_provider_usage_summary()
+ return {"success": True, "providers": providers}
+
+
+# ============================================================================
+# Agent Team Handlers
+# ============================================================================
+
+@ws_handler("workflow_id", "team_lead_node_id")
+async def handle_create_team(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Create a new agent team."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ team = await service.create_team(
+ team_lead_node_id=data["team_lead_node_id"],
+ teammate_node_ids=data.get("teammates", []),
+ workflow_id=data["workflow_id"],
+ config=data.get("config")
+ )
+ return {"team": team} if team else {"success": False, "error": "Failed to create team"}
+
+
+@ws_handler("team_id")
+async def handle_get_team(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get team info."""
+ database = container.database()
+ team = await database.get_team(data["team_id"])
+ return {"team": team} if team else {"success": False, "error": "Team not found"}
+
+
+@ws_handler()
+async def handle_get_team_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get team status with stats.
+
+ Can provide team_id directly, or team_lead_node_id to find active team.
+ """
+ from services.agent_team import get_agent_team_service
+
+ try:
+ service = get_agent_team_service()
+ except RuntimeError:
+ # Service not initialized - no active teams
+ return {"status": {"members": [], "task_count": 0, "completed_count": 0, "active_count": 0, "pending_count": 0, "failed_count": 0, "active_tasks": []}}
+
+ team_id = data.get("team_id")
+
+ # If no team_id, try to find by team_lead_node_id
+ if not team_id and data.get("team_lead_node_id"):
+ # Look up active team for this workflow (most recent)
+ # This is a simple approach - check if there's an active team with this lead
+ # For now, return empty status - teams are created when AI Employee runs
+ return {"status": {"members": [], "task_count": 0, "completed_count": 0, "active_count": 0, "pending_count": 0, "failed_count": 0, "active_tasks": [], "message": "No active team yet"}}
+
+ if not team_id:
+ return {"status": {"members": [], "task_count": 0, "completed_count": 0, "active_count": 0, "pending_count": 0, "failed_count": 0, "active_tasks": [], "message": "No team connected"}}
+
+ status = await service.get_team_status(team_id)
+ return {"status": status}
+
+
+@ws_handler("team_id")
+async def handle_dissolve_team(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Dissolve a team."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ success = await service.dissolve_team(data["team_id"], data.get("workflow_id"))
+ return {"success": success}
+
+
+@ws_handler("team_id", "title", "created_by")
+async def handle_add_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Add task to team."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ task = await service.add_task(
+ team_id=data["team_id"],
+ title=data["title"],
+ created_by=data["created_by"],
+ description=data.get("description"),
+ priority=data.get("priority", 3),
+ depends_on=data.get("depends_on")
+ )
+ return {"task": task} if task else {"success": False, "error": "Failed to add task"}
+
+
+@ws_handler("team_id", "task_id", "agent_node_id")
+async def handle_claim_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Claim a task."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ task = await service.claim_task(data["team_id"], data["task_id"], data["agent_node_id"])
+ return {"task": task} if task else {"success": False, "error": "Task unavailable"}
+
+
+@ws_handler("team_id", "task_id")
+async def handle_complete_team_task(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Complete a task."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ success = await service.complete_task(data["team_id"], data["task_id"], data.get("result"))
+ return {"success": success}
+
+
+@ws_handler("team_id")
+async def handle_get_team_tasks(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get team tasks."""
+ database = container.database()
+ tasks = await database.get_team_tasks(data["team_id"], data.get("status"))
+ return {"tasks": tasks}
+
+
+@ws_handler("team_id", "from_agent", "content")
+async def handle_send_team_message(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Send message in team."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ msg = await service.send_message(
+ team_id=data["team_id"],
+ from_agent=data["from_agent"],
+ content=data["content"],
+ to_agent=data.get("to_agent"),
+ message_type=data.get("message_type", "direct")
+ )
+ return {"message": msg} if msg else {"success": False, "error": "Failed to send message"}
+
+
+@ws_handler("team_id")
+async def handle_get_team_messages(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get team messages."""
+ from services.agent_team import get_agent_team_service
+ service = get_agent_team_service()
+ messages = await service.get_messages(
+ team_id=data["team_id"],
+ agent_node_id=data.get("agent_node_id"),
+ unread_only=data.get("unread_only", False)
+ )
+ return {"messages": messages}
+
+
# ============================================================================
# Message Router
# ============================================================================
@@ -2123,6 +2423,11 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"claude_oauth_login": handle_claude_oauth_login,
"claude_oauth_status": handle_claude_oauth_status,
+ # Twitter OAuth operations
+ "twitter_oauth_login": handle_twitter_oauth_login,
+ "twitter_oauth_status": handle_twitter_oauth_status,
+ "twitter_logout": handle_twitter_logout,
+
# Android operations
"get_android_devices": handle_get_android_devices,
"execute_android_action": handle_execute_android_action,
@@ -2195,6 +2500,21 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
# Compaction
"get_compaction_stats": handle_get_compaction_stats,
"configure_compaction": handle_configure_compaction,
+
+ # Provider Usage Summary
+ "get_provider_usage_summary": handle_get_provider_usage_summary,
+
+ # Agent Teams
+ "create_team": handle_create_team,
+ "get_team": handle_get_team,
+ "get_team_status": handle_get_team_status,
+ "dissolve_team": handle_dissolve_team,
+ "add_team_task": handle_add_team_task,
+ "claim_team_task": handle_claim_team_task,
+ "complete_team_task": handle_complete_team_task,
+ "get_team_tasks": handle_get_team_tasks,
+ "send_team_message": handle_send_team_message,
+ "get_team_messages": handle_get_team_messages,
}
diff --git a/server/services/agent_team.py b/server/services/agent_team.py
new file mode 100644
index 00000000..debde760
--- /dev/null
+++ b/server/services/agent_team.py
@@ -0,0 +1,266 @@
+"""Agent Team Service - Claude SDK Agent Teams pattern.
+
+Coordinates multi-agent teams with shared task lists and messaging.
+Teams are scoped to specific workflow executions.
+"""
+
+import uuid
+from typing import Dict, Any, List, Optional
+from core.database import Database
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+class AgentTeamService:
+ """Service for managing agent teams.
+
+ Teams are workflow-specific - each team belongs to a workflow execution.
+ """
+
+ def __init__(self, database: Database, broadcaster=None):
+ self.database = database
+ self.broadcaster = broadcaster
+ # Track active teams per workflow
+ self._active_teams: Dict[str, str] = {} # workflow_id -> team_id
+
+ # -------------------------------------------------------------------------
+ # Team Lifecycle
+ # -------------------------------------------------------------------------
+
+ async def create_team(
+ self,
+ team_lead_node_id: str,
+ teammate_node_ids: List[Dict[str, Any]],
+ workflow_id: str,
+ config: Optional[Dict[str, Any]] = None
+ ) -> Optional[Dict[str, Any]]:
+ """Create a team with lead and teammates.
+
+ Args:
+ team_lead_node_id: Node ID of the team lead agent
+ teammate_node_ids: List of {node_id, node_type, label} for teammates
+ workflow_id: Workflow containing the team
+ config: Team configuration (mode: parallel/sequential/hybrid)
+
+ Returns:
+ Team dict or None on failure
+ """
+ team_id = f"team_{uuid.uuid4().hex[:12]}"
+
+ # Create team
+ team = await self.database.create_team(
+ team_id=team_id,
+ workflow_id=workflow_id,
+ team_lead_node_id=team_lead_node_id,
+ config=config or {"mode": "parallel"}
+ )
+ if not team:
+ return None
+
+ # Add team lead as member
+ await self.database.add_team_member(
+ team_id=team_id,
+ agent_node_id=team_lead_node_id,
+ agent_type="orchestrator_agent",
+ role="team_lead"
+ )
+
+ # Add teammates
+ for teammate in teammate_node_ids:
+ await self.database.add_team_member(
+ team_id=team_id,
+ agent_node_id=teammate["node_id"],
+ agent_type=teammate.get("node_type", "agent"),
+ agent_label=teammate.get("label"),
+ role="teammate"
+ )
+
+ # Broadcast team creation
+ if self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "team_created", {
+ "team_id": team_id,
+ "workflow_id": workflow_id,
+ "member_count": len(teammate_node_ids) + 1
+ })
+
+ # Track active team for this workflow
+ self._active_teams[workflow_id] = team_id
+
+ logger.info(f"[Teams] Created team {team_id} with {len(teammate_node_ids)} teammates")
+ return {"team_id": team_id, **team}
+
+ def get_active_team_for_workflow(self, workflow_id: str) -> Optional[str]:
+ """Get the active team ID for a workflow."""
+ return self._active_teams.get(workflow_id)
+
+ async def dissolve_team(self, team_id: str, workflow_id: Optional[str] = None) -> bool:
+ """Dissolve a team."""
+ success = await self.database.update_team_status(team_id, "dissolved")
+ if success:
+ # Remove from active teams tracking
+ if workflow_id and workflow_id in self._active_teams:
+ del self._active_teams[workflow_id]
+ if self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "team_dissolved", {"team_id": team_id})
+ return success
+
+ async def get_team_status(self, team_id: str) -> Dict[str, Any]:
+ """Get comprehensive team status."""
+ return await self.database.get_team_stats(team_id)
+
+ # -------------------------------------------------------------------------
+ # Task Management
+ # -------------------------------------------------------------------------
+
+ async def add_task(
+ self,
+ team_id: str,
+ title: str,
+ created_by: str,
+ description: Optional[str] = None,
+ priority: int = 3,
+ depends_on: Optional[List[str]] = None
+ ) -> Optional[Dict[str, Any]]:
+ """Add a task to the shared task list."""
+ task_id = f"task_{uuid.uuid4().hex[:12]}"
+
+ task = await self.database.add_team_task(
+ task_id=task_id,
+ team_id=team_id,
+ title=title,
+ created_by=created_by,
+ description=description,
+ priority=priority,
+ depends_on=depends_on
+ )
+
+ if task and self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "task_added", task)
+
+ return task
+
+ async def claim_task(self, team_id: str, task_id: str, agent_node_id: str) -> Optional[Dict[str, Any]]:
+ """Claim a task for an agent."""
+ # Update member status to working
+ await self.database.update_member_status(team_id, agent_node_id, "working")
+
+ task = await self.database.claim_task(task_id, agent_node_id)
+
+ if task and self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "task_claimed", {
+ **task, "claimed_by": agent_node_id
+ })
+
+ return task
+
+ async def complete_task(self, team_id: str, task_id: str, result: Optional[Dict[str, Any]] = None) -> bool:
+ """Mark a task as completed."""
+ # Get task to find assigned agent
+ tasks = await self.database.get_team_tasks(team_id)
+ task = next((t for t in tasks if t["id"] == task_id), None)
+
+ success = await self.database.complete_task(task_id, result)
+
+ if success:
+ # Update member status back to idle
+ if task and task.get("assigned_to"):
+ await self.database.update_member_status(team_id, task["assigned_to"], "idle")
+
+ if self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "task_completed", {
+ "task_id": task_id, "result": result
+ })
+
+ return success
+
+ async def fail_task(self, team_id: str, task_id: str, error: str) -> bool:
+ """Mark a task as failed."""
+ tasks = await self.database.get_team_tasks(team_id)
+ task = next((t for t in tasks if t["id"] == task_id), None)
+
+ success = await self.database.fail_task(task_id, error)
+
+ if success:
+ if task and task.get("assigned_to"):
+ await self.database.update_member_status(team_id, task["assigned_to"], "idle")
+
+ if self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "task_failed", {
+ "task_id": task_id, "error": error
+ })
+
+ return success
+
+ async def get_claimable_tasks(self, team_id: str) -> List[Dict[str, Any]]:
+ """Get tasks ready to be claimed."""
+ return await self.database.get_claimable_tasks(team_id)
+
+ async def is_team_done(self, team_id: str) -> bool:
+ """Check if all tasks are completed/failed."""
+ tasks = await self.database.get_team_tasks(team_id)
+ if not tasks:
+ return True
+ return all(t["status"] in ("completed", "failed", "skipped") for t in tasks)
+
+ # -------------------------------------------------------------------------
+ # Messaging
+ # -------------------------------------------------------------------------
+
+ async def send_message(
+ self,
+ team_id: str,
+ from_agent: str,
+ content: str,
+ to_agent: Optional[str] = None,
+ message_type: str = "direct"
+ ) -> Optional[Dict[str, Any]]:
+ """Send a message to a specific agent or broadcast."""
+ msg = await self.database.add_agent_message(
+ team_id=team_id,
+ from_agent=from_agent,
+ content=content,
+ message_type=message_type if to_agent else "broadcast",
+ to_agent=to_agent
+ )
+
+ if msg and self.broadcaster:
+ await self.broadcaster.broadcast_team_event(team_id, "team_message", msg)
+
+ return msg
+
+ async def broadcast(self, team_id: str, from_agent: str, content: str) -> Optional[Dict[str, Any]]:
+ """Broadcast message to all team members."""
+ return await self.send_message(team_id, from_agent, content, to_agent=None)
+
+ async def get_messages(
+ self,
+ team_id: str,
+ agent_node_id: Optional[str] = None,
+ unread_only: bool = False
+ ) -> List[Dict[str, Any]]:
+ """Get messages for a team or specific agent."""
+ return await self.database.get_agent_messages(team_id, agent_node_id, unread_only)
+
+ async def mark_read(self, team_id: str, agent_node_id: str) -> int:
+ """Mark all messages as read for an agent."""
+ return await self.database.mark_messages_read(team_id, agent_node_id)
+
+
+# Singleton instance
+_service: Optional[AgentTeamService] = None
+
+
+def get_agent_team_service() -> AgentTeamService:
+ """Get the singleton AgentTeamService instance."""
+ global _service
+ if _service is None:
+ raise RuntimeError("AgentTeamService not initialized. Call init_agent_team_service first.")
+ return _service
+
+
+def init_agent_team_service(database: Database, broadcaster=None) -> AgentTeamService:
+ """Initialize the singleton AgentTeamService."""
+ global _service
+ _service = AgentTeamService(database, broadcaster)
+ return _service
diff --git a/server/services/ai.py b/server/services/ai.py
index 97940e7c..3a1ad398 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2917,6 +2917,49 @@ class AIService:
return TaskManagerSchema
+ # Twitter Send tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterSend':
+ class TwitterSendSchema(BaseModel):
+ """Post tweets, replies, retweets, and likes on Twitter/X."""
+ action: str = Field(
+ default="tweet",
+ description="Action: tweet, reply, retweet, like, unlike, delete"
+ )
+ text: Optional[str] = Field(
+ default=None,
+ description="Tweet text (max 280 chars). Required for tweet/reply."
+ )
+ tweet_id: Optional[str] = Field(
+ default=None,
+ description="Tweet ID for reply/retweet/like/unlike/delete actions."
+ )
+ reply_to_id: Optional[str] = Field(
+ default=None,
+ description="Tweet ID to reply to (alias for tweet_id when action=reply)."
+ )
+
+ return TwitterSendSchema
+
+ # Twitter Search tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterSearch':
+ class TwitterSearchSchema(BaseModel):
+ """Search recent tweets on Twitter/X."""
+ query: str = Field(description="Search query (supports X search operators)")
+ max_results: int = Field(default=10, description="Max results (10-100)")
+
+ return TwitterSearchSchema
+
+ # Twitter User tool schema (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterUser':
+ class TwitterUserSchema(BaseModel):
+ """Look up Twitter/X user profiles and social connections."""
+ operation: str = Field(default="me", description="Operation: me, by_username, by_id, followers, following")
+ username: Optional[str] = Field(default=None, description="Twitter username (without @) for by_username")
+ user_id: Optional[str] = Field(default=None, description="Twitter user ID for by_id/followers/following")
+ max_results: int = Field(default=100, description="Max results for followers/following (1-1000)")
+
+ return TwitterUserSchema
+
# 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/compaction.py b/server/services/compaction.py
index 443709f6..5a3ffb43 100644
--- a/server/services/compaction.py
+++ b/server/services/compaction.py
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
from typing import Dict, Any, Optional, TYPE_CHECKING
from core.logging import get_logger
+from services.pricing import get_pricing_service
if TYPE_CHECKING:
from core.database import Database
@@ -92,20 +93,54 @@ class CompactionService:
return {"context_management": {"compact_threshold": threshold or self._config.threshold}}
async def track(self, session_id: str, node_id: str, provider: str, model: str, usage: Dict[str, int]) -> Dict[str, Any]:
- """Track token usage and return compaction status."""
- await self._db.save_token_metric({"session_id": session_id, "node_id": node_id, "provider": provider, "model": model, **usage})
+ """Track token usage and cost, return compaction status."""
+ # Calculate cost using PricingService
+ pricing_service = get_pricing_service()
+ cost = pricing_service.calculate_cost(
+ provider=provider,
+ model=model,
+ input_tokens=usage.get("input_tokens", 0),
+ output_tokens=usage.get("output_tokens", 0),
+ cache_read_tokens=usage.get("cache_read_tokens", 0),
+ cache_creation_tokens=usage.get("cache_creation_tokens", 0),
+ reasoning_tokens=usage.get("reasoning_tokens", 0)
+ )
+
+ # Save token metric with cost fields
+ await self._db.save_token_metric({
+ "session_id": session_id,
+ "node_id": node_id,
+ "provider": provider,
+ "model": model,
+ **usage,
+ "input_cost": cost["input_cost"],
+ "output_cost": cost["output_cost"],
+ "cache_cost": cost["cache_cost"],
+ "total_cost": cost["total_cost"]
+ })
state = await self._db.get_or_create_session_token_state(session_id)
new_total = state["cumulative_total"] + usage.get("total_tokens", 0)
+ new_total_cost = state.get("cumulative_total_cost", 0.0) + cost["total_cost"]
+ # Update cumulative state with cost
await self._db.update_session_token_state(session_id, {
"cumulative_input_tokens": state["cumulative_input_tokens"] + usage.get("input_tokens", 0),
"cumulative_output_tokens": state["cumulative_output_tokens"] + usage.get("output_tokens", 0),
- "cumulative_total": new_total
+ "cumulative_total": new_total,
+ "cumulative_input_cost": state.get("cumulative_input_cost", 0.0) + cost["input_cost"],
+ "cumulative_output_cost": state.get("cumulative_output_cost", 0.0) + cost["output_cost"],
+ "cumulative_total_cost": new_total_cost
})
threshold = state.get("custom_threshold") or self._config.threshold
- return {"total": new_total, "threshold": threshold, "needs_compaction": self._config.enabled and new_total >= threshold}
+ return {
+ "total": new_total,
+ "total_cost": new_total_cost,
+ "cost": cost,
+ "threshold": threshold,
+ "needs_compaction": self._config.enabled and new_total >= threshold
+ }
async def record(self, session_id: str, node_id: str, provider: str, model: str, tokens_before: int, tokens_after: int, summary: Optional[str] = None) -> None:
"""Record compaction event after native API handles it."""
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index 5e6a3eaa..908d5ab1 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -110,6 +110,11 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {
event_type='task_completed',
display_name='Task Completed'
),
+ 'twitterReceive': TriggerConfig(
+ node_type='twitterReceive',
+ event_type='twitter_event_received',
+ display_name='Twitter Event'
+ ),
# Future triggers - just add to registry:
# 'emailTrigger': TriggerConfig('emailTrigger', 'email_received', 'Email'),
# 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),
@@ -336,12 +341,48 @@ def build_task_completed_filter(params: Dict) -> Callable[[Dict], bool]:
return matches
+def build_twitter_filter(params: Dict) -> Callable[[Dict], bool]:
+ """Build filter function for Twitter events.
+
+ Filters by:
+ - trigger_type: 'mentions', 'search', 'user_timeline'
+ - search_query: Search query for 'search' trigger type
+ - user_id: User ID for 'user_timeline' trigger type
+
+ Args:
+ params: Node parameters
+
+ Returns:
+ Filter function that checks if event matches criteria
+ """
+ trigger_type = params.get('trigger_type', 'mentions')
+ search_query = params.get('search_query', '')
+ user_id = params.get('user_id', '')
+
+ def matches(data: Dict) -> bool:
+ event_type = data.get('trigger_type', '')
+ if trigger_type != 'all' and event_type != trigger_type:
+ return False
+ if trigger_type == 'search' and search_query:
+ # Check if search query matches
+ event_query = data.get('query', '')
+ if search_query.lower() not in event_query.lower():
+ return False
+ if trigger_type == 'user_timeline' and user_id:
+ if data.get('user_id') != user_id:
+ return False
+ return True
+
+ return matches
+
+
# Registry of filter builders per trigger type
FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'whatsappReceive': build_whatsapp_filter,
'webhookTrigger': build_webhook_filter,
'chatTrigger': build_chat_filter,
'taskTrigger': build_task_completed_filter,
+ 'twitterReceive': build_twitter_filter,
}
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index b5c28a7a..248911d8 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -57,6 +57,7 @@ from .utility import (
handle_cron_scheduler,
handle_timer,
handle_console,
+ handle_team_monitor,
)
# WhatsApp handlers
@@ -65,6 +66,13 @@ from .whatsapp import (
handle_whatsapp_db,
)
+# Twitter handlers
+from .twitter import (
+ handle_twitter_send,
+ handle_twitter_search,
+ handle_twitter_user,
+)
+
# Social handlers (unified messaging)
from .social import (
handle_social_receive,
@@ -115,9 +123,14 @@ __all__ = [
'handle_cron_scheduler',
'handle_timer',
'handle_console',
+ 'handle_team_monitor',
# WhatsApp
'handle_whatsapp_send',
'handle_whatsapp_db',
+ # Twitter
+ 'handle_twitter_send',
+ 'handle_twitter_search',
+ 'handle_twitter_user',
# Social
'handle_social_receive',
'handle_social_send',
diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.py
index 413c59b3..1ef9667b 100644
--- a/server/services/handlers/ai.py
+++ b/server/services/handlers/ai.py
@@ -10,6 +10,9 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+# Team lead types that can create teams
+TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}
+
async def _collect_agent_connections(
node_id: str,
@@ -302,6 +305,50 @@ async def _collect_agent_connections(
return memory_data, skill_data, tool_data, input_data, task_data
+async def _collect_teammate_connections(
+ node_id: str,
+ context: Dict[str, Any],
+ database: "Database"
+) -> List[Dict[str, Any]]:
+ """Collect agents connected via input-teammates handle for team mode.
+
+ Args:
+ node_id: The team lead node ID
+ context: Execution context with nodes, edges
+ database: Database instance
+
+ Returns:
+ List of teammate node info dicts
+ """
+ nodes = context.get('nodes', [])
+ edges = context.get('edges', [])
+ teammates = []
+
+ for edge in edges:
+ if edge.get('target') != node_id or edge.get('targetHandle') != 'input-teammates':
+ continue
+
+ source_id = edge.get('source')
+ source_node = next((n for n in nodes if n.get('id') == source_id), None)
+ if not source_node:
+ continue
+
+ node_type = source_node.get('type', '')
+ if node_type not in AI_AGENT_TYPES:
+ continue
+
+ params = await database.get_node_parameters(source_id) or {}
+ teammates.append({
+ 'node_id': source_id,
+ 'node_type': node_type,
+ 'label': source_node.get('data', {}).get('label', node_type),
+ 'parameters': params
+ })
+ logger.debug(f"[Teams] Found teammate: {node_type} ({source_id})")
+
+ return teammates
+
+
def _format_task_context(task_data: Dict[str, Any]) -> str:
"""Format task completion data as context for the agent.
@@ -485,7 +532,24 @@ async def handle_chat_agent(
from services.status_broadcaster import get_status_broadcaster
broadcaster = get_status_broadcaster()
- # Execute Chat Agent with memory, skills and tools
+ # Team mode detection for orchestrator_agent and ai_employee nodes
+ # Teammates connected via input-teammates become delegation tools
+ if node_type in TEAM_LEAD_TYPES:
+ teammates = await _collect_teammate_connections(node_id, context, database)
+
+ if teammates:
+ # Add teammates as delegation tools (they become delegate_to_* tools)
+ tool_data = tool_data or []
+ for tm in teammates:
+ tool_data.append({
+ 'node_id': tm['node_id'],
+ 'node_type': tm['node_type'],
+ 'label': tm['label'],
+ 'parameters': tm.get('parameters', {}),
+ })
+ logger.info(f"[Teams] Added {len(teammates)} teammates as delegation tools")
+
+ # Standard execution (no team mode)
return await ai_service.execute_chat_agent(
node_id,
parameters,
@@ -494,7 +558,7 @@ async def handle_chat_agent(
tool_data=tool_data if tool_data else None,
broadcaster=broadcaster,
workflow_id=workflow_id,
- context=context # Pass context for nested agent delegation
+ context=context
)
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 4fa38973..f151720e 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -107,6 +107,18 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
if node_type == 'whatsappDb':
return await _execute_whatsapp_db(tool_args, config.get('parameters', {}))
+ # Twitter Send (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterSend':
+ return await _execute_twitter_send(tool_args, config.get('parameters', {}))
+
+ # Twitter Search (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterSearch':
+ return await _execute_twitter_search(tool_args, config.get('parameters', {}))
+
+ # Twitter User (dual-purpose: workflow node + AI tool)
+ if node_type == 'twitterUser':
+ return await _execute_twitter_user(tool_args, config.get('parameters', {}))
+
# Android toolkit - routes to connected service nodes
if node_type == 'androidTool':
return await _execute_android_toolkit(tool_args, config)
@@ -1118,6 +1130,78 @@ async def _execute_nearby_places(args: Dict[str, Any],
return {"error": f"Nearby places search failed: {str(e)}"}
+async def _execute_twitter_send(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter send action via XDK SDK.
+
+ Args:
+ args: LLM-provided arguments (action, text, tweet_id, reply_to_id)
+ node_params: Node parameters
+
+ Returns:
+ Twitter API result
+ """
+ from services.handlers.twitter import handle_twitter_send
+
+ parameters = {**node_params, **args}
+ # Handle reply_to_id alias
+ if args.get('reply_to_id') and not args.get('tweet_id'):
+ parameters['tweet_id'] = args['reply_to_id']
+
+ return await handle_twitter_send(
+ node_id="tool_twitter_send",
+ node_type="twitterSend",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_twitter_search(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter search via XDK SDK.
+
+ Args:
+ args: LLM-provided arguments (query, max_results)
+ node_params: Node parameters
+
+ Returns:
+ Search results
+ """
+ from services.handlers.twitter import handle_twitter_search
+
+ parameters = {**node_params, **args}
+
+ return await handle_twitter_search(
+ node_id="tool_twitter_search",
+ node_type="twitterSearch",
+ parameters=parameters,
+ context={}
+ )
+
+
+async def _execute_twitter_user(args: Dict[str, Any],
+ node_params: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Twitter user lookup via XDK SDK.
+
+ Args:
+ args: LLM-provided arguments (operation, username, user_id, max_results)
+ node_params: Node parameters
+
+ Returns:
+ User data
+ """
+ from services.handlers.twitter import handle_twitter_user
+
+ parameters = {**node_params, **args}
+
+ return await handle_twitter_user(
+ node_id="tool_twitter_user",
+ node_type="twitterUser",
+ 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/handlers/twitter.py b/server/services/handlers/twitter.py
new file mode 100644
index 00000000..e51c3a34
--- /dev/null
+++ b/server/services/handlers/twitter.py
@@ -0,0 +1,297 @@
+"""Twitter/X node handlers using official XDK SDK."""
+
+import time
+from typing import Dict, Any
+from xdk import Client
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+async def _get_twitter_client() -> Client:
+ """Get authenticated Twitter client from stored OAuth 2.0 credentials."""
+ # Import inside function to avoid circular import
+ from core.container import container
+ auth_service = container.auth_service()
+ access_token = await auth_service.get_api_key("twitter_access_token")
+ if not access_token:
+ raise ValueError("Twitter not connected. Please authenticate via Credentials.")
+ # Use access_token for OAuth 2.0 user token (not bearer_token which is app-only)
+ return Client(access_token=access_token)
+
+
+async def _get_my_user_id(client: Client) -> str:
+ """Get the authenticated user's ID."""
+ response = client.users.get_me()
+ # response.data is a dict with 'id', 'username', 'name' keys
+ return response.data["id"]
+
+
+async def handle_twitter_send(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Twitter send actions: tweet, reply, retweet, like, unlike, delete."""
+ start_time = time.time()
+ action = parameters.get('action', 'tweet')
+
+ try:
+ client = await _get_twitter_client()
+
+ match action:
+ case 'tweet':
+ text = parameters.get('text', '')
+ if not text:
+ raise ValueError("Tweet text is required")
+ # XDK API: client.posts.create(body={"text": "..."})
+ payload = {"text": text[:280]}
+ result = client.posts.create(body=payload)
+ return _success(_format_response(result), "tweet_sent", start_time)
+
+ case 'reply':
+ text = parameters.get('text', '')
+ reply_to = parameters.get('reply_to_id')
+ if not text or not reply_to:
+ raise ValueError("Text and reply_to_id are required")
+ # XDK API: reply uses nested reply object
+ payload = {
+ "text": text[:280],
+ "reply": {"in_reply_to_tweet_id": reply_to}
+ }
+ result = client.posts.create(body=payload)
+ return _success(_format_response(result), "reply_sent", start_time)
+
+ case 'retweet':
+ tweet_id = parameters.get('tweet_id')
+ if not tweet_id:
+ raise ValueError("tweet_id is required")
+ user_id = await _get_my_user_id(client)
+ # XDK API: client.users.repost_post(user_id, body={"tweet_id": "..."})
+ payload = {"tweet_id": tweet_id}
+ result = client.users.repost_post(user_id, body=payload)
+ return _success(_format_response(result), "retweeted", start_time)
+
+ case 'like':
+ tweet_id = parameters.get('tweet_id')
+ if not tweet_id:
+ raise ValueError("tweet_id is required")
+ user_id = await _get_my_user_id(client)
+ # XDK API: client.users.like_post(user_id, body={"tweet_id": "..."})
+ payload = {"tweet_id": tweet_id}
+ result = client.users.like_post(user_id, body=payload)
+ return _success(_format_response(result), "liked", start_time)
+
+ case 'unlike':
+ tweet_id = parameters.get('tweet_id')
+ if not tweet_id:
+ raise ValueError("tweet_id is required")
+ user_id = await _get_my_user_id(client)
+ # XDK API: client.users.unlike_post(user_id, tweet_id=post_id)
+ result = client.users.unlike_post(user_id, tweet_id=tweet_id)
+ return _success(_format_response(result), "unliked", start_time)
+
+ case 'delete':
+ tweet_id = parameters.get('tweet_id')
+ if not tweet_id:
+ raise ValueError("tweet_id is required")
+ # XDK API: client.posts.delete(post_id)
+ result = client.posts.delete(tweet_id)
+ return _success(_format_response(result), "deleted", start_time)
+
+ case _:
+ raise ValueError(f"Unknown action: {action}")
+
+ except Exception as e:
+ logger.error(f"Twitter send error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+async def handle_twitter_search(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Twitter search operations."""
+ start_time = time.time()
+
+ try:
+ client = await _get_twitter_client()
+ query = parameters.get('query', '')
+ max_results = min(parameters.get('max_results', 10), 100)
+
+ if not query:
+ raise ValueError("Search query is required")
+
+ tweets = []
+ # XDK API: client.posts.search_recent(query=..., max_results=..., tweet_fields=[...])
+ for page in client.posts.search_recent(
+ query=query,
+ max_results=max_results,
+ tweet_fields=["author_id", "created_at"]
+ ):
+ page_data = getattr(page, 'data', []) or []
+ tweets.extend([_format_tweet(t) for t in page_data])
+ break # Only first page
+
+ return {
+ "success": True,
+ "result": {"tweets": tweets, "count": len(tweets), "query": query},
+ "execution_time": time.time() - start_time
+ }
+
+ except Exception as e:
+ logger.error(f"Twitter search error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+async def handle_twitter_user(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Twitter user lookup operations."""
+ start_time = time.time()
+ operation = parameters.get('operation', 'me')
+
+ try:
+ client = await _get_twitter_client()
+
+ match operation:
+ case 'me':
+ # XDK API: client.users.get_me(user_fields=[...])
+ result = client.users.get_me(user_fields=["created_at", "description"])
+ return _success(_format_user_data(result.data), "user", start_time)
+
+ case 'by_username':
+ username = parameters.get('username')
+ if not username:
+ raise ValueError("Username is required")
+ # XDK API: client.users.get_by_usernames(usernames=[...], user_fields=[...])
+ result = client.users.get_by_usernames(
+ usernames=[username],
+ user_fields=["description", "created_at"]
+ )
+ users = getattr(result, 'data', []) or []
+ if not users:
+ raise ValueError(f"User @{username} not found")
+ return _success(_format_user_data(users[0]), "user", start_time)
+
+ case 'by_id':
+ user_id = parameters.get('user_id')
+ if not user_id:
+ raise ValueError("User ID is required")
+ # XDK API: client.users.get_by_ids works similar
+ result = client.users.get_by_ids(
+ ids=[user_id],
+ user_fields=["description", "created_at"]
+ )
+ users = getattr(result, 'data', []) or []
+ if not users:
+ raise ValueError(f"User ID {user_id} not found")
+ return _success(_format_user_data(users[0]), "user", start_time)
+
+ case 'followers':
+ user_id = parameters.get('user_id')
+ if not user_id:
+ user_id = await _get_my_user_id(client)
+ max_results = min(parameters.get('max_results', 100), 1000)
+ users = []
+ # XDK API: client.users.get_followers(user_id, max_results=..., user_fields=[...])
+ for page in client.users.get_followers(
+ user_id,
+ max_results=max_results,
+ user_fields=["created_at"]
+ ):
+ page_data = getattr(page, 'data', []) or []
+ users.extend([_format_user_data(u) for u in page_data])
+ break # Only first page
+ return _success({"users": users, "count": len(users)}, "followers", start_time)
+
+ case 'following':
+ user_id = parameters.get('user_id')
+ if not user_id:
+ user_id = await _get_my_user_id(client)
+ max_results = min(parameters.get('max_results', 100), 1000)
+ users = []
+ # XDK API: client.users.get_following(user_id, max_results=..., user_fields=[...])
+ for page in client.users.get_following(
+ user_id,
+ max_results=max_results,
+ user_fields=["created_at"]
+ ):
+ page_data = getattr(page, 'data', []) or []
+ users.extend([_format_user_data(u) for u in page_data])
+ break # Only first page
+ return _success({"users": users, "count": len(users)}, "following", start_time)
+
+ case _:
+ raise ValueError(f"Unknown operation: {operation}")
+
+ except Exception as e:
+ logger.error(f"Twitter user error: {e}")
+ return {"success": False, "error": str(e), "execution_time": time.time() - start_time}
+
+
+def _success(data: Any, action: str, start_time: float) -> Dict[str, Any]:
+ """Build success response."""
+ return {
+ "success": True,
+ "result": data if isinstance(data, dict) else {"data": data, "action": action},
+ "execution_time": time.time() - start_time
+ }
+
+
+def _format_response(response) -> Dict[str, Any]:
+ """Format XDK response object to dict."""
+ if hasattr(response, 'data'):
+ data = response.data
+ if isinstance(data, dict):
+ return data
+ # Convert object attributes to dict
+ return {k: v for k, v in data.__dict__.items() if not k.startswith('_')} if hasattr(data, '__dict__') else {"data": str(data)}
+ return {"response": str(response)}
+
+
+def _format_tweet(tweet) -> Dict[str, Any]:
+ """Format tweet object/dict to dict."""
+ if isinstance(tweet, dict):
+ return {
+ "id": tweet.get("id"),
+ "text": tweet.get("text"),
+ "author_id": tweet.get("author_id"),
+ "created_at": str(tweet.get("created_at", "")),
+ }
+ return {
+ "id": getattr(tweet, 'id', None),
+ "text": getattr(tweet, 'text', None),
+ "author_id": getattr(tweet, 'author_id', None),
+ "created_at": str(getattr(tweet, 'created_at', '')),
+ }
+
+
+def _format_user_data(user) -> Dict[str, Any]:
+ """Format user object/dict to dict."""
+ if isinstance(user, dict):
+ return {
+ "id": user.get("id"),
+ "username": user.get("username"),
+ "name": user.get("name"),
+ "profile_image_url": user.get("profile_image_url"),
+ "verified": user.get("verified", False),
+ "description": user.get("description"),
+ "created_at": str(user.get("created_at", "")),
+ }
+ return {
+ "id": getattr(user, 'id', None),
+ "username": getattr(user, 'username', None),
+ "name": getattr(user, 'name', None),
+ "profile_image_url": getattr(user, 'profile_image_url', None),
+ "verified": getattr(user, 'verified', False),
+ "description": getattr(user, 'description', None),
+ "created_at": str(getattr(user, 'created_at', '')),
+ }
diff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.py
index 5c2aa0fe..9d353a5d 100644
--- a/server/services/handlers/utility.py
+++ b/server/services/handlers/utility.py
@@ -820,3 +820,94 @@ def _format_console_output(data: Any, format_type: str) -> str:
return json.dumps(data, indent=2, default=str, ensure_ascii=False)
case _:
return str(data)
+
+
+# =============================================================================
+# TEAM MONITOR HANDLER
+# =============================================================================
+
+async def handle_team_monitor(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle team monitor node - returns team status snapshot.
+
+ Args:
+ node_id: The node ID
+ node_type: The node type (teamMonitor)
+ parameters: Resolved parameters
+ context: Execution context with team_id from connected team node
+
+ Returns:
+ Execution result dict with team status
+ """
+ from services.agent_team import get_agent_team_service
+ start_time = time.time()
+
+ try:
+ # Get team_id from context (set by connected team lead node)
+ team_id = context.get('team_id')
+
+ # Try to get from connected node outputs
+ if not team_id:
+ outputs = context.get('outputs', {})
+ for output in outputs.values():
+ if isinstance(output, dict) and output.get('team_id'):
+ team_id = output.get('team_id')
+ break
+
+ if not team_id:
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "teamMonitor",
+ "result": {
+ "message": "No team connected",
+ "team_id": None,
+ "members": [],
+ "tasks": {"total": 0, "completed": 0, "active": 0, "pending": 0, "failed": 0},
+ "active_tasks": [],
+ "recent_events": []
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ team_service = get_agent_team_service()
+ status = await team_service.get_team_status(team_id)
+
+ max_history = parameters.get('maxHistoryItems', 50)
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "teamMonitor",
+ "result": {
+ "team_id": team_id,
+ "members": status.get('members', []),
+ "tasks": {
+ "total": status.get('task_count', 0),
+ "completed": status.get('completed_count', 0),
+ "active": status.get('active_count', 0),
+ "pending": status.get('pending_count', 0),
+ "failed": status.get('failed_count', 0)
+ },
+ "active_tasks": status.get('active_tasks', []),
+ "recent_events": status.get('recent_events', [])[-max_history:]
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ logger.error("[TeamMonitor] Failed", node_id=node_id, error=str(e))
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "teamMonitor",
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 518c993f..cd384da4 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -30,12 +30,13 @@ from services.handlers import (
handle_create_map, handle_add_locations, handle_nearby_places,
handle_text_generator, handle_file_handler,
handle_chat_send, handle_chat_history,
- handle_start, handle_cron_scheduler, handle_timer, handle_console,
+ handle_start, handle_cron_scheduler, handle_timer, handle_console, handle_team_monitor,
handle_whatsapp_send, handle_whatsapp_db,
handle_social_receive, handle_social_send,
handle_http_scraper, handle_file_downloader, handle_document_parser,
handle_text_chunker, handle_embedding_generator, handle_vector_store,
handle_task_manager,
+ handle_twitter_send, handle_twitter_search, handle_twitter_user,
)
if TYPE_CHECKING:
@@ -122,6 +123,7 @@ class NodeExecutor:
'consumer_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
'autonomous_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
'orchestrator_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
+ 'ai_employee': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
'simpleMemory': handle_simple_memory,
# Maps
'gmaps_create': partial(handle_create_map, maps_service=self.maps_service),
@@ -133,6 +135,10 @@ class NodeExecutor:
# WhatsApp
'whatsappSend': handle_whatsapp_send,
'whatsappDb': handle_whatsapp_db,
+ # Twitter/X
+ 'twitterSend': handle_twitter_send,
+ 'twitterSearch': handle_twitter_search,
+ 'twitterUser': handle_twitter_user,
# Social (unified messaging)
# Note: socialReceive handled in _dispatch with connected_outputs
'socialSend': handle_social_send,
@@ -150,6 +156,8 @@ class NodeExecutor:
'vectorStore': handle_vector_store,
# Task management
'taskManager': handle_task_manager,
+ # Team monitoring
+ 'teamMonitor': handle_team_monitor,
# Note: 'console' handled in _dispatch with connected_outputs
}
@@ -227,6 +235,12 @@ class NodeExecutor:
await self._output_store(session_id, node_id, "output_contact", output_data.get('contact', {}))
await self._output_store(session_id, node_id, "output_metadata", output_data.get('metadata', {}))
+ # Store with multiple keys for different handle IDs used by frontend components:
+ # - output_main: SquareNode, GenericNode, TriggerNode, StartNode
+ # - output_top: AIAgentNode (agents use top output handle)
+ # - output_0: backward compatibility
+ await self._output_store(session_id, node_id, "output_main", output_data)
+ await self._output_store(session_id, node_id, "output_top", output_data)
await self._output_store(session_id, node_id, "output_0", output_data)
return result
diff --git a/server/services/pricing.py b/server/services/pricing.py
new file mode 100644
index 00000000..ef6dc9ba
--- /dev/null
+++ b/server/services/pricing.py
@@ -0,0 +1,270 @@
+"""LLM pricing service for token cost calculation.
+
+Provides cost calculation for all supported LLM providers based on official pricing.
+Pricing is in USD per million tokens (MTok).
+"""
+
+from dataclasses import dataclass
+from typing import Dict, Optional
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+@dataclass
+class ModelPricing:
+ """Pricing for a specific model."""
+ input_per_mtok: float # USD per 1M input tokens
+ output_per_mtok: float # USD per 1M output tokens
+ cache_read_per_mtok: Optional[float] = None # USD per 1M cache read tokens (Anthropic)
+ reasoning_per_mtok: Optional[float] = None # USD per 1M reasoning tokens (OpenAI o-series)
+
+
+# Official pricing as of February 2026
+# Sources: openai.com/api/pricing, anthropic.com/pricing, ai.google.dev/pricing,
+# groq.com/pricing, cerebras.ai/pricing
+PRICING_REGISTRY: Dict[str, Dict[str, ModelPricing]] = {
+ 'openai': {
+ # GPT-5 series
+ 'gpt-5.2': ModelPricing(1.75, 14.00),
+ 'gpt-5.1': ModelPricing(1.25, 10.00),
+ 'gpt-5': ModelPricing(1.25, 10.00),
+ 'gpt-5-mini': ModelPricing(0.25, 2.00),
+ 'gpt-5-nano': ModelPricing(0.05, 0.40),
+ 'gpt-5-pro': ModelPricing(15.00, 120.00),
+ # O-series (reasoning models)
+ 'o3': ModelPricing(2.00, 8.00, reasoning_per_mtok=8.00),
+ 'o3-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),
+ 'o3-pro': ModelPricing(20.00, 80.00, reasoning_per_mtok=80.00),
+ 'o4-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),
+ 'o1': ModelPricing(15.00, 60.00, reasoning_per_mtok=60.00),
+ 'o1-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),
+ # GPT-4 series
+ 'gpt-4o': ModelPricing(2.50, 10.00),
+ 'gpt-4o-mini': ModelPricing(0.15, 0.60),
+ 'gpt-4.1': ModelPricing(2.00, 8.00),
+ 'gpt-4.1-mini': ModelPricing(0.40, 1.60),
+ 'gpt-4.1-nano': ModelPricing(0.10, 0.40),
+ 'gpt-4-turbo': ModelPricing(10.00, 30.00),
+ 'gpt-4': ModelPricing(30.00, 60.00),
+ # GPT-3.5
+ 'gpt-3.5-turbo': ModelPricing(0.50, 1.50),
+ # Default fallback
+ '_default': ModelPricing(2.50, 10.00),
+ },
+ 'anthropic': {
+ # Claude 4.x series
+ 'claude-opus-4.6': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),
+ 'claude-opus-4.5': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),
+ 'claude-opus-4.1': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),
+ 'claude-opus-4': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),
+ 'claude-sonnet-4.6': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-sonnet-4.5': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-sonnet-4': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-haiku-4.5': ModelPricing(1.00, 5.00, cache_read_per_mtok=0.10),
+ # Claude 3.x series (legacy)
+ 'claude-3-opus': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),
+ 'claude-3-5-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-3-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-3-haiku': ModelPricing(0.25, 1.25, cache_read_per_mtok=0.03),
+ 'claude-3.5-haiku': ModelPricing(0.80, 4.00, cache_read_per_mtok=0.08),
+ # Partial matches (for model names like claude-3-5-sonnet-20241022)
+ 'claude-opus': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),
+ 'claude-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ 'claude-haiku': ModelPricing(1.00, 5.00, cache_read_per_mtok=0.10),
+ # Default fallback
+ '_default': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),
+ },
+ 'gemini': {
+ # Gemini 3.x series
+ 'gemini-3-pro': ModelPricing(2.00, 12.00),
+ 'gemini-3-flash': ModelPricing(0.50, 3.00),
+ # Gemini 2.5 series
+ 'gemini-2.5-pro': ModelPricing(1.25, 10.00),
+ 'gemini-2.5-flash': ModelPricing(0.30, 2.50),
+ 'gemini-2.5-flash-lite': ModelPricing(0.10, 0.40),
+ # Gemini 2.0 series
+ 'gemini-2.0-flash': ModelPricing(0.10, 0.40),
+ 'gemini-2.0-flash-lite': ModelPricing(0.08, 0.30),
+ # Gemini 1.x series (legacy)
+ 'gemini-1.5-pro': ModelPricing(1.25, 5.00),
+ 'gemini-1.5-flash': ModelPricing(0.075, 0.30),
+ 'gemini-pro': ModelPricing(0.50, 1.50),
+ # Default fallback
+ '_default': ModelPricing(0.50, 2.50),
+ },
+ 'groq': {
+ # Llama 4 series
+ 'llama-4-scout': ModelPricing(0.11, 0.34),
+ 'llama-4-maverick': ModelPricing(0.20, 0.60),
+ # Llama 3.x series
+ 'llama-3.3-70b': ModelPricing(0.59, 0.79),
+ 'llama-3.1-70b': ModelPricing(0.59, 0.79),
+ 'llama-3.1-8b': ModelPricing(0.05, 0.08),
+ 'llama3-70b': ModelPricing(0.59, 0.79),
+ 'llama3-8b': ModelPricing(0.05, 0.08),
+ # Qwen series
+ 'qwen3-32b': ModelPricing(0.29, 0.59),
+ 'qwen-qwq-32b': ModelPricing(0.29, 0.59),
+ # Mixtral
+ 'mixtral-8x7b': ModelPricing(0.24, 0.24),
+ # GPT OSS
+ 'gpt-oss-20b': ModelPricing(0.075, 0.30),
+ 'gpt-oss-120b': ModelPricing(0.15, 0.60),
+ # Default fallback
+ '_default': ModelPricing(0.29, 0.59),
+ },
+ 'cerebras': {
+ # Llama series
+ 'llama-3.1-8b': ModelPricing(0.10, 0.10),
+ 'llama-3.1-70b': ModelPricing(0.60, 0.60),
+ 'llama-3.1-405b': ModelPricing(6.00, 12.00),
+ 'llama3.1-8b': ModelPricing(0.10, 0.10),
+ 'llama3.1-70b': ModelPricing(0.60, 0.60),
+ # Qwen
+ 'qwen-3-32b': ModelPricing(0.20, 0.20),
+ # Default fallback
+ '_default': ModelPricing(0.60, 0.60),
+ },
+ 'openrouter': {
+ # OpenRouter passes through provider pricing
+ # These are approximate defaults; actual cost depends on underlying provider
+ '_default': ModelPricing(1.00, 5.00),
+ },
+}
+
+
+class PricingService:
+ """Service for calculating LLM token costs."""
+
+ def __init__(self):
+ self._registry = PRICING_REGISTRY
+
+ def get_pricing(self, provider: str, model: str) -> ModelPricing:
+ """Get pricing for a specific model.
+
+ Uses partial matching: 'claude-3-5-sonnet-20241022' matches 'claude-3-5-sonnet'.
+ Falls back to '_default' if no match found.
+
+ Args:
+ provider: Provider name (openai, anthropic, gemini, groq, cerebras, openrouter)
+ model: Model name or ID
+
+ Returns:
+ ModelPricing with rates per million tokens
+ """
+ provider_lower = provider.lower()
+ model_lower = model.lower() if model else ''
+
+ provider_pricing = self._registry.get(provider_lower, {})
+
+ # Try exact match first
+ if model_lower in provider_pricing:
+ return provider_pricing[model_lower]
+
+ # Try partial match (model name starts with a known key)
+ for model_key, pricing in provider_pricing.items():
+ if model_key != '_default' and model_lower.startswith(model_key):
+ return pricing
+
+ # Try if any key is contained in the model name
+ for model_key, pricing in provider_pricing.items():
+ if model_key != '_default' and model_key in model_lower:
+ return pricing
+
+ # Fall back to provider default
+ default_pricing = provider_pricing.get('_default')
+ if default_pricing:
+ return default_pricing
+
+ # Ultimate fallback
+ logger.warning(f"[Pricing] No pricing found for {provider}/{model}, using global default")
+ return ModelPricing(1.00, 5.00)
+
+ def calculate_cost(
+ self,
+ provider: str,
+ model: str,
+ input_tokens: int,
+ output_tokens: int,
+ cache_read_tokens: int = 0,
+ cache_creation_tokens: int = 0,
+ reasoning_tokens: int = 0
+ ) -> Dict[str, float]:
+ """Calculate cost for token usage.
+
+ Args:
+ provider: LLM provider name
+ model: Model name/ID
+ input_tokens: Number of input tokens
+ output_tokens: Number of output tokens
+ cache_read_tokens: Number of cache read tokens (Anthropic)
+ cache_creation_tokens: Number of cache creation tokens (Anthropic)
+ reasoning_tokens: Number of reasoning tokens (OpenAI o-series)
+
+ Returns:
+ Dict with cost breakdown:
+ - input_cost: USD for input tokens
+ - output_cost: USD for output tokens
+ - cache_cost: USD for cache tokens
+ - reasoning_cost: USD for reasoning tokens
+ - total_cost: Total USD cost
+ """
+ pricing = self.get_pricing(provider, model)
+
+ # Calculate costs (prices are per 1M tokens)
+ input_cost = (input_tokens / 1_000_000) * pricing.input_per_mtok
+ output_cost = (output_tokens / 1_000_000) * pricing.output_per_mtok
+
+ # Cache costs (Anthropic pattern)
+ cache_cost = 0.0
+ if pricing.cache_read_per_mtok:
+ # Cache reads are discounted (typically 10% of input price)
+ cache_cost += (cache_read_tokens / 1_000_000) * pricing.cache_read_per_mtok
+ # Cache creation is charged at 1.25x output rate
+ cache_cost += (cache_creation_tokens / 1_000_000) * pricing.output_per_mtok * 1.25
+
+ # Reasoning costs (OpenAI o-series)
+ reasoning_cost = 0.0
+ if pricing.reasoning_per_mtok and reasoning_tokens > 0:
+ reasoning_cost = (reasoning_tokens / 1_000_000) * pricing.reasoning_per_mtok
+
+ total_cost = input_cost + output_cost + cache_cost + reasoning_cost
+
+ return {
+ 'input_cost': round(input_cost, 6),
+ 'output_cost': round(output_cost, 6),
+ 'cache_cost': round(cache_cost, 6),
+ 'reasoning_cost': round(reasoning_cost, 6),
+ 'total_cost': round(total_cost, 6),
+ }
+
+ def get_all_pricing(self) -> Dict[str, Dict[str, Dict[str, float]]]:
+ """Get all pricing data for frontend display.
+
+ Returns:
+ Nested dict: {provider: {model: {input, output, cache_read, reasoning}}}
+ """
+ result = {}
+ for provider, models in self._registry.items():
+ result[provider] = {}
+ for model, pricing in models.items():
+ result[provider][model] = {
+ 'input': pricing.input_per_mtok,
+ 'output': pricing.output_per_mtok,
+ 'cache_read': pricing.cache_read_per_mtok,
+ 'reasoning': pricing.reasoning_per_mtok,
+ }
+ return result
+
+
+# Singleton instance
+_service: Optional[PricingService] = None
+
+
+def get_pricing_service() -> PricingService:
+ """Get the singleton PricingService instance."""
+ global _service
+ if _service is None:
+ _service = PricingService()
+ return _service
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index e2a61a06..ba0570e3 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -41,6 +41,13 @@ class StatusBroadcaster:
"device_id": None,
"qr": None
},
+ "twitter": {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ "name": None,
+ "profile_image_url": None
+ },
"api_keys": {}, # provider -> validation status
"nodes": {}, # node_id -> node status
"variables": {}, # variable_name -> value
@@ -73,6 +80,9 @@ class StatusBroadcaster:
# This ensures client sees actual connection state (especially after auto-connect)
await self._refresh_whatsapp_status()
+ # Fetch Twitter status from stored OAuth tokens
+ await self._refresh_twitter_status()
+
# Auto-reconnect Android relay if there's a stored session
await self._auto_reconnect_android_relay()
@@ -228,6 +238,56 @@ class StatusBroadcaster:
# Don't fail client connection if WhatsApp service is down
logger.debug(f"[StatusBroadcaster] Could not refresh WhatsApp status: {e}")
+ async def _refresh_twitter_status(self):
+ """Fetch Twitter status from stored OAuth tokens in database.
+
+ Called on client connect to check if user is authenticated with Twitter.
+ """
+ try:
+ from core.container import container
+ auth_service = container.auth_service()
+
+ # Check for stored access token
+ access_token = await auth_service.get_api_key("twitter_access_token")
+ if not access_token:
+ self._status["twitter"] = {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ "name": None,
+ "profile_image_url": None
+ }
+ return
+
+ # Get stored user info
+ user_info_str = await auth_service.get_api_key("twitter_user_info")
+ if user_info_str:
+ # Format: "user_id:username:name"
+ parts = user_info_str.split(":", 2)
+ user_id = parts[0] if len(parts) > 0 else None
+ username = parts[1] if len(parts) > 1 else None
+ name = parts[2] if len(parts) > 2 else None
+
+ self._status["twitter"] = {
+ "connected": True,
+ "username": username,
+ "user_id": user_id,
+ "name": name,
+ "profile_image_url": None # Could fetch fresh if needed
+ }
+ logger.debug(f"[StatusBroadcaster] Twitter status: connected as @{username}")
+ else:
+ # Has token but no user info - still connected
+ self._status["twitter"] = {
+ "connected": True,
+ "username": None,
+ "user_id": None,
+ "name": None,
+ "profile_image_url": None
+ }
+ except Exception as e:
+ logger.debug(f"[StatusBroadcaster] Could not refresh Twitter status: {e}")
+
async def _auto_reconnect_android_relay(self):
"""Auto-reconnect to Android relay if there's a stored pairing session.
@@ -755,6 +815,25 @@ class StatusBroadcaster:
"type": "terminal_logs_cleared"
})
+ # =========================================================================
+ # Agent Team Updates
+ # =========================================================================
+
+ async def broadcast_team_event(self, team_id: str, event_type: str, data: Dict[str, Any]):
+ """Broadcast a team-related event to all connected clients.
+
+ Args:
+ team_id: The team ID
+ event_type: Event type (team_created, task_added, task_claimed, etc.)
+ data: Event data
+ """
+ await self.broadcast({
+ "type": "team_event",
+ "team_id": team_id,
+ "event_type": event_type,
+ "data": data
+ })
+
# =========================================================================
# Generic Updates
# =========================================================================
diff --git a/server/services/twitter_oauth.py b/server/services/twitter_oauth.py
new file mode 100644
index 00000000..e348bac6
--- /dev/null
+++ b/server/services/twitter_oauth.py
@@ -0,0 +1,410 @@
+"""
+Twitter/X OAuth 2.0 with PKCE - Browser-based login flow for X API v2.
+
+Based on official X API documentation:
+- Authorization URL: https://x.com/i/oauth2/authorize
+- Token URL: https://api.x.com/2/oauth2/token
+- Docs: https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code
+
+Access tokens expire in 2 hours by default. Use offline.access scope for refresh tokens.
+Authorization codes expire in 30 seconds.
+"""
+
+import base64
+import hashlib
+import secrets
+import time
+from typing import Any, Dict, Optional
+from urllib.parse import urlencode
+
+import httpx
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# X API OAuth 2.0 endpoints (updated URLs per latest docs)
+AUTHORIZATION_URL = "https://x.com/i/oauth2/authorize"
+TOKEN_URL = "https://api.x.com/2/oauth2/token"
+REVOKE_URL = "https://api.x.com/2/oauth2/revoke"
+USER_INFO_URL = "https://api.x.com/2/users/me"
+
+# Required scopes for full Twitter integration
+# See: https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code
+DEFAULT_SCOPES = [
+ "tweet.read", # Read tweets
+ "tweet.write", # Post tweets
+ "users.read", # User lookup
+ "follows.read", # Read followers/following
+ "like.read", # Read likes
+ "like.write", # Like/unlike tweets
+ "offline.access", # Enable refresh tokens (access tokens expire in 2 hours)
+]
+
+# In-memory store for PKCE state (production should use Redis/database)
+_oauth_states: Dict[str, Dict[str, Any]] = {}
+
+
+def _generate_code_verifier() -> str:
+ """
+ Generate a cryptographically random code verifier (43-128 chars).
+ Per RFC 7636, must be 43-128 characters from [A-Z, a-z, 0-9, -, ., _, ~].
+ """
+ # Generate 96 random bytes, encode to base64url (128 chars after stripping padding)
+ random_bytes = secrets.token_bytes(96)
+ verifier = base64.urlsafe_b64encode(random_bytes).rstrip(b"=").decode("ascii")
+ return verifier[:128]
+
+
+def _generate_code_challenge(code_verifier: str) -> str:
+ """
+ Generate S256 code challenge from verifier.
+ challenge = BASE64URL(SHA256(code_verifier))
+ """
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+ return challenge
+
+
+def _generate_state() -> str:
+ """Generate random state parameter for CSRF protection (up to 500 chars per X docs)."""
+ return secrets.token_urlsafe(32)
+
+
+class TwitterOAuth:
+ """
+ Twitter/X OAuth 2.0 with PKCE flow implementation.
+
+ Usage:
+ oauth = TwitterOAuth(client_id="...", redirect_uri="http://localhost:3010/api/twitter/callback")
+
+ # Step 1: Generate authorization URL
+ auth_data = oauth.generate_authorization_url()
+ # Redirect user to auth_data["url"]
+
+ # Step 2: Handle callback and exchange code
+ tokens = await oauth.exchange_code(code="...", state="...")
+
+ # Step 3: Use access_token for API calls
+ user_info = await oauth.get_user_info(tokens["access_token"])
+ """
+
+ def __init__(
+ self,
+ client_id: str,
+ client_secret: Optional[str] = None,
+ redirect_uri: str = "http://localhost:3010/api/twitter/callback",
+ scopes: Optional[list] = None,
+ ):
+ """
+ Initialize Twitter OAuth client.
+
+ Args:
+ client_id: Twitter OAuth 2.0 Client ID (from Developer Portal)
+ client_secret: Client Secret (required for confidential clients, optional for public clients with PKCE)
+ redirect_uri: OAuth callback URL (must match Developer Portal settings exactly)
+ scopes: List of OAuth scopes (defaults to DEFAULT_SCOPES)
+ """
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.redirect_uri = redirect_uri
+ self.scopes = scopes or DEFAULT_SCOPES
+
+ def generate_authorization_url(self) -> Dict[str, str]:
+ """
+ Generate OAuth authorization URL with PKCE parameters.
+
+ Returns:
+ Dict with:
+ - url: Authorization URL to redirect user to
+ - state: State parameter (for verification in callback)
+ - code_verifier: PKCE code verifier (save for token exchange)
+ """
+ state = _generate_state()
+ code_verifier = _generate_code_verifier()
+ code_challenge = _generate_code_challenge(code_verifier)
+
+ # Store state for verification (with expiry tracking)
+ _oauth_states[state] = {
+ "code_verifier": code_verifier,
+ "created_at": time.time(),
+ }
+
+ params = {
+ "response_type": "code",
+ "client_id": self.client_id,
+ "redirect_uri": self.redirect_uri,
+ "scope": " ".join(self.scopes),
+ "state": state,
+ "code_challenge": code_challenge,
+ "code_challenge_method": "S256",
+ }
+
+ authorization_url = f"{AUTHORIZATION_URL}?{urlencode(params)}"
+
+ logger.info("Generated Twitter OAuth authorization URL", state=state[:8])
+
+ return {
+ "url": authorization_url,
+ "state": state,
+ "code_verifier": code_verifier,
+ }
+
+ async def exchange_code(self, code: str, state: str) -> Dict[str, Any]:
+ """
+ Exchange authorization code for access token.
+
+ Note: Authorization codes expire in 30 seconds per X docs.
+
+ Args:
+ code: Authorization code from callback
+ state: State parameter for verification
+
+ Returns:
+ Dict with:
+ - success: True/False
+ - access_token: Bearer token for API calls (expires in 2 hours)
+ - refresh_token: Token for refreshing access (if offline.access scope)
+ - expires_in: Token expiry in seconds
+ - scope: Granted scopes
+ """
+ # Verify state and get code_verifier
+ oauth_state = _oauth_states.pop(state, None)
+ if not oauth_state:
+ logger.error("Invalid or expired OAuth state", state=state[:8] if state else "None")
+ return {"success": False, "error": "Invalid or expired state"}
+
+ code_verifier = oauth_state["code_verifier"]
+
+ # Prepare token request body
+ data = {
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": self.redirect_uri,
+ "code_verifier": code_verifier,
+ }
+
+ # Authentication: Basic auth for confidential clients, client_id in body for public clients
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+
+ if self.client_secret:
+ # Confidential client: use Basic auth
+ credentials = base64.b64encode(
+ f"{self.client_id}:{self.client_secret}".encode()
+ ).decode()
+ headers["Authorization"] = f"Basic {credentials}"
+ else:
+ # Public client: include client_id in body
+ data["client_id"] = self.client_id
+
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ response = await client.post(
+ TOKEN_URL,
+ data=data,
+ headers=headers,
+ )
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ logger.error(
+ "Token exchange failed",
+ status=response.status_code,
+ error=error_data,
+ )
+ return {
+ "success": False,
+ "error": error_data.get("error_description", error_data.get("error", "Token exchange failed")),
+ }
+
+ token_data = response.json()
+ logger.info("Twitter OAuth token exchange successful")
+
+ return {
+ "success": True,
+ "access_token": token_data.get("access_token"),
+ "refresh_token": token_data.get("refresh_token"),
+ "expires_in": token_data.get("expires_in"),
+ "scope": token_data.get("scope"),
+ "token_type": token_data.get("token_type", "Bearer"),
+ }
+
+ except httpx.HTTPError as e:
+ logger.error("HTTP error during token exchange", error=str(e))
+ return {"success": False, "error": str(e)}
+
+ async def refresh_access_token(self, refresh_token: str) -> Dict[str, Any]:
+ """
+ Refresh an expired access token.
+
+ Args:
+ refresh_token: The refresh token from previous authorization
+
+ Returns:
+ Dict with new access_token, refresh_token, expires_in
+ """
+ data = {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ }
+
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+
+ if self.client_secret:
+ credentials = base64.b64encode(
+ f"{self.client_id}:{self.client_secret}".encode()
+ ).decode()
+ headers["Authorization"] = f"Basic {credentials}"
+ else:
+ data["client_id"] = self.client_id
+
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ response = await client.post(
+ TOKEN_URL,
+ data=data,
+ headers=headers,
+ )
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ logger.error(
+ "Token refresh failed",
+ status=response.status_code,
+ error=error_data,
+ )
+ return {
+ "success": False,
+ "error": error_data.get("error_description", "Token refresh failed"),
+ }
+
+ token_data = response.json()
+ logger.info("Twitter token refresh successful")
+
+ return {
+ "success": True,
+ "access_token": token_data.get("access_token"),
+ "refresh_token": token_data.get("refresh_token"),
+ "expires_in": token_data.get("expires_in"),
+ "scope": token_data.get("scope"),
+ }
+
+ except httpx.HTTPError as e:
+ logger.error("HTTP error during token refresh", error=str(e))
+ return {"success": False, "error": str(e)}
+
+ async def revoke_token(self, token: str, token_type: str = "access_token") -> Dict[str, Any]:
+ """
+ Revoke an access or refresh token.
+
+ Args:
+ token: The token to revoke
+ token_type: 'access_token' or 'refresh_token'
+
+ Returns:
+ Dict with success status
+ """
+ data = {
+ "token": token,
+ "token_type_hint": token_type,
+ }
+
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+
+ if self.client_secret:
+ credentials = base64.b64encode(
+ f"{self.client_id}:{self.client_secret}".encode()
+ ).decode()
+ headers["Authorization"] = f"Basic {credentials}"
+ else:
+ data["client_id"] = self.client_id
+
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ response = await client.post(
+ REVOKE_URL,
+ data=data,
+ headers=headers,
+ )
+
+ # 200 = success, even if token was already revoked
+ if response.status_code == 200:
+ logger.info("Twitter token revoked successfully")
+ return {"success": True}
+ else:
+ error_data = response.json() if response.text else {}
+ return {
+ "success": False,
+ "error": error_data.get("error_description", "Revocation failed"),
+ }
+
+ except httpx.HTTPError as e:
+ logger.error("HTTP error during token revocation", error=str(e))
+ return {"success": False, "error": str(e)}
+
+ async def get_user_info(self, access_token: str) -> Dict[str, Any]:
+ """
+ Get authenticated user information.
+
+ Args:
+ access_token: Valid Twitter access token
+
+ Returns:
+ Dict with user id, username, name, profile_image_url, verified
+ """
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ response = await client.get(
+ USER_INFO_URL,
+ params={"user.fields": "id,name,username,profile_image_url,verified"},
+ headers={"Authorization": f"Bearer {access_token}"},
+ )
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ error_detail = error_data.get("detail") or error_data.get("title", "Failed to get user info")
+ return {
+ "success": False,
+ "error": error_detail,
+ }
+
+ data = response.json()
+ user = data.get("data", {})
+
+ return {
+ "success": True,
+ "id": user.get("id"),
+ "username": user.get("username"),
+ "name": user.get("name"),
+ "profile_image_url": user.get("profile_image_url"),
+ "verified": user.get("verified", False),
+ }
+
+ except httpx.HTTPError as e:
+ logger.error("HTTP error getting user info", error=str(e))
+ return {"success": False, "error": str(e)}
+
+
+def cleanup_expired_states(max_age_seconds: int = 600):
+ """
+ Remove OAuth states older than max_age_seconds (default 10 minutes).
+
+ Authorization codes expire in 30 seconds, so states older than a few
+ minutes are definitely stale.
+ """
+ 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)
+
+ if expired:
+ logger.debug(f"Cleaned up {len(expired)} expired OAuth states")
+
+
+def get_pending_state(state: str) -> Optional[Dict[str, Any]]:
+ """Get pending OAuth state without removing it (for verification)."""
+ return _oauth_states.get(state)
diff --git a/server/skills/social_agent/twitter-search-skill/SKILL.md b/server/skills/social_agent/twitter-search-skill/SKILL.md
new file mode 100644
index 00000000..03513dee
--- /dev/null
+++ b/server/skills/social_agent/twitter-search-skill/SKILL.md
@@ -0,0 +1,146 @@
+---
+name: twitter-search-skill
+description: Search for recent tweets on Twitter/X using keywords, hashtags, mentions, and advanced query operators.
+allowed-tools: twitter_search
+metadata:
+ author: machina
+ version: "1.0"
+ category: social
+ icon: "🔍"
+ color: "#000000"
+---
+
+# Twitter Search Tool
+
+Search for recent tweets on Twitter/X.
+
+## How It Works
+
+This skill provides instructions for the **Twitter Search** tool node. Connect the **Twitter Search** node to an AI Agent's `input-tools` handle to enable tweet searching.
+
+## twitter_search Tool
+
+Search for tweets matching a query.
+
+### Schema Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| query | string | Yes | Search query (supports operators) |
+| max_results | integer | No | Number of results (10-100, default: 10) |
+
+### Query Operators
+
+The X API supports advanced search operators:
+
+| Operator | Example | Description |
+|----------|---------|-------------|
+| keyword | `python` | Tweets containing the word |
+| phrase | `"machine learning"` | Exact phrase match |
+| hashtag | `#AI` | Tweets with hashtag |
+| mention | `@username` | Tweets mentioning user |
+| from | `from:elonmusk` | Tweets by specific user |
+| to | `to:username` | Replies to user |
+| -keyword | `-spam` | Exclude keyword |
+| OR | `python OR javascript` | Either term |
+| lang | `lang:en` | Language filter |
+| has:links | `AI has:links` | Tweets with URLs |
+| has:media | `sunset has:media` | Tweets with media |
+| is:retweet | `bitcoin is:retweet` | Only retweets |
+| -is:retweet | `news -is:retweet` | Exclude retweets |
+
+### Examples
+
+**Simple keyword search:**
+```json
+{
+ "query": "artificial intelligence",
+ "max_results": 20
+}
+```
+
+**Search with hashtag:**
+```json
+{
+ "query": "#MachineLearning",
+ "max_results": 50
+}
+```
+
+**Search tweets from a user:**
+```json
+{
+ "query": "from:OpenAI",
+ "max_results": 10
+}
+```
+
+**Complex query:**
+```json
+{
+ "query": "AI (startup OR company) -is:retweet lang:en",
+ "max_results": 100
+}
+```
+
+**Search with media:**
+```json
+{
+ "query": "sunset has:media",
+ "max_results": 25
+}
+```
+
+### Response Format
+
+```json
+{
+ "success": true,
+ "result": {
+ "tweets": [
+ {
+ "id": "1234567890123456789",
+ "text": "Exciting developments in AI...",
+ "author_id": "987654321",
+ "created_at": "2025-02-19T10:30:00Z"
+ }
+ ],
+ "count": 20,
+ "query": "#AI"
+ },
+ "execution_time": 0.82
+}
+```
+
+### Error Response
+
+```json
+{
+ "success": false,
+ "error": "Search query is required",
+ "execution_time": 0.01
+}
+```
+
+## Guidelines
+
+1. **Query length**: Keep queries concise for better results
+2. **Max results**: Limited to 100 per request (API constraint)
+3. **Recent tweets only**: X API v2 free tier searches recent tweets (last 7 days)
+4. **Rate limits**: Be mindful of API rate limits when searching repeatedly
+5. **Combine operators**: Use multiple operators for precise filtering
+
+## Common Use Cases
+
+- Monitor brand mentions
+- Track trending topics
+- Find tweets about specific subjects
+- Research competitor activity
+- Gather content for curation
+- Find influencers discussing topics
+
+## Setup Requirements
+
+1. Connect the **Twitter Search** node to an AI Agent's `input-tools` handle
+2. Ensure Twitter is connected (authenticated via OAuth in Credentials Modal)
+3. Your X Developer account must have appropriate API access level
diff --git a/server/skills/social_agent/twitter-send-skill/SKILL.md b/server/skills/social_agent/twitter-send-skill/SKILL.md
new file mode 100644
index 00000000..e64c90cd
--- /dev/null
+++ b/server/skills/social_agent/twitter-send-skill/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: twitter-send-skill
+description: Post tweets, reply to tweets, retweet, like/unlike, and delete tweets on Twitter/X.
+allowed-tools: twitter_send
+metadata:
+ author: machina
+ version: "1.0"
+ category: social
+ icon: "📤"
+ color: "#000000"
+---
+
+# Twitter Send Tool
+
+Post and interact with tweets on Twitter/X.
+
+## How It Works
+
+This skill provides instructions for the **Twitter Send** tool node. Connect the **Twitter Send** node to an AI Agent's `input-tools` handle to enable posting and interactions.
+
+## twitter_send Tool
+
+Send tweets, replies, retweets, likes, and deletions.
+
+### Schema Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| action | string | Yes | Action type: `tweet`, `reply`, `retweet`, `like`, `unlike`, `delete` |
+| text | string | If tweet/reply | Tweet text content (max 280 characters) |
+| tweet_id | string | If retweet/like/unlike/delete | Target tweet ID |
+| reply_to_id | string | If reply | Tweet ID to reply to |
+
+### Actions
+
+| Action | Required Fields | Description |
+|--------|-----------------|-------------|
+| `tweet` | text | Post a new tweet |
+| `reply` | text, reply_to_id | Reply to an existing tweet |
+| `retweet` | tweet_id | Retweet an existing tweet |
+| `like` | tweet_id | Like a tweet |
+| `unlike` | tweet_id | Remove like from a tweet |
+| `delete` | tweet_id | Delete your own tweet |
+
+### Examples
+
+**Post a tweet:**
+```json
+{
+ "action": "tweet",
+ "text": "Hello Twitter! This is my first automated tweet."
+}
+```
+
+**Reply to a tweet:**
+```json
+{
+ "action": "reply",
+ "text": "Thanks for sharing this!",
+ "reply_to_id": "1234567890123456789"
+}
+```
+
+**Retweet:**
+```json
+{
+ "action": "retweet",
+ "tweet_id": "1234567890123456789"
+}
+```
+
+**Like a tweet:**
+```json
+{
+ "action": "like",
+ "tweet_id": "1234567890123456789"
+}
+```
+
+**Unlike a tweet:**
+```json
+{
+ "action": "unlike",
+ "tweet_id": "1234567890123456789"
+}
+```
+
+**Delete a tweet:**
+```json
+{
+ "action": "delete",
+ "tweet_id": "1234567890123456789"
+}
+```
+
+### Response Format
+
+```json
+{
+ "success": true,
+ "result": {
+ "data": {
+ "id": "1234567890123456789",
+ "text": "Hello Twitter!"
+ },
+ "action": "tweet_sent"
+ },
+ "execution_time": 0.45
+}
+```
+
+### Error Response
+
+```json
+{
+ "success": false,
+ "error": "Tweet text is required",
+ "execution_time": 0.01
+}
+```
+
+## Guidelines
+
+1. **Character limit**: Tweets are limited to 280 characters
+2. **Tweet IDs**: Use the numeric ID string (e.g., `1234567890123456789`)
+3. **Rate limits**: X API has rate limits - avoid rapid posting
+4. **Content policy**: Follow X's content policies and terms of service
+5. **Threading**: Use reply action with reply_to_id to create threads
+
+## Common Use Cases
+
+- Post automated updates and announcements
+- Reply to mentions or specific tweets
+- Like tweets matching certain criteria
+- Create tweet threads by chaining replies
+- Engage with followers programmatically
+
+## Setup Requirements
+
+1. Connect the **Twitter Send** node to an AI Agent's `input-tools` handle
+2. Ensure Twitter is connected (authenticated via OAuth in Credentials Modal)
+3. Your X Developer account must have appropriate API access level
diff --git a/server/skills/social_agent/twitter-user-skill/SKILL.md b/server/skills/social_agent/twitter-user-skill/SKILL.md
new file mode 100644
index 00000000..e708a0d5
--- /dev/null
+++ b/server/skills/social_agent/twitter-user-skill/SKILL.md
@@ -0,0 +1,165 @@
+---
+name: twitter-user-skill
+description: Look up Twitter/X user profiles, get authenticated user info, and retrieve followers/following lists.
+allowed-tools: twitter_user
+metadata:
+ author: machina
+ version: "1.0"
+ category: social
+ icon: "👤"
+ color: "#000000"
+---
+
+# Twitter User Tool
+
+Look up user profiles and social connections on Twitter/X.
+
+## How It Works
+
+This skill provides instructions for the **Twitter User** tool node. Connect the **Twitter User** node to an AI Agent's `input-tools` handle to enable user lookups.
+
+## twitter_user Tool
+
+Retrieve user information and social connections.
+
+### Schema Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| operation | string | Yes | Operation type: `me`, `by_username`, `by_id`, `followers`, `following` |
+| username | string | If by_username | Twitter username (without @) |
+| user_id | string | If by_id/followers/following | Twitter user ID |
+| max_results | integer | No | For followers/following (default: 100, max: 1000) |
+
+### Operations
+
+| Operation | Required Fields | Description |
+|-----------|-----------------|-------------|
+| `me` | none | Get authenticated user's profile |
+| `by_username` | username | Look up user by username |
+| `by_id` | user_id | Look up user by ID |
+| `followers` | user_id (optional) | Get user's followers (defaults to authenticated user) |
+| `following` | user_id (optional) | Get accounts user follows (defaults to authenticated user) |
+
+### Examples
+
+**Get my profile:**
+```json
+{
+ "operation": "me"
+}
+```
+
+**Look up user by username:**
+```json
+{
+ "operation": "by_username",
+ "username": "elonmusk"
+}
+```
+
+**Look up user by ID:**
+```json
+{
+ "operation": "by_id",
+ "user_id": "44196397"
+}
+```
+
+**Get my followers:**
+```json
+{
+ "operation": "followers",
+ "max_results": 100
+}
+```
+
+**Get accounts I follow:**
+```json
+{
+ "operation": "following",
+ "max_results": 50
+}
+```
+
+**Get another user's followers:**
+```json
+{
+ "operation": "followers",
+ "user_id": "44196397",
+ "max_results": 200
+}
+```
+
+### Response Format - Single User
+
+```json
+{
+ "success": true,
+ "result": {
+ "user": {
+ "id": "44196397",
+ "username": "elonmusk",
+ "name": "Elon Musk",
+ "profile_image_url": "https://pbs.twimg.com/...",
+ "verified": true
+ }
+ },
+ "execution_time": 0.35
+}
+```
+
+### Response Format - User List
+
+```json
+{
+ "success": true,
+ "result": {
+ "followers": {
+ "users": [
+ {
+ "id": "123456789",
+ "username": "user1",
+ "name": "User One",
+ "profile_image_url": "https://...",
+ "verified": false
+ }
+ ],
+ "count": 100
+ }
+ },
+ "execution_time": 1.2
+}
+```
+
+### Error Response
+
+```json
+{
+ "success": false,
+ "error": "Username is required",
+ "execution_time": 0.01
+}
+```
+
+## Guidelines
+
+1. **Usernames**: Provide without the @ symbol (e.g., `elonmusk` not `@elonmusk`)
+2. **User IDs**: Use the numeric ID string
+3. **Rate limits**: Follower/following endpoints have lower rate limits
+4. **Max results**: Limited to 1000 per request for followers/following
+5. **Pagination**: For large accounts, results are paginated (first page returned)
+
+## Common Use Cases
+
+- Get your own profile information
+- Look up profiles of users you interact with
+- Check if users are verified
+- Analyze follower/following relationships
+- Build lists of relevant accounts
+
+## Setup Requirements
+
+1. Connect the **Twitter User** node to an AI Agent's `input-tools` handle
+2. Ensure Twitter is connected (authenticated via OAuth in Credentials Modal)
+3. Your X Developer account must have appropriate API access level