Skip to content

Self-improving AI Employees for everyone

fix: Persist skillsConfig on user skill delete to prevent reappearance

trohitg02176488e4f4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3aac9d24..1685c57c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -30,6 +30,9 @@ jobs:
- name: Install dependencies
run: npm install --ignore-scripts
+ - name: Sync versions from git tag
+ run: node scripts/sync-version.js
+
- name: Verify package contents
run: npm pack --dry-run
@@ -58,6 +61,9 @@ jobs:
- name: Install dependencies
run: npm install --ignore-scripts
+ - name: Sync versions from git tag
+ run: node scripts/sync-version.js
+
- name: Configure scoped package
run: |
node -e "
diff --git a/CLAUDE.md b/CLAUDE.md
index dfbd2b95..9f3c303e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -87,7 +87,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 tables
+└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage, TokenUsageMetric, CompactionEvent, SessionTokenState, UserSettings, ProviderDefaults tables
```
### Polyglot Server Integration (Optional)
@@ -290,15 +290,15 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **75 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 10 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 (84 message handlers)
+- **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)
- **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
-- **WebSocket-First Communication**: 84 WebSocket message handlers replace most REST API calls
+- **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
- **Code Cleanup**: Removed dead code, unused files, and legacy methods
@@ -437,7 +437,7 @@ 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 84 message handlers
+- `server/routers/websocket.py` - WebSocket endpoint with 86 message handlers
- `server/services/status_broadcaster.py` - Connection management and broadcasting
## Implemented Node Types
@@ -454,21 +454,12 @@ The following 75 nodes are currently implemented and functional:
### AI Agents & Memory (3 nodes)
- **aiAgent**: Advanced AI agent with tool calling, memory input handle, and iterative reasoning. Uses LangGraph for structured execution. Parameters: Provider, Model, Prompt, System Message, Options.
- **chatAgent**: Conversational AI agent with memory and skill support for multi-turn chat interactions. Parameters: Provider, Model, Prompt (supports `{{chatTrigger.message}}` template or auto-fallback from connected input), System Message. Behavior extended by connected skills.
-- **simpleMemory**: Markdown-based conversation memory with editable UI, window-based trimming, and optional vector DB for long-term semantic retrieval
+### AI Agent Tool Nodes (5 dedicated + 6 dual-purpose)
+Tool nodes connect to AI Agent's `input-tools` handle to provide capabilities the agent can invoke during reasoning. Both `masterSkill` and `simpleMemory` are in the AI Tools category.
-### Zeenie Skill Nodes (11 nodes)
-Skill nodes connect to Zeenie's `input-skill` handle to provide capabilities defined in SKILL.md files following the [Agent Skills specification](https://agentskills.io/specification):
-- **masterSkill**: Master Skill (icon: target) - Aggregates multiple skills with enable/disable toggles. Split-panel UI: left panel shows skill list with checkboxes, right panel shows selected skill's markdown editor. Enabled skills are expanded into individual skill entries when the AI Agent executes.
-- **assistantPersonality**: Assistant Skill (icon: sparkles) - default assistant personality with helpful, harmless, honest responses
-- **whatsappSkill**: Send and receive WhatsApp messages via Zeenie
-- **memorySkill**: Long-term memory management across conversations
-- **mapsSkill**: Location services - geocoding, nearby places, directions via Google Maps
-- **httpSkill**: Make HTTP requests to external APIs
-- **schedulerSkill**: Task scheduling with timers and cron expressions
-- **androidSkill**: Android device control - battery, wifi, bluetooth, apps, location, camera
-- **codeSkill**: Execute Python or JavaScript code for calculations and data processing
-- **webSearchSkill**: Search the web for current information, news, facts, and real-time data
-- **customSkill**: User-created custom skill with configurable capabilities (select from database)
+#### Dedicated Tool Nodes (passive, tool-only)
+- **masterSkill**: Master Skill (icon: target) - Aggregates multiple skills with enable/disable toggles. Split-panel UI: left panel shows skill list with checkboxes, right panel shows selected skill's markdown editor. Supports both built-in skills (from `server/skills/` folders) and user-created skills (stored in database). User skills can be created/edited/deleted inline via the "+" button.
+- **simpleMemory**: Markdown-based conversation memory with editable UI, window-based trimming, and optional vector DB for long-term semantic retrieval
#### Skill Node Architecture
Skills are organized in subfolders under `server/skills/`. Each top-level folder appears as an option in the Master Skill node's folder dropdown. See **[Skill Creation Guide](./server/skills/GUIDE.md)** for full documentation.
@@ -607,20 +598,19 @@ if skill_type == 'masterSkill':
**Key Files:**
| File | Description |
|------|-------------|
-| `client/src/components/parameterPanel/MasterSkillEditor.tsx` | Split-panel skill aggregator UI with folder dropdown |
-| `client/src/nodeDefinitions/skillNodes.ts` | masterSkill node definition |
-| `server/services/handlers/ai.py` | Expands masterSkill into individual skills |
-| `server/skills/GUIDE.md` | Skill creation guide |
-
-### AI Agent Tool Nodes (3 dedicated + 6 dual-purpose)
-Tool nodes connect to AI Agent's `input-tools` handle to provide capabilities the agent can invoke during reasoning.
-
-#### Dedicated Tool Nodes (passive, tool-only)
+| `client/src/components/parameterPanel/MasterSkillEditor.tsx` | Split-panel skill aggregator UI with inline user skill CRUD |
+| `client/src/nodeDefinitions/skillNodes.ts` | masterSkill node definition (group: tool) |
+| `server/routers/websocket.py` | User skill CRUD: `get_user_skills`, `create_user_skill`, `update_user_skill`, `delete_user_skill` |
+| `server/core/database.py` | UserSkill model and database CRUD methods |
+| `server/services/handlers/ai.py` | Expands masterSkill into individual skills at execution |
+| `server/skills/GUIDE.md` | Skill creation guide for built-in skills |
+
+#### Other Dedicated Tool Nodes
- **calculatorTool**: Mathematical operations (add, subtract, multiply, divide, power, sqrt, mod, abs)
- **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 (10 nodes)
+### Specialized AI Agents (12 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:**
@@ -641,6 +631,8 @@ Specialized agents are AI Agents pre-configured for specific domains. They inher
- **productivity_agent**: Productivity Agent - AI agent for productivity workflows. Connect scheduling, task, and utility nodes as tools.
- **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.
**Backend Routing:**
Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and routed to `handle_chat_agent`:
@@ -648,7 +640,8 @@ Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and routed to `hand
# In node_executor.py - all specialized agents route to handle_chat_agent
SPECIALIZED_AGENT_TYPES = {
'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
- 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'
+ 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
+ 'autonomous_agent', 'orchestrator_agent'
}
```
@@ -973,7 +966,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**: 84 message handlers replacing REST APIs
+✅ **WebSocket-First Architecture**: 86 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
@@ -1281,11 +1274,13 @@ deploy_workflow() -> Sets up triggers, returns immediately
- **Execution Engine**: Routes AI nodes to Python Flask backend with auto-injection of API keys
#### Supported AI Providers & Models
-- **OpenAI**: GPT-4o, GPT-4 Turbo, GPT-3.5 Turbo with response format options. O-series (o1, o3, o4) with reasoning effort.
-- **Anthropic**: Claude 3.5 Sonnet/Haiku, Claude 3 Opus with extended thinking support (thinkingBudget parameter)
-- **Google**: Gemini 2.5 Pro/Flash, Gemini 2.0 Flash Thinking with thinking_budget parameter and safety settings
-- **Groq**: Ultra-fast Llama, Mixtral, Gemma models. Qwen3/QwQ with reasoning_format parameter.
-- **Cerebras**: Ultra-fast Llama and Qwen models on custom AI hardware with thinking support
+All 6 providers are available across aiAgent, chatAgent (Zeenie), and all specialized agents:
+- **OpenAI**: GPT-5, GPT-4o, o-series (o1, o3, o4) with reasoning effort. Max output: 128K tokens.
+- **Anthropic**: Claude Opus 4.6, Sonnet 4.5 with extended thinking. Max output: 128K tokens.
+- **Google**: Gemini 3.0, 2.5 Pro/Flash with thinking_budget. Max output: 65K tokens.
+- **Groq**: Ultra-fast Llama, Qwen3/QwQ with reasoning_format. Max output: 8K tokens.
+- **OpenRouter**: Unified API for 200+ models from multiple providers.
+- **Cerebras**: Ultra-fast Llama and Qwen models on custom AI hardware.
#### Key Features
- Visual configuration with status indicators and parameter buttons
@@ -1294,6 +1289,39 @@ deploy_workflow() -> Sets up triggers, returns immediately
- Secure API key validation with automatic model discovery and 30-day expiration
- Execution routing to Python Flask backend for AI model processing
- **Proxy-based authentication** for routing through local servers (Ollama pattern)
+- **Provider default parameters** configurable in Credentials Modal (temperature, max_tokens, thinking settings)
+
+#### Provider Default Parameters
+Users can configure default parameter values per LLM provider in the Credentials Modal. These defaults are applied to new AI nodes using that provider.
+
+**Configurable Parameters:**
+- `temperature` (0-2): Controls randomness in responses
+- `max_tokens` (1-128000): Maximum response length
+- `thinking_enabled`: Enable extended thinking for supported models
+- `thinking_budget` (1024-16000): Token budget for thinking
+- `reasoning_effort` (low/medium/high): For OpenAI o-series, Groq
+- `reasoning_format` (parsed/hidden): For Groq Qwen models
+
+**Database Model** (`server/models/database.py`):
+```python
+class ProviderDefaults(SQLModel, table=True):
+ provider: str # openai, anthropic, gemini, groq, openrouter, cerebras
+ temperature: float
+ max_tokens: int
+ thinking_enabled: bool
+ thinking_budget: int
+ reasoning_effort: str # low, medium, high
+ reasoning_format: str # parsed, hidden
+```
+
+**Key Files:**
+| File | Description |
+|------|-------------|
+| `server/models/database.py` | `ProviderDefaults` SQLModel |
+| `server/core/database.py` | `get_provider_defaults()`, `save_provider_defaults()` CRUD |
+| `server/routers/websocket.py` | `get_provider_defaults`, `save_provider_defaults` handlers |
+| `client/src/hooks/useApiKeys.ts` | `getProviderDefaults()`, `saveProviderDefaults()` methods |
+| `client/src/components/CredentialsModal.tsx` | Default Parameters UI section |
#### Proxy-Based Authentication (Ollama Pattern)
AI providers support optional proxy-based authentication, allowing requests to route through a local proxy server that handles authentication. This follows the [Ollama Claude Code integration](https://docs.ollama.com/integrations/claude-code) pattern.
@@ -1366,10 +1394,10 @@ Extended thinking and reasoning capabilities for supported AI models. When enabl
| Provider | Models | Parameter | Notes |
|----------|--------|-----------|-------|
-| **Claude** | claude-3-5-sonnet, claude-3-opus | `thinkingBudget` (1024-16000 tokens) | Requires `max_tokens > budget_tokens`. Temperature auto-set to 1. |
-| **Gemini** | gemini-2.5-flash, gemini-2.5-pro, gemini-2.0-flash-thinking | `thinkingBudget` (token count) | Uses `thinking_budget` API parameter |
+| **Claude** | opus-4.6, sonnet-4.5 | `thinkingBudget` (1024-16000 tokens) | Requires `max_tokens > budget_tokens`. Temperature auto-set to 1. |
+| **Gemini** | gemini-3.0, gemini-2.5-pro/flash | `thinkingBudget` (token count) | Uses `thinking_budget` API parameter |
| **Groq** | qwen3-32b, qwq-32b | `reasoningFormat` ('parsed' or 'hidden') | 'parsed' returns reasoning, 'hidden' returns only final answer |
-| **OpenAI** | o1, o3, o4 series | `reasoningEffort` (minimal/low/medium/high) | Reasoning summaries require organization verification at platform.openai.com |
+| **OpenAI** | o1, o3, o4, GPT-5 series | `reasoningEffort` (minimal/low/medium/high/xhigh) | GPT-5.2 supports xhigh reasoning |
#### Frontend Parameters (`client/src/factories/baseChatModelFactory.ts`)
```typescript
@@ -1521,8 +1549,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-task', label: 'Task', position: '85%' },
],
},
- // ... 10 specialized agents (android_agent, coding_agent, web_agent, task_agent,
- // social_agent, travel_agent, tool_agent, productivity_agent, payments_agent, consumer_agent)
+ // ... 11 specialized agents (android_agent, coding_agent, web_agent, task_agent,
+ // social_agent, travel_agent, tool_agent, productivity_agent, payments_agent, consumer_agent, autonomous_agent)
// each with themeColorKey, standard Skill/Tool bottom handles, Memory/Task left handles
};
```
@@ -1677,6 +1705,8 @@ The system supports specialized agent variants that inherit from the base AI Age
| Productivity | `productivity_agent` | clock | cyan |
| Payments | `payments_agent` | credit card | green |
| Consumer | `consumer_agent` | cart | purple |
+| Autonomous | `autonomous_agent` | target | purple |
+| Orchestrator | `orchestrator_agent` | conductor | cyan |
All specialized agents share the same handle configuration:
- **Left**: `input-main` (Input, 30%), `input-memory` (Memory, 55%), `input-task` (Task, 85%)
@@ -3875,7 +3905,7 @@ def has_real_android_devices(self) -> bool:
Updated `client_left` and presence handlers use `has_real_android_devices()` instead of checking total device count.
-### WebSocket Message Types (84 Handlers)
+### WebSocket Message Types (86 Handlers)
#### Request/Response Messages (Client -> Server -> Client)
| Category | Message Types |
@@ -3900,6 +3930,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins
| **Built-in Skills** | `get_skill_content`, `save_skill_content`, `scan_skill_folder`, `list_skill_folders` |
| **Memory/Skill Reset** | `clear_memory`, `reset_skill` |
| **User Settings** | `get_user_settings`, `save_user_settings` |
+| **Provider Defaults** | `get_provider_defaults`, `save_provider_defaults` |
#### Broadcast Messages (Server -> All Clients)
| Message Type | Description |
@@ -4056,7 +4087,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**: 84 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations
+- **WebSocket-First Architecture**: 86 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/README.md b/README.md
index 2cf27d6e..ff5e5509 100644
--- a/README.md
+++ b/README.md
@@ -57,11 +57,11 @@ npm run docker:up
| Provider | Models | Features |
|----------|--------|----------|
-| **OpenAI** | GPT-4o, GPT-4 Turbo, o1, o3, o4-mini | JSON mode, reasoning effort |
-| **Anthropic** | Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Haiku | Extended thinking |
-| **Google** | Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 2.0 Flash Thinking | Multimodal, 1M context |
+| **OpenAI** | GPT-5, GPT-4o, o1, o3, o4 | 128K output, reasoning effort |
+| **Anthropic** | Claude Opus 4.6, Sonnet 4.5 | 128K output, extended thinking |
+| **Google** | Gemini 3.0, 2.5 Pro/Flash | 65K output, 1M context |
| **OpenRouter** | 200+ models | Unified API for all providers |
-| **Groq** | Llama, Mixtral, Qwen | Ultra-fast inference |
+| **Groq** | Llama, Qwen | Ultra-fast inference |
| **Cerebras** | Llama, Qwen | Ultra-fast on custom hardware |
### AI Agents & Skills
diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsx
index 2d9b0d45..5c347498 100644
--- a/client/src/components/AIAgentNode.tsx
+++ b/client/src/components/AIAgentNode.tsx
@@ -66,28 +66,29 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
chatAgent: {
icon: <span style={{ fontSize: '28px' }}>🧞</span>,
title: 'Zeenie',
- subtitle: 'Your Personal Assistant',
+ subtitle: 'Personal Assistant',
themeColorKey: 'cyan',
bottomHandles: [
{ id: 'input-skill', label: 'Skill', position: '25%' },
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
+ topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
socialReceive: {
icon: <SocialReceiveIcon />,
@@ -122,7 +123,7 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
},
android_agent: {
icon: <span style={{ fontSize: '28px' }}>📱</span>,
- title: 'Android Control Agent',
+ title: 'Android Agent',
subtitle: 'Device Control',
themeColorKey: 'green',
bottomHandles: [
@@ -130,12 +131,12 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
coding_agent: {
icon: <span style={{ fontSize: '28px' }}>💻</span>,
@@ -147,16 +148,16 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
web_agent: {
icon: <span style={{ fontSize: '28px' }}>🌐</span>,
- title: 'Web Control Agent',
+ title: 'Web Agent',
subtitle: 'Browser Automation',
themeColorKey: 'pink',
bottomHandles: [
@@ -164,16 +165,16 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
task_agent: {
icon: <span style={{ fontSize: '28px' }}>📋</span>,
- title: 'Task Management Agent',
+ title: 'Task Agent',
subtitle: 'Task Automation',
themeColorKey: 'purple',
bottomHandles: [
@@ -181,16 +182,16 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
social_agent: {
icon: <span style={{ fontSize: '28px' }}>📱</span>,
- title: 'Social Media Agent',
+ title: 'Social Agent',
subtitle: 'Social Messaging',
themeColorKey: 'green',
bottomHandles: [
@@ -198,12 +199,12 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
travel_agent: {
icon: <span style={{ fontSize: '28px' }}>✈️</span>,
@@ -215,12 +216,12 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
tool_agent: {
icon: <span style={{ fontSize: '28px' }}>🔧</span>,
@@ -232,29 +233,29 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
productivity_agent: {
icon: <span style={{ fontSize: '28px' }}>⏰</span>,
title: 'Productivity Agent',
- subtitle: 'Productivity',
+ subtitle: 'Workflows',
themeColorKey: 'cyan',
bottomHandles: [
{ id: 'input-skill', label: 'Skill', position: '25%' },
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
payments_agent: {
icon: <span style={{ fontSize: '28px' }}>💳</span>,
@@ -266,12 +267,12 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
},
consumer_agent: {
icon: <span style={{ fontSize: '28px' }}>🛒</span>,
@@ -283,12 +284,46 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {
{ id: 'input-tools', label: 'Tool', position: '75%' },
],
leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '55%' },
+ { id: 'input-memory', label: 'Memory', position: '65%' },
{ id: 'input-task', label: 'Task', position: '85%' },
],
topOutputHandle: { id: 'output-top', label: 'Output' },
width: 260,
- height: 160,
+ height: 200,
+ },
+ autonomous_agent: {
+ icon: <span style={{ fontSize: '28px' }}>🎯</span>,
+ title: 'Autonomous Agent',
+ subtitle: 'Autonomous Ops',
+ themeColorKey: 'purple',
+ bottomHandles: [
+ { id: 'input-skill', label: 'Skill', position: '25%' },
+ { id: 'input-tools', label: 'Tool', position: '75%' },
+ ],
+ leftHandles: [
+ { id: 'input-memory', label: 'Memory', position: '65%' },
+ { id: 'input-task', label: 'Task', position: '85%' },
+ ],
+ topOutputHandle: { id: 'output-top', label: 'Output' },
+ width: 260,
+ height: 200,
+ },
+ orchestrator_agent: {
+ icon: <span style={{ fontSize: '28px' }}>🎼</span>,
+ title: 'Orchestrator Agent',
+ subtitle: 'Agent Coordination',
+ themeColorKey: 'cyan',
+ bottomHandles: [
+ { id: 'input-skill', label: 'Skill', position: '25%' },
+ { id: 'input-tools', label: 'Tool', position: '75%' },
+ ],
+ leftHandles: [
+ { id: 'input-memory', label: 'Memory', position: '65%' },
+ { id: 'input-task', label: 'Task', position: '85%' },
+ ],
+ topOutputHandle: { id: 'output-top', label: 'Output' },
+ width: 260,
+ height: 200,
},
};
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index b8700c7a..041cdd13 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -13,7 +13,7 @@ import {
import Modal from './ui/Modal';
import QRCodeDisplay from './ui/QRCodeDisplay';
import ApiKeyInput from './ui/ApiKeyInput';
-import { useApiKeys } from '../hooks/useApiKeys';
+import { useApiKeys, ProviderDefaults } from '../hooks/useApiKeys';
import { useAppTheme } from '../hooks/useAppTheme';
import { useWhatsAppStatus, useAndroidStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
import { useWhatsApp } from '../hooks/useWhatsApp';
@@ -114,7 +114,7 @@ interface Props {
const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const theme = useAppTheme();
- const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, isConnected } = useApiKeys();
+ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, getProviderDefaults, saveProviderDefaults, isConnected } = useApiKeys();
const whatsappStatus = useWhatsAppStatus();
const androidStatus = useAndroidStatus();
@@ -138,6 +138,11 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const [proxyUrls, setProxyUrls] = useState<Record<string, string>>({});
const [selectedItem, setSelectedItem] = useState<CredentialItem | null>(null);
+ // Provider defaults state
+ const [providerDefaults, setProviderDefaults] = useState<Record<string, ProviderDefaults>>({});
+ const [defaultsLoading, setDefaultsLoading] = useState<Record<string, boolean>>({});
+ const [defaultsDirty, setDefaultsDirty] = useState<Record<string, boolean>>({});
+
// Load stored keys and proxy URLs
const loadKeys = useCallback(async () => {
const allItems = CATEGORIES.flatMap(c => c.items);
@@ -177,6 +182,42 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [visible, isConnected, loadKeys]);
+ // Load provider defaults when AI provider is selected
+ useEffect(() => {
+ const isAIProvider = CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === selectedItem?.id);
+ if (selectedItem && !selectedItem.isSpecial && isAIProvider && isConnected) {
+ // Only load if we don't already have defaults for this provider
+ if (!providerDefaults[selectedItem.id]) {
+ const loadDefaults = async () => {
+ setDefaultsLoading(l => ({ ...l, [selectedItem.id]: true }));
+ const defaults = await getProviderDefaults(selectedItem.id);
+ setProviderDefaults(p => ({ ...p, [selectedItem.id]: defaults }));
+ setDefaultsLoading(l => ({ ...l, [selectedItem.id]: false }));
+ };
+ loadDefaults();
+ }
+ }
+ }, [selectedItem, isConnected, getProviderDefaults, providerDefaults]);
+
+ // Handler to update a single default value
+ const updateProviderDefault = (provider: string, key: keyof ProviderDefaults, value: number | boolean | string) => {
+ setProviderDefaults(p => ({
+ ...p,
+ [provider]: { ...(p[provider] || {}), [key]: value } as ProviderDefaults
+ }));
+ setDefaultsDirty(d => ({ ...d, [provider]: true }));
+ };
+
+ // Handler to save provider defaults
+ const handleSaveProviderDefaults = async (provider: string) => {
+ setDefaultsLoading(l => ({ ...l, [provider]: true }));
+ const success = await saveProviderDefaults(provider, providerDefaults[provider]);
+ if (success) {
+ setDefaultsDirty(d => ({ ...d, [provider]: false }));
+ }
+ setDefaultsLoading(l => ({ ...l, [provider]: false }));
+ };
+
const handleValidate = async (id: string) => {
const key = keys[id];
if (!key?.trim()) return;
@@ -323,7 +364,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
// WhatsApp actions
const { getStatus: getWhatsAppStatus, startConnection, restartConnection } = useWhatsApp();
- const { sendRequest, getWhatsAppRateLimitConfig, setWhatsAppRateLimitConfig, unpauseWhatsAppRateLimit } = useWebSocket();
+ const { sendRequest, setAndroidStatus, getWhatsAppRateLimitConfig, setWhatsAppRateLimitConfig, unpauseWhatsAppRateLimit } = useWebSocket();
// Android state
const [androidApiKey, setAndroidApiKey] = useState('');
@@ -381,8 +422,19 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
url: import.meta.env.VITE_ANDROID_RELAY_URL || '',
api_key: key,
});
+ console.log('[Android] Connect response:', response);
if (!response.success) {
setAndroidError(response.error || 'Failed to connect');
+ } else if (response.qr_data) {
+ console.log('[Android] Setting QR data from response');
+ // Use response data directly - don't rely on broadcast timing
+ setAndroidStatus(prev => ({
+ ...prev,
+ connected: true,
+ paired: false,
+ qr_data: response.qr_data,
+ session_token: response.session_token || prev.session_token,
+ }));
}
} catch (err: any) {
setAndroidError(err.message || 'Failed to connect');
@@ -592,7 +644,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
<QRCodeDisplay
value={whatsappStatus.qr}
isConnected={whatsappStatus.connected}
- size={200}
+ size={280}
connectedTitle="Already Connected!"
connectedSubtitle="No QR code needed"
loading={whatsappStatus.running && !whatsappStatus.qr && !whatsappStatus.connected}
@@ -916,12 +968,12 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
backgroundColor: theme.colors.backgroundAlt,
borderRadius: theme.borderRadius.lg,
marginBottom: theme.spacing.xl,
- minHeight: 200,
+ minHeight: 300,
}}>
<QRCodeDisplay
value={androidStatus.qr_data}
isConnected={androidStatus.paired}
- size={260}
+ size={280}
connectedTitle="Device Paired!"
connectedSubtitle={androidStatus.device_name || androidStatus.device_id || 'Android Device'}
loading={androidStatus.connected && !androidStatus.qr_data && !androidStatus.paired}
@@ -1213,6 +1265,110 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
</div>
)}
+ {/* Default Parameters Section - Only for AI providers */}
+ {CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === item.id) && (
+ <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.md,
+ }}>
+ Default Parameters
+ </label>
+
+ <div style={{
+ padding: theme.spacing.lg,
+ backgroundColor: theme.colors.backgroundAlt,
+ borderRadius: theme.borderRadius.md,
+ border: `1px solid ${theme.colors.border}`,
+ opacity: defaultsLoading[item.id] ? 0.6 : 1,
+ }}>
+ {/* Temperature */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: theme.spacing.md }}>
+ <div>
+ <div style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>Temperature</div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Controls randomness (0-2)</div>
+ </div>
+ <InputNumber
+ size="small"
+ value={providerDefaults[item.id]?.temperature ?? 0.7}
+ onChange={(v) => updateProviderDefault(item.id, 'temperature', v ?? 0.7)}
+ min={0}
+ max={2}
+ step={0.1}
+ style={{ width: 80 }}
+ />
+ </div>
+
+ {/* Max Tokens */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: theme.spacing.md }}>
+ <div>
+ <div style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>Max Tokens</div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Maximum response length</div>
+ </div>
+ <InputNumber
+ size="small"
+ value={providerDefaults[item.id]?.max_tokens ?? 4096}
+ onChange={(v) => updateProviderDefault(item.id, 'max_tokens', v ?? 4096)}
+ min={1}
+ max={128000}
+ style={{ width: 100 }}
+ />
+ </div>
+
+ {/* Thinking/Reasoning Toggle */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: theme.spacing.md }}>
+ <div>
+ <div style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>Thinking/Reasoning</div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Extended thinking for supported models</div>
+ </div>
+ <Switch
+ size="small"
+ checked={providerDefaults[item.id]?.thinking_enabled ?? false}
+ onChange={(v) => updateProviderDefault(item.id, 'thinking_enabled', v)}
+ />
+ </div>
+
+ {/* Thinking Budget - conditional */}
+ {providerDefaults[item.id]?.thinking_enabled && (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: theme.spacing.md }}>
+ <div>
+ <div style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>Thinking Budget</div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>Token budget (1024-16000)</div>
+ </div>
+ <InputNumber
+ size="small"
+ value={providerDefaults[item.id]?.thinking_budget ?? 2048}
+ onChange={(v) => updateProviderDefault(item.id, 'thinking_budget', v ?? 2048)}
+ min={1024}
+ max={16000}
+ style={{ width: 80 }}
+ />
+ </div>
+ )}
+
+ {/* Save Button */}
+ <Button
+ size="small"
+ onClick={() => handleSaveProviderDefaults(item.id)}
+ loading={defaultsLoading[item.id]}
+ disabled={!defaultsDirty[item.id]}
+ block
+ style={{
+ marginTop: theme.spacing.sm,
+ backgroundColor: defaultsDirty[item.id] ? `${theme.dracula.green}25` : undefined,
+ borderColor: defaultsDirty[item.id] ? `${theme.dracula.green}60` : undefined,
+ color: defaultsDirty[item.id] ? theme.dracula.green : undefined,
+ }}
+ >
+ Save Defaults
+ </Button>
+ </div>
+ </div>
+ )}
+
{/* Models list */}
{models[item.id]?.length > 0 && (
<div style={{ marginBottom: theme.spacing.xl }}>
diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsx
index 3d0f6ce5..27e29d8e 100644
--- a/client/src/components/ParameterRenderer.tsx
+++ b/client/src/components/ParameterRenderer.tsx
@@ -768,6 +768,8 @@ interface ParameterRendererProps {
onParameterChange?: (paramName: string, value: any) => void;
onClosePanel?: () => void;
isLoadingParameters?: boolean;
+ /** For memory nodes: the connected agent's node ID for auto-session display */
+ connectedAgentId?: string | null;
}
// Type guard to check if parameter is INodeProperties
@@ -782,6 +784,7 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
allParameters,
onParameterChange,
isLoadingParameters = false,
+ connectedAgentId,
}) => {
const theme = useAppTheme();
// Don't use default while loading - wait for actual saved value to load
@@ -1380,6 +1383,44 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
);
}
+ // Special case for sessionId parameter - show auto-derived session ID in placeholder
+ if (parameter.name === 'sessionId' && connectedAgentId) {
+ const effectivePlaceholder = connectedAgentId;
+
+ return (
+ <input
+ type="text"
+ value={currentValue || ''}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={effectivePlaceholder}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ border: isDragOver ? `2px solid ${theme.accent.cyan}` : `1px solid ${theme.colors.border}`,
+ borderRadius: '6px',
+ fontSize: '14px',
+ backgroundColor: isDragOver ? `${theme.accent.cyan}10` : theme.colors.backgroundAlt,
+ color: currentValue && currentValue.includes('{{') ? theme.accent.yellow : theme.colors.text,
+ outline: 'none',
+ transition: 'all 0.2s ease',
+ fontFamily: currentValue && currentValue.includes('{{') ? 'monospace' : 'system-ui, sans-serif',
+ boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)'
+ }}
+ onFocus={(e) => {
+ e.target.style.borderColor = theme.accent.cyan;
+ e.target.style.boxShadow = `0 0 0 3px ${theme.accent.cyan}20, inset 0 1px 2px rgba(0,0,0,0.05)`;
+ }}
+ onBlur={(e) => {
+ e.target.style.borderColor = theme.colors.border;
+ e.target.style.boxShadow = 'inset 0 1px 2px rgba(0,0,0,0.05)';
+ }}
+ />
+ );
+ }
+
return (
<input
type={isPassword ? "password" : "text"}
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index 01e36b06..65f2fb7c 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -88,7 +88,8 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const AGENT_WITH_SKILLS_TYPES = [
'aiAgent', 'chatAgent', 'android_agent', 'coding_agent',
'web_agent', 'task_agent', 'social_agent', 'travel_agent',
- 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'
+ 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
+ 'autonomous_agent', 'orchestrator_agent'
];
// Check if current node is an agent that shows skills in Middle Section
const isAgentWithSkills = AGENT_WITH_SKILLS_TYPES.includes(currentNodeType || '');
@@ -486,7 +487,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const isMemory = nodeType === 'simpleMemory';
const nodeTypeLower = nodeType.toLowerCase();
// AI agent types that use the AI output schema
- const aiAgentTypes = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'];
+ const aiAgentTypes = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent'];
const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || aiAgentTypes.includes(nodeType));
const isFile = nodeType.includes('file');
const isWhatsAppDb = nodeType === 'whatsappDb';
diff --git a/client/src/components/parameterPanel/MasterSkillEditor.tsx b/client/src/components/parameterPanel/MasterSkillEditor.tsx
index cb237c77..f52dbffa 100644
--- a/client/src/components/parameterPanel/MasterSkillEditor.tsx
+++ b/client/src/components/parameterPanel/MasterSkillEditor.tsx
@@ -6,11 +6,13 @@
*
* Skills loaded from skillFolder (server/skills/<folder>/) or built-in list.
* The skillsConfig uses skillName (folder name) as keys.
+ *
+ * User skills are created/edited inline in the right panel (no modal).
*/
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { Input, Select, Checkbox, Button, Spin, List, Badge, Empty, Tooltip, Alert } from 'antd';
-import { SearchOutlined, ReloadOutlined, InfoCircleOutlined, FolderOutlined } from '@ant-design/icons';
+import { Input, Select, Checkbox, Button, Spin, List, Badge, Empty, Tooltip, Alert, Popconfirm, message } from 'antd';
+import { SearchOutlined, ReloadOutlined, InfoCircleOutlined, FolderOutlined, PlusOutlined, DeleteOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';
import { useAppTheme } from '../../hooks/useAppTheme';
import { useWebSocket } from '../../contexts/WebSocketContext';
import { skillNodes, SKILL_NODE_TYPES } from '../../nodeDefinitions/skillNodes';
@@ -34,6 +36,29 @@ interface AvailableSkill {
icon: string;
color: string;
description: string;
+ isUserSkill?: boolean; // True if this is a user-created skill from database
+}
+
+// User skill from database
+interface UserSkill {
+ name: string;
+ display_name: string;
+ description: string;
+ instructions: string;
+ icon: string;
+ color: string;
+ category: string;
+ is_active: boolean;
+}
+
+// Pending skill data for create/edit
+interface PendingSkillData {
+ name: string;
+ display_name: string;
+ description: string;
+ instructions: string;
+ icon: string;
+ color: string;
}
interface MasterSkillEditorProps {
@@ -41,6 +66,7 @@ interface MasterSkillEditorProps {
onConfigChange: (config: MasterSkillConfig) => void;
skillFolder?: string;
onSkillFolderChange?: (folder: string) => void;
+ nodeId?: string; // For persisting skillsConfig to database
}
// Lookup icon/color from skillNodes.ts definitions by skill name
@@ -71,7 +97,8 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
skillsConfig,
onConfigChange,
skillFolder,
- onSkillFolderChange
+ onSkillFolderChange,
+ nodeId
}) => {
const theme = useAppTheme();
const { sendRequest } = useWebSocket();
@@ -86,9 +113,17 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
const hasFetchedFolders = useRef(false);
const editorWrapperRef = useRef<HTMLDivElement>(null);
+ // User skills from database
+ const [userSkills, setUserSkills] = useState<UserSkill[]>([]);
+
+ // Inline editing state (no modal)
+ const [isCreatingNew, setIsCreatingNew] = useState(false);
+ const [pendingSkillData, setPendingSkillData] = useState<PendingSkillData | null>(null);
+ const [savingSkill, setSavingSkill] = useState(false);
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+
// Native DOM keydown handler to stop React Flow's document-level listeners
// from intercepting standard text editing shortcuts (Ctrl+A, Ctrl+C, etc.)
- // React synthetic stopPropagation doesn't prevent native document.addEventListener handlers.
useEffect(() => {
const el = editorWrapperRef.current;
if (!el) return;
@@ -127,6 +162,22 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
fetchFolders();
}, [sendRequest]);
+ // Fetch user-created skills from database
+ const fetchUserSkills = useCallback(async () => {
+ try {
+ const response = await sendRequest<{ skills: UserSkill[]; count: number }>('get_user_skills', { active_only: false });
+ if (response?.skills) {
+ setUserSkills(response.skills);
+ }
+ } catch (error) {
+ console.error('[MasterSkillEditor] Failed to fetch user skills:', error);
+ }
+ }, [sendRequest]);
+
+ useEffect(() => {
+ fetchUserSkills();
+ }, [fetchUserSkills]);
+
// Fetch skills from folder when skillFolder is set
useEffect(() => {
if (!skillFolder) {
@@ -150,7 +201,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
type: s.name,
skillName: s.name,
displayName: s.name.split('-').map(w => w[0].toUpperCase() + w.slice(1)).join(' '),
- icon: defaults.icon || s.metadata?.icon || '📄',
+ icon: defaults.icon || s.metadata?.icon || '',
color: defaults.color || s.metadata?.color || '#6366F1',
description: s.description || ''
};
@@ -166,32 +217,50 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
fetchFolderSkills();
}, [skillFolder, sendRequest]);
- // Build list of available skills - from folder scan or node definitions
+ // Build list of available skills - from folder scan, node definitions, and user skills
const availableSkills = useMemo<AvailableSkill[]>(() => {
+ const skills: AvailableSkill[] = [];
+
+ // Add folder skills if available
if (skillFolder && folderSkills.length > 0) {
- return folderSkills;
+ skills.push(...folderSkills);
+ } else {
+ // Add built-in skills from node definitions
+ SKILL_NODE_TYPES
+ .filter(type => type !== 'customSkill' && type !== 'masterSkill')
+ .forEach(type => {
+ const nodeDef = skillNodes[type];
+ if (!nodeDef) return;
+
+ const skillNameProp = nodeDef.properties?.find(p => p.name === 'skillName');
+ const skillName = skillNameProp?.default as string || type;
+
+ skills.push({
+ type,
+ skillName,
+ displayName: nodeDef.displayName || type,
+ icon: nodeDef.icon || '',
+ color: (nodeDef.defaults?.color as string) || '#6366F1',
+ description: nodeDef.description || ''
+ });
+ });
}
- return SKILL_NODE_TYPES
- .filter(type => type !== 'customSkill' && type !== 'masterSkill')
- .map(type => {
- const nodeDef = skillNodes[type];
- if (!nodeDef) return null;
-
- const skillNameProp = nodeDef.properties?.find(p => p.name === 'skillName');
- const skillName = skillNameProp?.default as string || type;
-
- return {
- type,
- skillName, // This is the folder name used as config key
- displayName: nodeDef.displayName || type,
- icon: nodeDef.icon || '',
- color: (nodeDef.defaults?.color as string) || '#6366F1',
- description: nodeDef.description || ''
- };
- })
- .filter((s): s is AvailableSkill => s !== null);
- }, [skillFolder, folderSkills]);
+ // Add user-created skills
+ userSkills.forEach(us => {
+ skills.push({
+ type: 'userSkill',
+ skillName: us.name,
+ displayName: us.display_name,
+ icon: us.icon || '',
+ color: us.color || '#6366F1',
+ description: us.description || '',
+ isUserSkill: true
+ });
+ });
+
+ return skills;
+ }, [skillFolder, folderSkills, userSkills]);
// Filter skills based on search query
const filteredSkills = useMemo(() => {
@@ -203,12 +272,34 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
);
}, [availableSkills, searchQuery]);
+ // Clean up skillsConfig - remove skills that no longer exist in availableSkills
+ useEffect(() => {
+ if (availableSkills.length === 0) return; // Wait for skills to load
+
+ const availableSkillNames = new Set(availableSkills.map(s => s.skillName));
+ const configSkillNames = Object.keys(skillsConfig);
+ const staleSkills = configSkillNames.filter(name => !availableSkillNames.has(name));
+
+ if (staleSkills.length > 0) {
+ console.log('[MasterSkillEditor] Removing stale skills from config:', staleSkills);
+ const cleanedConfig = { ...skillsConfig };
+ staleSkills.forEach(name => delete cleanedConfig[name]);
+ onConfigChange(cleanedConfig);
+
+ // Clear selection if selected skill was stale
+ if (selectedSkillName && staleSkills.includes(selectedSkillName)) {
+ setSelectedSkillName(null);
+ setPendingSkillData(null);
+ }
+ }
+ }, [availableSkills, skillsConfig, onConfigChange, selectedSkillName]);
+
// Auto-select first skill
useEffect(() => {
- if (!selectedSkillName && availableSkills.length > 0) {
+ if (!selectedSkillName && !isCreatingNew && availableSkills.length > 0) {
setSelectedSkillName(availableSkills[0].skillName);
}
- }, [selectedSkillName, availableSkills]);
+ }, [selectedSkillName, isCreatingNew, availableSkills]);
// Load skill content from skill folder
const fetchSkillContent = useCallback(async (skillName: string): Promise<string> => {
@@ -239,14 +330,44 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
// Load instructions when skill is selected (for preview)
useEffect(() => {
- if (!selectedSkillName) return;
+ if (!selectedSkillName || isCreatingNew) return;
+
+ // Skip if skill doesn't exist in availableSkills (may have been deleted)
+ const skillExists = availableSkills.some(s => s.skillName === selectedSkillName);
+ if (!skillExists) return;
// Skip if already cached
if (defaultInstructions[selectedSkillName]) return;
// Load skill content for preview
fetchSkillContent(selectedSkillName);
- }, [selectedSkillName, defaultInstructions, fetchSkillContent]);
+ }, [selectedSkillName, isCreatingNew, defaultInstructions, fetchSkillContent, availableSkills]);
+
+ // When selecting a user skill, load its data into pendingSkillData for editing
+ useEffect(() => {
+ if (isCreatingNew || !selectedSkillName) {
+ return;
+ }
+
+ const selectedInfo = availableSkills.find(s => s.skillName === selectedSkillName);
+ if (selectedInfo?.isUserSkill) {
+ const userSkill = userSkills.find(us => us.name === selectedSkillName);
+ if (userSkill) {
+ setPendingSkillData({
+ name: userSkill.name,
+ display_name: userSkill.display_name,
+ description: userSkill.description,
+ instructions: userSkill.instructions,
+ icon: userSkill.icon || '',
+ color: userSkill.color || '#6366F1'
+ });
+ setHasUnsavedChanges(false);
+ }
+ } else {
+ setPendingSkillData(null);
+ setHasUnsavedChanges(false);
+ }
+ }, [selectedSkillName, isCreatingNew, availableSkills, userSkills]);
// Toggle skill enabled/disabled
const handleToggleSkill = useCallback(async (skillName: string, enabled: boolean) => {
@@ -271,7 +392,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
}
}, [skillsConfig, onConfigChange, fetchSkillContent]);
- // Update instructions
+ // Update instructions (for built-in skills)
const handleUpdateInstructions = useCallback((skillName: string, instructions: string) => {
const currentConfig = skillsConfig[skillName];
const defaultContent = defaultInstructions[skillName] || '';
@@ -305,11 +426,145 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
});
}, [skillsConfig, onConfigChange, fetchSkillContent]);
+ // Create new skill - show inline editor
+ const handleCreateSkill = useCallback(() => {
+ setIsCreatingNew(true);
+ setSelectedSkillName(null);
+ setPendingSkillData({
+ name: '',
+ display_name: '',
+ description: '',
+ instructions: '# Skill Instructions\n\nDescribe what this skill does and how the AI should use it.',
+ icon: '',
+ color: '#6366F1'
+ });
+ setHasUnsavedChanges(false);
+ }, []);
+
+ // Cancel creating new skill
+ const handleCancelCreate = useCallback(() => {
+ setIsCreatingNew(false);
+ setPendingSkillData(null);
+ setHasUnsavedChanges(false);
+ // Select first available skill
+ if (availableSkills.length > 0) {
+ setSelectedSkillName(availableSkills[0].skillName);
+ }
+ }, [availableSkills]);
+
+ // Update pending skill data
+ const handlePendingDataChange = useCallback((field: keyof PendingSkillData, value: string) => {
+ setPendingSkillData(prev => prev ? { ...prev, [field]: value } : null);
+ setHasUnsavedChanges(true);
+ }, []);
+
+ // Save skill (create or update)
+ const handleSaveSkill = useCallback(async () => {
+ if (!pendingSkillData) return;
+
+ // Validate required fields
+ if (!pendingSkillData.display_name.trim()) {
+ message.error('Display name is required');
+ return;
+ }
+ if (!pendingSkillData.instructions.trim()) {
+ message.error('Instructions are required');
+ return;
+ }
+
+ // For new skills, generate name from display_name if not provided
+ let skillName = pendingSkillData.name;
+ if (isCreatingNew) {
+ if (!skillName.trim()) {
+ skillName = pendingSkillData.display_name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '');
+ }
+ if (!skillName || !/^[a-z0-9-]+$/.test(skillName)) {
+ message.error('Invalid skill ID. Use lowercase letters, numbers, and hyphens only.');
+ return;
+ }
+ }
+
+ setSavingSkill(true);
+ try {
+ const handler = isCreatingNew ? 'create_user_skill' : 'update_user_skill';
+ const payload = {
+ name: skillName,
+ display_name: pendingSkillData.display_name,
+ description: pendingSkillData.description,
+ instructions: pendingSkillData.instructions,
+ icon: pendingSkillData.icon,
+ color: pendingSkillData.color,
+ category: skillFolder || 'custom',
+ is_active: true
+ };
+
+ const result = await sendRequest<{ skill?: UserSkill; success?: boolean; error?: string }>(handler, payload);
+
+ if (result.skill || result.success) {
+ message.success(isCreatingNew ? 'Skill created' : 'Skill saved');
+ await fetchUserSkills();
+
+ if (isCreatingNew) {
+ // Add to config as enabled
+ onConfigChange({
+ ...skillsConfig,
+ [skillName]: { enabled: true, instructions: pendingSkillData.instructions, isCustomized: false }
+ });
+ setIsCreatingNew(false);
+ setSelectedSkillName(skillName);
+ }
+ setHasUnsavedChanges(false);
+ } else {
+ message.error(result.error || 'Failed to save skill');
+ }
+ } catch (err: any) {
+ message.error(err.message || 'Failed to save skill');
+ } finally {
+ setSavingSkill(false);
+ }
+ }, [pendingSkillData, isCreatingNew, skillFolder, sendRequest, fetchUserSkills, skillsConfig, onConfigChange]);
+
+ // Delete user skill
+ const handleDeleteSkill = useCallback(async (skillName: string) => {
+ try {
+ const result = await sendRequest<{ success: boolean; error?: string }>('delete_user_skill', { name: skillName });
+ if (result.success) {
+ message.success('Skill deleted');
+ // Remove from config
+ const newConfig = { ...skillsConfig };
+ delete newConfig[skillName];
+ onConfigChange(newConfig);
+
+ // Persist cleaned config to database so deleted skill doesn't reappear
+ if (nodeId) {
+ await sendRequest('save_node_parameters', {
+ node_id: nodeId,
+ parameters: { skillsConfig: newConfig, skillFolder: skillFolder || 'assistant' }
+ });
+ }
+
+ // Clear selection if deleted skill was selected
+ if (selectedSkillName === skillName) {
+ setSelectedSkillName(null);
+ setPendingSkillData(null);
+ }
+ // Refresh user skills list from database
+ await fetchUserSkills();
+ } else {
+ message.error(result.error || 'Failed to delete skill');
+ }
+ } catch (err: any) {
+ message.error(err.message || 'Failed to delete skill');
+ }
+ }, [sendRequest, fetchUserSkills, skillsConfig, onConfigChange, selectedSkillName, nodeId, skillFolder]);
+
const selectedSkillInfo = availableSkills.find(s => s.skillName === selectedSkillName);
const selectedSkillConfig = selectedSkillName ? skillsConfig[selectedSkillName] : undefined;
const enabledCount = Object.values(skillsConfig).filter(c => c?.enabled).length;
-
- console.log('[MasterSkillEditor] RENDER', { skillFolder, onSkillFolderChange: !!onSkillFolderChange, skillsConfig: Object.keys(skillsConfig) });
+ const isEditingUserSkill = selectedSkillInfo?.isUserSkill && pendingSkillData;
return (
<div style={{
@@ -329,7 +584,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
border: `1px solid ${theme.colors.border}`,
overflow: 'hidden'
}}>
- {/* Header with count */}
+ {/* Header with count and create button */}
<div style={{
padding: theme.spacing.sm,
borderBottom: `1px solid ${theme.colors.border}`,
@@ -341,11 +596,22 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
<span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>
Skills
</span>
- <Badge
- count={enabledCount}
- style={{ backgroundColor: theme.dracula.purple }}
- showZero
- />
+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.xs }}>
+ <Badge count={enabledCount} style={{ backgroundColor: theme.dracula.purple }} showZero />
+ <Tooltip title="Create new skill">
+ <Button
+ size="small"
+ icon={<PlusOutlined />}
+ onClick={handleCreateSkill}
+ disabled={isCreatingNew}
+ style={{
+ backgroundColor: `${theme.dracula.green}20`,
+ borderColor: theme.dracula.green,
+ color: theme.dracula.green,
+ }}
+ />
+ </Tooltip>
+ </div>
</div>
{/* Search */}
@@ -401,13 +667,22 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
dataSource={filteredSkills}
renderItem={(skill) => {
const config = skillsConfig[skill.skillName];
- const isSelected = selectedSkillName === skill.skillName;
+ const isSelected = selectedSkillName === skill.skillName && !isCreatingNew;
const isEnabled = config?.enabled || false;
const isCustomized = config?.isCustomized || false;
return (
<List.Item
- onClick={() => setSelectedSkillName(skill.skillName)}
+ onClick={() => {
+ if (isCreatingNew) {
+ // Confirm cancel if creating new
+ if (hasUnsavedChanges) {
+ if (!confirm('Discard unsaved changes?')) return;
+ }
+ setIsCreatingNew(false);
+ }
+ setSelectedSkillName(skill.skillName);
+ }}
style={{
padding: `${theme.spacing.sm} ${theme.spacing.md}`,
cursor: 'pointer',
@@ -425,7 +700,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
}}
onClick={(e) => e.stopPropagation()}
/>
- {renderSkillIcon(skill.icon, 16)}
+ {renderSkillIcon(skill.icon || '', 16)}
<span style={{
flex: 1,
fontSize: theme.fontSize.sm,
@@ -448,6 +723,19 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
}} />
</Tooltip>
)}
+ {skill.isUserSkill && (
+ <Badge
+ count="Custom"
+ style={{
+ backgroundColor: `${theme.dracula.cyan}20`,
+ color: theme.dracula.cyan,
+ fontSize: 10,
+ padding: '0 4px',
+ height: 16,
+ lineHeight: '16px'
+ }}
+ />
+ )}
</div>
</List.Item>
);
@@ -467,9 +755,10 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
border: `1px solid ${theme.colors.border}`,
overflow: 'hidden'
}}>
- {selectedSkillInfo ? (
+ {/* Creating new skill */}
+ {isCreatingNew && pendingSkillData ? (
<>
- {/* Skill Header */}
+ {/* New Skill Header */}
<div style={{
padding: theme.spacing.md,
borderBottom: `1px solid ${theme.colors.border}`,
@@ -478,35 +767,245 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
alignItems: 'center',
gap: theme.spacing.md
}}>
- {renderSkillIcon(selectedSkillInfo.icon, 24)}
+ <div style={{
+ width: 40,
+ height: 40,
+ borderRadius: theme.borderRadius.md,
+ backgroundColor: `${pendingSkillData.color}20`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ border: `2px dashed ${pendingSkillData.color}`
+ }}>
+ {pendingSkillData.icon ? renderSkillIcon(pendingSkillData.icon, 20) : <PlusOutlined style={{ color: pendingSkillData.color }} />}
+ </div>
<div style={{ flex: 1 }}>
<div style={{
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.semibold,
- color: theme.colors.text,
- display: 'flex',
- alignItems: 'center',
- gap: theme.spacing.sm
+ color: theme.dracula.green
}}>
- {selectedSkillInfo.displayName}
- {selectedSkillConfig?.isCustomized && (
- <Badge
- count="Customized"
- style={{
- backgroundColor: `${theme.dracula.orange}20`,
- color: theme.dracula.orange,
- fontSize: theme.fontSize.xs
- }}
- />
- )}
+ Create New Skill
</div>
<div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: 2 }}>
- {selectedSkillInfo.description}
+ Fill in the details below and save
+ </div>
+ </div>
+ <Button
+ icon={<CloseOutlined />}
+ size="small"
+ onClick={handleCancelCreate}
+ style={{
+ backgroundColor: `${theme.dracula.red}15`,
+ borderColor: `${theme.dracula.red}40`,
+ color: theme.dracula.red,
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ icon={<SaveOutlined />}
+ size="small"
+ onClick={handleSaveSkill}
+ loading={savingSkill}
+ style={{
+ backgroundColor: `${theme.dracula.green}15`,
+ borderColor: `${theme.dracula.green}40`,
+ color: theme.dracula.green,
+ }}
+ >
+ Save
+ </Button>
+ </div>
+
+ {/* New Skill Form */}
+ <div ref={editorWrapperRef} style={{ flex: 1, padding: theme.spacing.md, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: theme.spacing.md }}>
+ {/* Display Name */}
+ <div>
+ <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: 4 }}>
+ Display Name *
+ </label>
+ <Input
+ value={pendingSkillData.display_name}
+ onChange={(e) => handlePendingDataChange('display_name', e.target.value)}
+ placeholder="My Custom Skill"
+ style={{ backgroundColor: theme.colors.backgroundAlt, borderColor: theme.colors.border }}
+ />
+ </div>
+
+ {/* Description */}
+ <div>
+ <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: 4 }}>
+ Description
+ </label>
+ <Input
+ value={pendingSkillData.description}
+ onChange={(e) => handlePendingDataChange('description', e.target.value)}
+ placeholder="Brief description of what this skill does"
+ style={{ backgroundColor: theme.colors.backgroundAlt, borderColor: theme.colors.border }}
+ />
+ </div>
+
+ {/* Icon and Color */}
+ <div style={{ display: 'flex', gap: theme.spacing.md }}>
+ <div style={{ width: 100 }}>
+ <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: 4 }}>
+ Icon (emoji)
+ </label>
+ <Input
+ value={pendingSkillData.icon}
+ onChange={(e) => handlePendingDataChange('icon', e.target.value)}
+ placeholder=""
+ style={{ backgroundColor: theme.colors.backgroundAlt, borderColor: theme.colors.border, textAlign: 'center' }}
+ />
+ </div>
+ <div style={{ width: 80 }}>
+ <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: 4 }}>
+ Color
+ </label>
+ <Input
+ type="color"
+ value={pendingSkillData.color}
+ onChange={(e) => handlePendingDataChange('color', e.target.value)}
+ style={{ backgroundColor: theme.colors.backgroundAlt, borderColor: theme.colors.border, height: 32, padding: 2 }}
+ />
</div>
</div>
- {/* Reset Button */}
- {selectedSkillConfig?.isCustomized && (
+ {/* Instructions */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 200 }}>
+ <label style={{ display: 'block', fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginBottom: 4 }}>
+ Instructions *
+ </label>
+ <Input.TextArea
+ value={pendingSkillData.instructions}
+ onChange={(e) => handlePendingDataChange('instructions', e.target.value)}
+ placeholder="# Skill Instructions..."
+ spellCheck={false}
+ autoSize={false}
+ style={{
+ flex: 1,
+ minHeight: 0,
+ resize: 'none',
+ fontFamily: "'Consolas', 'Monaco', 'Fira Code', monospace",
+ fontSize: 13,
+ lineHeight: 1.5,
+ backgroundColor: theme.colors.backgroundAlt,
+ color: theme.colors.text,
+ borderColor: theme.colors.border,
+ borderRadius: theme.borderRadius.md,
+ }}
+ />
+ </div>
+ </div>
+ </>
+ ) : selectedSkillInfo ? (
+ <>
+ {/* Skill Header */}
+ <div style={{
+ padding: theme.spacing.md,
+ borderBottom: `1px solid ${theme.colors.border}`,
+ backgroundColor: theme.colors.backgroundAlt,
+ display: 'flex',
+ alignItems: 'center',
+ gap: theme.spacing.md
+ }}>
+ {renderSkillIcon(selectedSkillInfo.icon || '', 24)}
+ <div style={{ flex: 1 }}>
+ {isEditingUserSkill ? (
+ <Input
+ value={pendingSkillData?.display_name || ''}
+ onChange={(e) => handlePendingDataChange('display_name', e.target.value)}
+ style={{
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.semibold,
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ marginBottom: 4
+ }}
+ />
+ ) : (
+ <div style={{
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.semibold,
+ color: theme.colors.text,
+ display: 'flex',
+ alignItems: 'center',
+ gap: theme.spacing.sm
+ }}>
+ {selectedSkillInfo.displayName}
+ {selectedSkillConfig?.isCustomized && (
+ <Badge
+ count="Customized"
+ style={{
+ backgroundColor: `${theme.dracula.orange}20`,
+ color: theme.dracula.orange,
+ fontSize: theme.fontSize.xs
+ }}
+ />
+ )}
+ </div>
+ )}
+ {isEditingUserSkill ? (
+ <Input
+ value={pendingSkillData?.description || ''}
+ onChange={(e) => handlePendingDataChange('description', e.target.value)}
+ placeholder="Description"
+ style={{
+ fontSize: theme.fontSize.xs,
+ backgroundColor: theme.colors.background,
+ borderColor: theme.colors.border,
+ }}
+ />
+ ) : (
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: 2 }}>
+ {selectedSkillInfo.description}
+ </div>
+ )}
+ </div>
+
+ {/* User skill actions */}
+ {isEditingUserSkill && (
+ <>
+ {hasUnsavedChanges && (
+ <Button
+ icon={<SaveOutlined />}
+ size="small"
+ onClick={handleSaveSkill}
+ loading={savingSkill}
+ style={{
+ backgroundColor: `${theme.dracula.green}15`,
+ borderColor: `${theme.dracula.green}40`,
+ color: theme.dracula.green,
+ }}
+ >
+ Save
+ </Button>
+ )}
+ <Popconfirm
+ title="Delete this skill?"
+ onConfirm={() => handleDeleteSkill(selectedSkillName!)}
+ okText="Delete"
+ cancelText="Cancel"
+ okButtonProps={{ danger: true }}
+ >
+ <Button
+ icon={<DeleteOutlined />}
+ size="small"
+ danger
+ style={{
+ backgroundColor: `${theme.dracula.red}15`,
+ borderColor: `${theme.dracula.red}40`,
+ }}
+ >
+ Delete
+ </Button>
+ </Popconfirm>
+ </>
+ )}
+
+ {/* Reset Button for built-in skills */}
+ {!isEditingUserSkill && selectedSkillConfig?.isCustomized && (
<Button
icon={<ReloadOutlined />}
size="small"
@@ -531,8 +1030,18 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
</div>
) : (
<Input.TextArea
- value={selectedSkillConfig?.instructions || defaultInstructions[selectedSkillName!] || ''}
- onChange={(e) => handleUpdateInstructions(selectedSkillName!, e.target.value)}
+ value={
+ isEditingUserSkill
+ ? pendingSkillData?.instructions || ''
+ : (selectedSkillConfig?.instructions || defaultInstructions[selectedSkillName!] || '')
+ }
+ onChange={(e) => {
+ if (isEditingUserSkill) {
+ handlePendingDataChange('instructions', e.target.value);
+ } else {
+ handleUpdateInstructions(selectedSkillName!, e.target.value);
+ }
+ }}
placeholder="Loading skill instructions..."
spellCheck={false}
autoSize={false}
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index f599bc1c..0a4a461b 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -29,7 +29,9 @@ const AGENT_WITH_SKILLS_TYPES = [
'tool_agent',
'productivity_agent',
'payments_agent',
- 'consumer_agent'
+ 'consumer_agent',
+ 'autonomous_agent',
+ 'orchestrator_agent'
];
interface ConnectedSkill {
@@ -108,6 +110,9 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const [editThresholdValue, setEditThresholdValue] = useState<number>(100000);
const [savingThreshold, setSavingThreshold] = useState(false);
+ // For Memory nodes: track the connected agent's ID for auto-session display
+ const [connectedAgentId, setConnectedAgentId] = useState<string | null>(null);
+
// Clear memory handler
const handleClearMemory = async () => {
setIsProcessing(true);
@@ -168,6 +173,26 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
// State for Master Skill parameters
const [masterSkillParams, setMasterSkillParams] = useState<Record<string, any>>({});
+ // Load global memory window size setting for new Memory nodes
+ useEffect(() => {
+ if (!isMemoryNode) return;
+
+ // Only apply global default if windowSize hasn't been explicitly set yet
+ const loadGlobalWindowSize = async () => {
+ try {
+ const response = await sendRequest<{ settings: any }>('get_user_settings', {});
+ const globalWindowSize = response?.settings?.memory_window_size;
+ if (globalWindowSize !== undefined && parameters.windowSize === undefined) {
+ onParameterChange('windowSize', globalWindowSize);
+ }
+ } catch (err) {
+ console.error('[MiddleSection] Failed to load global memory settings:', err);
+ }
+ };
+
+ loadGlobalWindowSize();
+ }, [nodeId, isMemoryNode]); // Only run when node changes, not on every parameter change
+
// Get connected memory session ID and compaction stats for agent nodes
useEffect(() => {
if (!isAgentWithSkills || !currentWorkflow) {
@@ -190,13 +215,18 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
}
// Get memory node's sessionId from its parameters
+ // If empty or 'default', the actual session will be the agent's node_id (auto-derived)
const fetchMemorySessionId = async () => {
try {
const response = await sendRequest<{ parameters: Record<string, any> }>('get_node_parameters', {
node_id: memoryEdge.source
});
- const sessionId = response?.parameters?.sessionId || 'default';
- setConnectedMemorySessionId(sessionId);
+ const configuredSession = response?.parameters?.sessionId || '';
+ // Auto-derive: use agent's nodeId if sessionId is empty or 'default'
+ const actualSessionId = configuredSession && configuredSession !== 'default'
+ ? configuredSession
+ : nodeId; // nodeId is the agent's ID
+ setConnectedMemorySessionId(actualSessionId);
// Fetch compaction stats for this session
setCompactionLoading(true);
@@ -205,11 +235,11 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
total: number;
threshold: number;
count: number;
- }>('get_compaction_stats', { session_id: sessionId });
+ }>('get_compaction_stats', { session_id: actualSessionId });
if (statsResponse) {
setCompactionStats({
- session_id: statsResponse.session_id || sessionId,
+ session_id: statsResponse.session_id || actualSessionId,
total: statsResponse.total || 0,
threshold: statsResponse.threshold || 100000,
count: statsResponse.count || 0
@@ -225,6 +255,28 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
fetchMemorySessionId();
}, [nodeId, isAgentWithSkills, currentWorkflow, sendRequest]);
+ // For Memory nodes: find which AI Agent this memory is connected TO
+ // Used to display the auto-derived session ID
+ useEffect(() => {
+ if (!isMemoryNode || !currentWorkflow) {
+ setConnectedAgentId(null);
+ return;
+ }
+
+ const edges = currentWorkflow.edges || [];
+
+ // Find edge where this memory node is the SOURCE and target handle is 'input-memory'
+ const agentEdge = edges.find((edge: Edge) =>
+ edge.source === nodeId && edge.targetHandle === 'input-memory'
+ );
+
+ if (agentEdge) {
+ setConnectedAgentId(agentEdge.target);
+ } else {
+ setConnectedAgentId(null);
+ }
+ }, [nodeId, isMemoryNode, currentWorkflow]);
+
// Get connected skills for agent nodes
useEffect(() => {
if (!isAgentWithSkills || !currentWorkflow) {
@@ -388,6 +440,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
onConfigChange={(config) => onParameterChange('skillsConfig', config)}
skillFolder={parameters.skillFolder || 'assistant'}
onSkillFolderChange={(folder) => onParameterChange('skillFolder', folder)}
+ nodeId={nodeId}
/>
</div>
) : (
@@ -441,6 +494,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
onParameterChange={onParameterChange}
onClosePanel={() => {}}
isLoadingParameters={isLoadingParameters}
+ connectedAgentId={isMemoryNode ? connectedAgentId : undefined}
/>
</div>
);
diff --git a/client/src/components/ui/QRCodeDisplay.tsx b/client/src/components/ui/QRCodeDisplay.tsx
index 5725b9b5..c245f4c1 100644
--- a/client/src/components/ui/QRCodeDisplay.tsx
+++ b/client/src/components/ui/QRCodeDisplay.tsx
@@ -49,7 +49,7 @@ const isBase64Image = (value: string): boolean => {
const QRCodeDisplay: React.FC<QRCodeDisplayProps> = ({
value,
isConnected = false,
- size = 160,
+ size = 280,
loading = false,
connectedTitle = 'Connected',
connectedSubtitle = 'No QR code needed',
diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsx
index 65b17fa1..ee58ad9b 100644
--- a/client/src/components/ui/SettingsPanel.tsx
+++ b/client/src/components/ui/SettingsPanel.tsx
@@ -10,6 +10,7 @@ export interface WorkflowSettings {
sidebarDefaultOpen: boolean;
componentPaletteDefaultOpen: boolean;
consolePanelDefaultOpen: boolean;
+ memoryWindowSize: number;
}
export const defaultSettings: WorkflowSettings = {
@@ -18,6 +19,7 @@ export const defaultSettings: WorkflowSettings = {
sidebarDefaultOpen: true,
componentPaletteDefaultOpen: true,
consolePanelDefaultOpen: false,
+ memoryWindowSize: 100,
};
interface SettingsPanelProps {
@@ -57,6 +59,7 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
sidebarDefaultOpen: dbSettings.sidebar_default_open ?? defaultSettings.sidebarDefaultOpen,
componentPaletteDefaultOpen: dbSettings.component_palette_default_open ?? defaultSettings.componentPaletteDefaultOpen,
consolePanelDefaultOpen: dbSettings.console_panel_default_open ?? defaultSettings.consolePanelDefaultOpen,
+ memoryWindowSize: dbSettings.memory_window_size ?? defaultSettings.memoryWindowSize,
});
}
} catch (error) {
@@ -76,6 +79,7 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
sidebar_default_open: newSettings.sidebarDefaultOpen,
component_palette_default_open: newSettings.componentPaletteDefaultOpen,
console_panel_default_open: newSettings.consolePanelDefaultOpen,
+ memory_window_size: newSettings.memoryWindowSize,
}
});
if (showMessage) {
@@ -391,6 +395,31 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
</div>
)}
</div>
+
+ {/* Memory Settings */}
+ <div style={sectionStyle}>
+ <div style={sectionHeaderStyle}>
+ <div style={{ ...sectionIconStyle, backgroundColor: `${theme.dracula.purple}20` }}>{'\uD83E\uDDE0'}</div>
+ <div style={sectionTitleStyle}>Memory</div>
+ </div>
+
+ <div style={settingRowStyle}>
+ <div style={settingLabelStyle}>
+ <div style={labelTextStyle}>Default Window Size</div>
+ <div style={descriptionStyle}>Number of message pairs to keep in short-term memory (1-100)</div>
+ </div>
+ <InputNumber
+ size="small"
+ min={1}
+ max={100}
+ step={1}
+ value={settings.memoryWindowSize}
+ onChange={(value) => handleChange('memoryWindowSize', value ?? 100)}
+ disabled={isSaving}
+ style={{ width: 80 }}
+ />
+ </div>
+ </div>
</div>
</div>
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index ddc84d39..9590ad3e 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -201,6 +201,7 @@ interface WebSocketContextValue {
// Status data
androidStatus: AndroidStatus;
+ setAndroidStatus: React.Dispatch<React.SetStateAction<AndroidStatus>>;
whatsappStatus: WhatsAppStatus;
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
@@ -1956,6 +1957,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Status data
androidStatus,
+ setAndroidStatus,
whatsappStatus,
whatsappMessages,
lastWhatsAppMessage,
diff --git a/client/src/factories/baseChatModelFactory.ts b/client/src/factories/baseChatModelFactory.ts
index 04686a6b..225de43f 100644
--- a/client/src/factories/baseChatModelFactory.ts
+++ b/client/src/factories/baseChatModelFactory.ts
@@ -152,8 +152,8 @@ export const STANDARD_PARAMETERS = {
displayName: 'Maximum Tokens',
name: 'maxTokens',
type: 'number' as const,
- default: 1000,
- typeOptions: { minValue: 1, maxValue: 8192 },
+ default: 4096,
+ typeOptions: { minValue: 1, maxValue: 128000 },
description: 'Maximum number of tokens to generate'
},
diff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.ts
index 897cfa36..979cf16b 100644
--- a/client/src/hooks/useApiKeys.ts
+++ b/client/src/hooks/useApiKeys.ts
@@ -14,6 +14,15 @@ export interface ApiKeyValidationResult {
models?: string[];
}
+export interface ProviderDefaults {
+ temperature: number;
+ max_tokens: number;
+ thinking_enabled: boolean;
+ thinking_budget: number;
+ reasoning_effort: 'low' | 'medium' | 'high';
+ reasoning_format: 'parsed' | 'hidden';
+}
+
export interface UseApiKeysResult {
// Validate and store API key
validateApiKey: (provider: string, apiKey: string) => Promise<ApiKeyValidationResult>;
@@ -39,6 +48,10 @@ export interface UseApiKeysResult {
// Get AI models for a provider
getAiModels: (provider: string, apiKey: string) => Promise<string[]>;
+ // Provider defaults
+ getProviderDefaults: (provider: string) => Promise<ProviderDefaults>;
+ saveProviderDefaults: (provider: string, defaults: ProviderDefaults) => Promise<boolean>;
+
// State
isValidating: boolean;
validationError: string | null;
@@ -53,6 +66,7 @@ export const useApiKeys = (): UseApiKeysResult => {
deleteApiKey: wsDeleteApiKey,
validateMapsKey: wsValidateMapsKey,
getAiModels: wsGetAiModels,
+ sendRequest,
isConnected
} = useWebSocket();
@@ -222,6 +236,50 @@ export const useApiKeys = (): UseApiKeysResult => {
}
}, [wsGetAiModels]);
+ /**
+ * Get default parameters for a provider
+ */
+ const getProviderDefaults = useCallback(async (
+ provider: string
+ ): Promise<ProviderDefaults> => {
+ const defaultValues: ProviderDefaults = {
+ temperature: 0.7,
+ max_tokens: 4096,
+ thinking_enabled: false,
+ thinking_budget: 2048,
+ reasoning_effort: 'medium',
+ reasoning_format: 'parsed',
+ };
+
+ if (!isConnected) return defaultValues;
+
+ try {
+ const response = await sendRequest<{ defaults: ProviderDefaults }>('get_provider_defaults', { provider });
+ return response?.defaults || defaultValues;
+ } catch (error) {
+ console.warn(`Error fetching provider defaults for ${provider}:`, error);
+ return defaultValues;
+ }
+ }, [sendRequest, isConnected]);
+
+ /**
+ * Save default parameters for a provider
+ */
+ const saveProviderDefaults = useCallback(async (
+ provider: string,
+ defaults: ProviderDefaults
+ ): Promise<boolean> => {
+ if (!isConnected) return false;
+
+ try {
+ const response = await sendRequest<{ success: boolean }>('save_provider_defaults', { provider, defaults });
+ return response?.success || false;
+ } catch (error) {
+ console.warn(`Error saving provider defaults for ${provider}:`, error);
+ return false;
+ }
+ }, [sendRequest, isConnected]);
+
return {
validateApiKey,
saveApiKey,
@@ -231,6 +289,8 @@ export const useApiKeys = (): UseApiKeysResult => {
removeApiKey,
validateGoogleMapsKey,
getAiModels,
+ getProviderDefaults,
+ saveProviderDefaults,
isValidating,
validationError,
isConnected
diff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.ts
index 63a0dfca..00fa923a 100644
--- a/client/src/nodeDefinitions/aiAgentNodes.ts
+++ b/client/src/nodeDefinitions/aiAgentNodes.ts
@@ -74,6 +74,18 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
{
name: 'Google (Gemini)',
value: 'gemini'
+ },
+ {
+ name: 'Groq',
+ value: 'groq'
+ },
+ {
+ name: 'OpenRouter',
+ value: 'openrouter'
+ },
+ {
+ name: 'Cerebras',
+ value: 'cerebras'
}
],
default: 'openai',
@@ -133,8 +145,8 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
displayName: 'Maximum Tokens',
name: 'maxTokens',
type: 'number',
- default: 1000,
- typeOptions: { minValue: 1, maxValue: 8192 },
+ default: 4096,
+ typeOptions: { minValue: 1, maxValue: 128000 },
description: 'Maximum number of tokens to generate'
},
{
@@ -244,6 +256,10 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
{
name: 'OpenRouter',
value: 'openrouter'
+ },
+ {
+ name: 'Cerebras',
+ value: 'cerebras'
}
],
default: 'openai',
@@ -298,8 +314,8 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
displayName: 'Maximum Tokens',
name: 'maxTokens',
type: 'number',
- default: 1000,
- typeOptions: { minValue: 1, maxValue: 8192 },
+ default: 4096,
+ typeOptions: { minValue: 1, maxValue: 128000 },
description: 'Maximum number of tokens to generate'
},
{
@@ -342,7 +358,7 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
displayName: 'Simple Memory',
name: 'simpleMemory',
icon: '🧠',
- group: ['skill', 'memory'], // 'skill' = appears in AI Skills category
+ group: ['tool', 'memory'], // 'tool' = appears in AI Tools category
version: 1,
description: 'Markdown-based conversation memory with optional vector DB for long-term retrieval',
defaults: { name: 'Memory', color: '#8b5cf6' },
@@ -355,20 +371,21 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {
}],
properties: [
{
- displayName: 'Session ID',
+ displayName: 'Session ID (Override)',
name: 'sessionId',
type: 'string',
- default: 'default',
- required: true,
- description: 'Unique identifier for conversation session'
+ default: '',
+ required: false,
+ description: 'Leave empty to auto-use connected agent ID. Set manually to share memory across agents.',
+ placeholder: 'Auto (uses agent ID)'
},
{
displayName: 'Window Size',
name: 'windowSize',
type: 'number',
- default: 10,
+ default: 100,
typeOptions: { minValue: 1, maxValue: 100 },
- description: 'Number of message pairs to keep in short-term memory'
+ description: 'Number of message pairs to keep in short-term memory (uses global default from Settings)'
},
{
displayName: 'Conversation History',
diff --git a/client/src/nodeDefinitions/skillNodes.ts b/client/src/nodeDefinitions/skillNodes.ts
index facd8394..2f43619a 100644
--- a/client/src/nodeDefinitions/skillNodes.ts
+++ b/client/src/nodeDefinitions/skillNodes.ts
@@ -3,184 +3,23 @@ import {
INodeTypeDescription,
NodeConnectionType
} from '../types/INodeProperties';
-import { WHATSAPP_CONNECT_ICON } from './whatsappNodes';
// ============================================================================
// SKILL NODES - Connect to Zeenie's input-skill handle
// ============================================================================
-
-// Factory function for creating skill node definitions
-export function createSkillNode(config: {
- name: string;
- displayName: string;
- icon: string;
- color: string;
- skillName: string;
- description: string;
- subtitle: string;
- properties?: any[];
-}): INodeTypeDescription {
- return {
- displayName: config.displayName,
- name: config.name,
- icon: config.icon,
- group: ['skill'],
- version: 1,
- subtitle: config.subtitle,
- description: config.description,
- defaults: { name: config.displayName, color: config.color },
- inputs: [], // No input - skill node is passive
- outputs: [{
- name: 'skill',
- displayName: 'Skill',
- type: 'main' as NodeConnectionType,
- description: 'Connect to Zeenie skill handle'
- }],
- properties: [
- {
- displayName: 'Skill Name',
- name: 'skillName',
- type: 'string',
- default: config.skillName,
- required: true,
- description: 'Internal skill identifier',
- typeOptions: { readonly: true }
- },
- {
- displayName: 'Instructions',
- name: 'instructions',
- type: 'string',
- default: '',
- description: 'Skill instructions in Markdown format. Loaded from SKILL.md file.',
- typeOptions: {
- rows: 20,
- editor: 'code',
- editorLanguage: 'markdown'
- }
- },
- ...(config.properties || [])
- ]
- };
-}
+// Master Skill node aggregates built-in skills from server/skills/ folders
+// and user-created skills from database. Supports inline skill creation/editing.
export const skillNodes: Record<string, INodeTypeDescription> = {
- // Assistant Personality Skill - Default assistant personality
- assistantPersonality: createSkillNode({
- name: 'assistantPersonality',
- displayName: 'Assistant Personality',
- icon: '✨',
- color: '#D97706',
- skillName: 'assistant-personality',
- subtitle: 'AI Personality',
- description: 'Default assistant personality with helpful, harmless, and honest responses'
- }),
-
- // WhatsApp Skill - Send and receive messages
- whatsappSkill: createSkillNode({
- name: 'whatsappSkill',
- displayName: 'WhatsApp Skill',
- icon: WHATSAPP_CONNECT_ICON,
- color: '#25D366',
- skillName: 'whatsapp-skill',
- subtitle: 'Messaging',
- description: 'Send and receive WhatsApp messages via Zeenie'
- }),
-
- // Memory Skill - Remember and recall information
- memorySkill: createSkillNode({
- name: 'memorySkill',
- displayName: 'Memory Skill',
- icon: '🧠',
- color: '#8B5CF6',
- skillName: 'memory-skill',
- subtitle: 'Long-term Memory',
- description: 'Remember information across conversations with short and long-term memory',
- properties: [
- {
- displayName: 'Default Session',
- name: 'defaultSession',
- type: 'string',
- default: 'default',
- description: 'Default session ID for memory storage'
- }
- ]
- }),
-
- // Maps Skill - Location and geocoding services
- mapsSkill: createSkillNode({
- name: 'mapsSkill',
- displayName: 'Maps Skill',
- icon: '🗺️',
- color: '#4285F4',
- skillName: 'maps-skill',
- subtitle: 'Location Services',
- description: 'Geocoding, nearby places, and map creation via Google Maps'
- }),
-
- // HTTP Skill - Make API requests
- httpSkill: createSkillNode({
- name: 'httpSkill',
- displayName: 'HTTP Skill',
- icon: '🌐',
- color: '#EF4444',
- skillName: 'http-skill',
- subtitle: 'API Requests',
- description: 'Make HTTP requests to external APIs and web services'
- }),
-
- // Scheduler Skill - Timers and cron jobs
- schedulerSkill: createSkillNode({
- name: 'schedulerSkill',
- displayName: 'Scheduler Skill',
- icon: '⏰',
- color: '#10B981',
- skillName: 'scheduler-skill',
- subtitle: 'Task Scheduling',
- description: 'Schedule tasks with timers and cron expressions'
- }),
-
- // Android Skill - Device control
- androidSkill: createSkillNode({
- name: 'androidSkill',
- displayName: 'Android Skill',
- icon: '📱',
- color: '#3DDC84',
- skillName: 'android-skill',
- subtitle: 'Device Control',
- description: 'Control Android devices - battery, wifi, bluetooth, apps, location, camera'
- }),
-
- // Code Skill - Execute code
- codeSkill: createSkillNode({
- name: 'codeSkill',
- displayName: 'Code Skill',
- icon: '💻',
- color: '#F59E0B',
- skillName: 'code-skill',
- subtitle: 'Code Execution',
- description: 'Execute Python or JavaScript code for calculations and data processing'
- }),
-
- // Web Search Skill - Search the web for information
- webSearchSkill: createSkillNode({
- name: 'webSearchSkill',
- displayName: 'Web Search Skill',
- icon: '🔍',
- color: '#bd93f9',
- skillName: 'web-search-skill',
- subtitle: 'Web Search',
- description: 'Search the web for current information, news, facts, and real-time data'
- }),
-
// Master Skill - Aggregates multiple skills with enable/disable toggles
masterSkill: {
displayName: 'Master Skill',
name: 'masterSkill',
icon: '🎯',
- group: ['skill'],
+ group: ['tool'], // Appears in AI Tools category
version: 1,
subtitle: 'Skill Aggregator',
- description: 'Combine multiple skills with enable/disable toggles in a single connection',
+ description: 'Combine built-in and custom skills with enable/disable toggles',
defaults: { name: 'Master Skill', color: '#9333EA' },
inputs: [],
outputs: [{
@@ -205,54 +44,12 @@ export const skillNodes: Record<string, INodeTypeDescription> = {
description: 'Enabled skills and their instructions'
}
]
- },
-
- // Custom Skill - User-created skill
- customSkill: {
- displayName: 'Custom Skill',
- name: 'customSkill',
- icon: '⭐',
- group: ['skill'],
- version: 1,
- subtitle: 'User-defined',
- description: 'User-created custom skill with configurable capabilities',
- defaults: { name: 'Custom Skill', color: '#6366F1' },
- inputs: [],
- outputs: [{
- name: 'skill',
- displayName: 'Skill',
- type: 'main' as NodeConnectionType,
- description: 'Connect to Zeenie skill handle'
- }],
- properties: [
- {
- displayName: 'Skill',
- name: 'selectedSkill',
- type: 'options',
- default: '',
- required: true,
- description: 'Select a user-created skill',
- typeOptions: {
- dynamicOptions: true
- }
- }
- ]
}
};
// List of skill node types for easy identification
export const SKILL_NODE_TYPES = [
- 'assistantPersonality',
- 'whatsappSkill',
- 'memorySkill',
- 'mapsSkill',
- 'httpSkill',
- 'schedulerSkill',
- 'androidSkill',
- 'codeSkill',
- 'webSearchSkill',
- 'masterSkill',
- 'customSkill'
+ 'masterSkill'
];
// Export for nodeDefinitions.ts
diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.ts
index afdbad41..6a79721f 100644
--- a/client/src/nodeDefinitions/specializedAgentNodes.ts
+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts
@@ -69,7 +69,8 @@ export const AI_AGENT_PROPERTIES: INodeProperties[] = [
{ name: 'Anthropic (Claude)', value: 'anthropic' },
{ name: 'Google (Gemini)', value: 'gemini' },
{ name: 'Groq', value: 'groq' },
- { name: 'OpenRouter', value: 'openrouter' }
+ { name: 'OpenRouter', value: 'openrouter' },
+ { name: 'Cerebras', value: 'cerebras' }
],
default: 'openai',
description: 'The AI provider to use (configure API keys in Credentials)'
@@ -124,8 +125,8 @@ export const AI_AGENT_PROPERTIES: INodeProperties[] = [
displayName: 'Maximum Tokens',
name: 'maxTokens',
type: 'number',
- default: 1000,
- typeOptions: { minValue: 1, maxValue: 8192 },
+ default: 4096,
+ typeOptions: { minValue: 1, maxValue: 128000 },
description: 'Maximum number of tokens to generate'
},
{
@@ -314,6 +315,36 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {
inputs: AI_AGENT_INPUTS,
outputs: AI_AGENT_OUTPUTS,
properties: AI_AGENT_PROPERTIES
+ },
+
+ // Autonomous Agent - AI Agent for autonomous operations with Code Mode patterns
+ autonomous_agent: {
+ displayName: 'Autonomous Agent',
+ name: 'autonomous_agent',
+ icon: '🎯',
+ group: ['agent', 'ai'],
+ version: 1,
+ subtitle: 'Autonomous Operations',
+ description: 'AI Agent specialized for autonomous operations. Uses Code Mode patterns (81-98% token savings), agentic loops, progressive discovery, error recovery, and multi-tool orchestration.',
+ defaults: { name: 'Autonomous Agent', color: dracula.purple },
+ inputs: AI_AGENT_INPUTS,
+ outputs: AI_AGENT_OUTPUTS,
+ properties: AI_AGENT_PROPERTIES
+ },
+
+ // Orchestrator Agent - Coordinates multiple agents for complex workflows
+ orchestrator_agent: {
+ displayName: 'Orchestrator Agent',
+ name: 'orchestrator_agent',
+ icon: '🎼',
+ group: ['agent', 'ai'],
+ version: 1,
+ 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,
+ outputs: AI_AGENT_OUTPUTS,
+ properties: AI_AGENT_PROPERTIES
}
};
@@ -322,4 +353,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'];
+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'];
diff --git a/docs-internal/specialized_agent_node_creation.md b/docs-internal/specialized_agent_node_creation.md
index 5585b1bb..eae028db 100644
--- a/docs-internal/specialized_agent_node_creation.md
+++ b/docs-internal/specialized_agent_node_creation.md
@@ -58,6 +58,8 @@ All agent colors use centralized dracula theme constants from `client/src/styles
| `productivity_agent` | Productivity Agent | Productivity workflows agent | `dracula.cyan` |
| `payments_agent` | Payments Agent | Payment processing agent | `dracula.green` |
| `consumer_agent` | Consumer Agent | Consumer interactions agent | `dracula.purple` |
+| `autonomous_agent` | Autonomous Agent | Autonomous operations with Code Mode patterns | `dracula.purple` |
+| `orchestrator_agent` | Orchestrator Agent | Multi-agent coordination and task delegation | `dracula.cyan` |
## Shared AI Agent Properties
@@ -754,13 +756,13 @@ Memory connected to `input-memory` provides conversation history via a two-tier
### Shared Handler Routing
-All 10 specialized agents route to the same backend handler:
+All 12 specialized agents route to the same backend handler:
```python
# In node_executor.py
'android_agent': partial(handle_chat_agent, ai_service=..., database=...),
'coding_agent': partial(handle_chat_agent, ai_service=..., database=...),
-# ... all 10 specialized agents use handle_chat_agent
+# ... all 12 specialized agents use handle_chat_agent
```
This means specialization is purely UI/configuration, not backend behavioral. All agents share:
diff --git a/package-lock.json b/package-lock.json
index 5b81a8ae..41f0a48d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -27,7 +27,7 @@
},
"client": {
"name": "react-flow-client",
- "version": "0.0.12",
+ "version": "0.0.13",
"dependencies": {
"@ant-design/icons": "^6.0.2",
"@eslint/js": "^9.33.0",
diff --git a/package.json b/package.json
index 8a59c3db..3e7747fa 100644
--- a/package.json
+++ b/package.json
@@ -70,6 +70,7 @@
"whatsapp:stop": "whatsapp-rpc stop",
"whatsapp:status": "whatsapp-rpc status",
"whatsapp:api": "whatsapp-rpc api --foreground",
+ "whatsapp:build": "whatsapp-rpc build",
"build": "node scripts/build.js",
"clean": "node scripts/clean.js",
"stop": "node scripts/stop.js",
diff --git a/scripts/build.js b/scripts/build.js
index b6e42869..adb04c5b 100644
--- a/scripts/build.js
+++ b/scripts/build.js
@@ -84,7 +84,11 @@ function installPython() {
process.exit(1);
}
} else {
- if (runSilent('apt --version')) {
+ // Linux package managers
+ if (runSilent('apk --version')) {
+ // Alpine Linux
+ run('apk add --no-cache python3 py3-pip');
+ } else if (runSilent('apt --version')) {
run('sudo apt update && sudo apt install -y python3.12 python3.12-venv');
} else if (runSilent('dnf --version')) {
run('sudo dnf install -y python3.12');
@@ -97,17 +101,25 @@ function installPython() {
}
}
-function installUv() {
+function installUv(pythonCmd) {
console.log(' Installing uv...');
if (isWindows) {
- run('powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"');
- } else {
- run('curl -LsSf https://astral.sh/uv/install.sh | sh');
- }
- if (isWindows) {
- process.env.PATH = `${process.env.USERPROFILE}\\.local\\bin;${process.env.PATH}`;
+ // Windows: use pip (simple and works)
+ run(`${pythonCmd} -m pip install uv`);
+ } else if (isMac) {
+ // macOS: use pip (no PEP 668 issues with Homebrew Python)
+ run(`${pythonCmd} -m pip install uv`);
+ } else if (runSilent('apk --version')) {
+ // Alpine: use pip with --break-system-packages
+ run(`${pythonCmd} -m pip install uv --break-system-packages`);
} else {
- process.env.PATH = `${process.env.HOME}/.local/bin:${process.env.PATH}`;
+ // Other Linux: try pip first, fall back to curl installer
+ if (runSilent(`${pythonCmd} -m pip install uv --break-system-packages`)) {
+ // pip worked
+ } else {
+ run('curl -LsSf https://astral.sh/uv/install.sh | sh');
+ process.env.PATH = `${process.env.HOME}/.local/bin:${process.env.PATH}`;
+ }
}
}
@@ -156,7 +168,7 @@ let uvVersion = getVersion('uv --version');
if (uvVersion) {
console.log(` uv: ${uvVersion}`);
} else {
- installUv();
+ installUv(pyCmd);
uvVersion = getVersion('uv --version');
if (uvVersion) {
console.log(` uv: ${uvVersion}`);
@@ -210,36 +222,15 @@ try {
// Step 4: Install Python dependencies
console.log('[4/5] Installing Python dependencies...');
const serverDir = resolve(ROOT, 'server');
- run('uv venv', serverDir);
+ // Check if .venv exists, skip creation if it does
+ if (!existsSync(resolve(serverDir, '.venv'))) {
+ run('uv venv', serverDir);
+ }
run('uv sync', serverDir);
- // Step 5: Ensure WhatsApp RPC binary is downloaded
- // The whatsapp-rpc postinstall skips download in CI, so we run it explicitly.
- const whatsappBin = resolve(ROOT, 'node_modules', 'whatsapp-rpc', 'bin',
- isWindows ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server');
- const whatsappDownloadScript = resolve(ROOT, 'node_modules', 'whatsapp-rpc', 'scripts', 'download-binary.js');
- if (!existsSync(whatsappBin) && existsSync(whatsappDownloadScript)) {
- console.log('[5/5] Downloading WhatsApp RPC binary...');
- try {
- // Run download script without CI env vars so it doesn't skip
- const dlEnv = { ...process.env };
- delete dlEnv.CI;
- delete dlEnv.GITHUB_ACTIONS;
- const scriptPath = whatsappDownloadScript.replace(/\\/g, '/');
- execSync(`node "${scriptPath}"`, {
- cwd: resolve(ROOT, 'node_modules', 'whatsapp-rpc'),
- stdio: 'inherit',
- shell: true,
- env: dlEnv
- });
- } catch (e) {
- console.log('Warning: Failed to download WhatsApp RPC binary. WhatsApp features will be unavailable.');
- }
- } else if (existsSync(whatsappBin)) {
- console.log('[5/5] WhatsApp RPC binary already present');
- } else {
- console.log('[5/5] WhatsApp RPC package not found, skipping binary download');
- }
+ // Step 5: Verify WhatsApp RPC package
+ console.log('[5/5] Verifying WhatsApp RPC...');
+ run('whatsapp-rpc status', ROOT);
console.log('\nBuild complete.');
diff --git a/scripts/install.js b/scripts/install.js
index 7831f6e6..6102b78c 100644
--- a/scripts/install.js
+++ b/scripts/install.js
@@ -120,6 +120,9 @@ function installUv(pythonCmd) {
} else if (isMac) {
// Use pip on macOS (no PEP 668 issues with Homebrew Python)
run(`${pythonCmd} -m pip install uv`);
+ } else if (runSilent('apk --version')) {
+ // Alpine: use pip (apk doesn't have uv package)
+ run(`${pythonCmd} -m pip install uv --break-system-packages`);
} else {
// Linux: use official installer (avoids PEP 668 externally-managed-environment)
run('curl -LsSf https://astral.sh/uv/install.sh | sh');
@@ -219,7 +222,11 @@ try {
// Install Python dependencies (always needed - venv not included in package)
step++;
console.log(`[${step}/${totalSteps}] Installing Python dependencies...`);
- run('uv venv', serverDir); // 5 min default
+ // Check if .venv exists, skip creation if it does
+ const venvPath = resolve(serverDir, '.venv');
+ if (!existsSync(venvPath)) {
+ run('uv venv', serverDir); // 5 min default
+ }
run('uv sync', serverDir, 600000); // 10 min timeout
// WhatsApp RPC is now an npm dependency - binary downloaded via postinstall
diff --git a/scripts/start.js b/scripts/start.js
index 67da5dfd..79583447 100644
--- a/scripts/start.js
+++ b/scripts/start.js
@@ -227,14 +227,8 @@ if (isProduction) {
// Python backend: use gunicorn in daemon mode, uvicorn in development
services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');
-// WhatsApp RPC: only start if the pre-built binary exists
-const whatsappBin = resolve(ROOT, 'node_modules', 'whatsapp-rpc', 'bin',
- isWindows ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server');
-if (existsSync(whatsappBin)) {
- services.push('npm:whatsapp:api');
-} else {
- log('WhatsApp RPC binary not found, skipping. Run "npm run build" to download it.');
-}
+// WhatsApp RPC service - npm handles package availability
+services.push('npm:whatsapp:api');
if (config.temporalEnabled) {
services.push('npm:temporal:worker');
diff --git a/server/constants.py b/server/constants.py
index d09c2c23..d2380bf5 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -32,6 +32,8 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset([
'productivity_agent',
'payments_agent',
'consumer_agent',
+ 'autonomous_agent',
+ 'orchestrator_agent',
])
AI_MEMORY_TYPES: FrozenSet[str] = frozenset([
@@ -48,16 +50,9 @@ AI_TOOL_TYPES: FrozenSet[str] = frozenset([
# Skill node types (connect to Zeenie's input-skill handle)
# Skills provide SKILL.md context/instructions, not executed as workflow nodes
+# masterSkill: Aggregates built-in skills and user-created skills with inline editing
SKILL_NODE_TYPES: FrozenSet[str] = frozenset([
- 'assistantPersonality',
- 'whatsappSkill',
- 'memorySkill',
- 'mapsSkill',
- 'httpSkill',
- 'schedulerSkill',
- 'androidSkill',
- 'codeSkill',
- 'customSkill',
+ 'masterSkill',
])
# Toolkit node types (aggregate sub-nodes, n8n Sub-Node pattern)
diff --git a/server/core/container.py b/server/core/container.py
index 84d2ddc2..c173c33d 100644
--- a/server/core/container.py
+++ b/server/core/container.py
@@ -13,9 +13,23 @@ from services.auth import AuthService
from services.text import TextService
from services.android_service import AndroidService
from services.user_auth import UserAuthService
-from services.temporal import TemporalClientWrapper
from services.compaction import init_compaction_service
+# Temporal is optional - import with fallback
+try:
+ from services.temporal import TemporalClientWrapper
+ _TEMPORAL_AVAILABLE = True
+except ImportError:
+ TemporalClientWrapper = None
+ _TEMPORAL_AVAILABLE = False
+
+
+def _create_temporal_client(server_address: str, namespace: str):
+ """Factory function for temporal client - returns None if not available."""
+ if not _TEMPORAL_AVAILABLE or TemporalClientWrapper is None:
+ return None
+ return TemporalClientWrapper(server_address=server_address, namespace=namespace)
+
class Container(containers.DeclarativeContainer):
"""Application dependency injection container."""
@@ -41,9 +55,9 @@ class Container(containers.DeclarativeContainer):
database=database
)
- # Temporal client (lazy - only created when temporal_enabled)
+ # Temporal client (lazy - returns None if temporalio not installed)
temporal_client = providers.Singleton(
- TemporalClientWrapper,
+ _create_temporal_client,
server_address=settings.provided.temporal_server_address,
namespace=settings.provided.temporal_namespace,
)
diff --git a/server/core/database.py b/server/core/database.py
index e7b4949a..fb6d8d98 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -12,7 +12,7 @@ from core.config import Settings
from models.database import (
NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput,
ConversationMessage, ToolSchema, UserSkill, ChatMessage, UserSettings,
- TokenUsageMetric, CompactionEvent, SessionTokenState
+ TokenUsageMetric, CompactionEvent, SessionTokenState, ProviderDefaults
)
from models.cache import CacheEntry # SQLite-backed cache for Redis alternative
from models.auth import User # Import User model to ensure table creation
@@ -1482,6 +1482,70 @@ class Database:
logger.error("Failed to save user settings", user_id=user_id, error=str(e))
return False
+ # ============================================================================
+ # Provider Defaults
+ # ============================================================================
+
+ async def get_provider_defaults(self, provider: str) -> Optional[Dict[str, Any]]:
+ """Get default parameters for a provider."""
+ try:
+ async with self.get_session() as session:
+ stmt = select(ProviderDefaults).where(ProviderDefaults.provider == provider.lower())
+ result = await session.execute(stmt)
+ record = result.scalar_one_or_none()
+ if not record:
+ return None
+ return {
+ "temperature": record.temperature,
+ "max_tokens": record.max_tokens,
+ "thinking_enabled": record.thinking_enabled,
+ "thinking_budget": record.thinking_budget,
+ "reasoning_effort": record.reasoning_effort,
+ "reasoning_format": record.reasoning_format,
+ }
+ except Exception as e:
+ logger.error("Failed to get provider defaults", provider=provider, error=str(e))
+ return None
+
+ async def save_provider_defaults(self, provider: str, defaults: Dict[str, Any]) -> bool:
+ """Upsert provider defaults."""
+ try:
+ async with self.get_session() as session:
+ stmt = select(ProviderDefaults).where(ProviderDefaults.provider == provider.lower())
+ result = await session.execute(stmt)
+ record = result.scalar_one_or_none()
+
+ now = datetime.now(timezone.utc)
+ if record:
+ record.temperature = defaults.get("temperature", record.temperature)
+ record.max_tokens = defaults.get("max_tokens", record.max_tokens)
+ record.thinking_enabled = defaults.get("thinking_enabled", record.thinking_enabled)
+ record.thinking_budget = defaults.get("thinking_budget", record.thinking_budget)
+ record.reasoning_effort = defaults.get("reasoning_effort", record.reasoning_effort)
+ record.reasoning_format = defaults.get("reasoning_format", record.reasoning_format)
+ record.updated_at = now
+ else:
+ record = ProviderDefaults(
+ provider=provider.lower(),
+ temperature=defaults.get("temperature", 0.7),
+ max_tokens=defaults.get("max_tokens", 1000),
+ thinking_enabled=defaults.get("thinking_enabled", False),
+ thinking_budget=defaults.get("thinking_budget", 2048),
+ reasoning_effort=defaults.get("reasoning_effort", "medium"),
+ reasoning_format=defaults.get("reasoning_format", "parsed"),
+ created_at=now,
+ updated_at=now
+ )
+ session.add(record)
+
+ await session.commit()
+ logger.info(f"[DB] Provider defaults saved for: {provider}")
+ return True
+
+ except Exception as e:
+ logger.error("Failed to save provider defaults", provider=provider, error=str(e))
+ return False
+
# ============================================================================
# Token Usage Metrics
# ============================================================================
@@ -1557,7 +1621,10 @@ class Database:
async def get_or_create_session_token_state(
self, session_id: str
) -> Dict[str, Any]:
- """Get or create token state for a session."""
+ """Get or create token state for a session.
+
+ Handles race conditions when multiple requests try to create the same session.
+ """
try:
async with self.get_session() as session:
stmt = select(SessionTokenState).where(
@@ -1567,13 +1634,34 @@ class Database:
state = result.scalar_one_or_none()
if not state:
- state = SessionTokenState(
- session_id=session_id,
- updated_at=datetime.now(timezone.utc)
- )
- session.add(state)
- await session.commit()
- await session.refresh(state)
+ try:
+ state = SessionTokenState(
+ session_id=session_id,
+ updated_at=datetime.now(timezone.utc)
+ )
+ session.add(state)
+ await session.commit()
+ await session.refresh(state)
+ except IntegrityError:
+ # Race condition: another request created the session
+ # Rollback and fetch the existing record
+ await session.rollback()
+ result = await session.execute(stmt)
+ state = result.scalar_one_or_none()
+ if not state:
+ # Shouldn't happen, but return defaults if it does
+ return {
+ "session_id": session_id,
+ "cumulative_input_tokens": 0,
+ "cumulative_output_tokens": 0,
+ "cumulative_cache_tokens": 0,
+ "cumulative_reasoning_tokens": 0,
+ "cumulative_total": 0,
+ "last_compaction_at": None,
+ "compaction_count": 0,
+ "custom_threshold": None,
+ "compaction_enabled": True
+ }
return {
"session_id": state.session_id,
diff --git a/server/main.py b/server/main.py
index 11d012af..e36664ca 100644
--- a/server/main.py
+++ b/server/main.py
@@ -132,6 +132,10 @@ async def lifespan(app: FastAPI):
from services.temporal import TemporalClientWrapper, TemporalExecutor
from services.temporal.worker import TemporalWorkerManager
+ # Check if temporal is actually available (temporalio installed)
+ if TemporalClientWrapper is None:
+ raise ImportError("temporalio not installed")
+
logger.info(
"Initializing Temporal integration",
server_address=settings.temporal_server_address,
@@ -141,6 +145,8 @@ async def lifespan(app: FastAPI):
# Connect Temporal client
temporal_client_wrapper = container.temporal_client()
+ if temporal_client_wrapper is None:
+ raise ImportError("temporalio not installed")
temporal_client = await temporal_client_wrapper.connect()
# Create and set the Temporal executor on WorkflowService
@@ -178,7 +184,9 @@ async def lifespan(app: FastAPI):
# Disconnect Temporal client if connected
if settings.temporal_enabled:
try:
- await container.temporal_client().disconnect()
+ temporal_client_wrapper = container.temporal_client()
+ if temporal_client_wrapper is not None:
+ await temporal_client_wrapper.disconnect()
except Exception:
pass
@@ -285,9 +293,11 @@ async def health_check():
}
if settings.temporal_enabled:
try:
- temporal_status["connected"] = container.temporal_client().is_connected
- temporal_status["server_address"] = settings.temporal_server_address
- temporal_status["task_queue"] = settings.temporal_task_queue
+ temporal_client_wrapper = container.temporal_client()
+ if temporal_client_wrapper is not None:
+ temporal_status["connected"] = temporal_client_wrapper.is_connected
+ temporal_status["server_address"] = settings.temporal_server_address
+ temporal_status["task_queue"] = settings.temporal_task_queue
except Exception:
pass
diff --git a/server/models/database.py b/server/models/database.py
index 57029658..b31850f9 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -263,6 +263,33 @@ class UserSettings(SQLModel, table=True):
)
+class ProviderDefaults(SQLModel, table=True):
+ """LLM provider default parameters - persisted across server restarts.
+
+ Database is the source of truth for provider-specific default parameters.
+ These defaults are applied to new AI nodes and can be overridden per-node.
+ """
+
+ __tablename__ = "provider_defaults"
+
+ id: Optional[int] = Field(default=None, primary_key=True)
+ provider: str = Field(unique=True, index=True, max_length=50) # openai, anthropic, gemini, etc.
+ temperature: float = Field(default=0.7)
+ max_tokens: int = Field(default=1000)
+ thinking_enabled: bool = Field(default=False)
+ thinking_budget: int = Field(default=2048)
+ reasoning_effort: str = Field(default="medium", max_length=20) # low, medium, high
+ reasoning_format: str = Field(default="parsed", max_length=20) # parsed, hidden
+ created_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), server_default=func.now())
+ )
+ updated_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc),
+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())
+ )
+
+
# =============================================================================
# Token Tracking and Memory Compaction
# =============================================================================
diff --git a/server/pyproject.toml b/server/pyproject.toml
index 0e46aa52..9b76f51d 100644
--- a/server/pyproject.toml
+++ b/server/pyproject.toml
@@ -45,9 +45,6 @@ dependencies = [
# Dependency Injection
"dependency-injector>=4.40.0",
- # Temporal (distributed execution)
- "temporalio>=1.7.0",
-
# Utils
"python-dotenv>=1.0.0",
"apscheduler>=3.10.0",
@@ -63,6 +60,9 @@ dev = [
"pytest>=8.0.0",
"ruff>=0.8.0",
]
+temporal = [
+ "temporalio>=1.7.0",
+]
extra-ai = [
"langchain-cerebras>=0.1.0",
]
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 4fbade3b..44992416 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1146,6 +1146,7 @@ async def handle_android_relay_connect(data: Dict[str, Any], websocket: WebSocke
try:
client, error = await get_relay_client(url, api_key)
if client:
+ logger.info(f"[WebSocket] Android relay connect success, qr_data present: {bool(client.qr_data)}, session_token: {client.session_token}")
return {
"success": True,
"connected": True,
@@ -1636,8 +1637,8 @@ async def handle_get_skill_content(data: Dict[str, Any], websocket: WebSocket) -
skill_name = data["skill_name"]
skill_loader = get_skill_loader()
- # Try to load the skill
- skill = skill_loader.load_skill(skill_name)
+ # Use load_skill_async which checks both filesystem and database
+ skill = await skill_loader.load_skill_async(skill_name)
if skill:
return {
"success": True,
@@ -1649,20 +1650,6 @@ async def handle_get_skill_content(data: Dict[str, Any], websocket: WebSocket) -
"timestamp": time.time()
}
- # Try loading from database for user skills
- database = container.database()
- user_skill = await database.get_user_skill(skill_name)
- if user_skill:
- return {
- "success": True,
- "skill_name": skill_name,
- "instructions": user_skill.instructions,
- "description": user_skill.description,
- "allowed_tools": user_skill.allowed_tools.split(',') if user_skill.allowed_tools else [],
- "is_builtin": False,
- "timestamp": time.time()
- }
-
return {"success": False, "error": f"Skill '{skill_name}' not found"}
@@ -1894,7 +1881,8 @@ async def handle_delete_user_skill(data: Dict[str, Any], websocket: WebSocket) -
"name": data["name"],
"timestamp": time.time()
})
- return {"deleted": True, "name": data["name"], "timestamp": time.time()}
+ logger.info(f"[Skills] Deleted user skill: {data['name']}")
+ return {"success": True, "deleted": True, "name": data["name"], "timestamp": time.time()}
return {"success": False, "error": f"Skill '{data['name']}' not found"}
@@ -2011,6 +1999,41 @@ async def handle_save_user_settings(data: Dict[str, Any], websocket: WebSocket)
return {"success": False, "error": "Failed to save settings"}
+# ============================================================================
+# Provider Defaults Handlers
+# ============================================================================
+
+@ws_handler()
+async def handle_get_provider_defaults(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get default parameters for a provider."""
+ database = container.database()
+ provider = data.get("provider", "").lower()
+ defaults = await database.get_provider_defaults(provider)
+
+ # Return defaults or standard fallback values
+ return {
+ "provider": provider,
+ "defaults": defaults or {
+ "temperature": 0.7,
+ "max_tokens": 1000,
+ "thinking_enabled": False,
+ "thinking_budget": 2048,
+ "reasoning_effort": "medium",
+ "reasoning_format": "parsed",
+ }
+ }
+
+
+@ws_handler()
+async def handle_save_provider_defaults(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Save default parameters for a provider."""
+ database = container.database()
+ provider = data.get("provider", "").lower()
+ defaults = data.get("defaults", {})
+ success = await database.save_provider_defaults(provider, defaults)
+ return {"success": success, "provider": provider}
+
+
# ============================================================================
# Compaction Handlers
# ============================================================================
@@ -2165,6 +2188,10 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"get_user_settings": handle_get_user_settings,
"save_user_settings": handle_save_user_settings,
+ # Provider Defaults
+ "get_provider_defaults": handle_get_provider_defaults,
+ "save_provider_defaults": handle_save_provider_defaults,
+
# Compaction
"get_compaction_stats": handle_get_compaction_stats,
"configure_compaction": handle_configure_compaction,
diff --git a/server/services/ai.py b/server/services/ai.py
index 36ffc455..97940e7c 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2323,6 +2323,8 @@ class AIService:
'productivity_agent': 'delegate_to_productivity_agent',
'payments_agent': 'delegate_to_payments_agent',
'consumer_agent': 'delegate_to_consumer_agent',
+ 'autonomous_agent': 'delegate_to_autonomous_agent',
+ 'orchestrator_agent': 'delegate_to_orchestrator_agent',
# Android service nodes (direct tool usage)
'batteryMonitor': 'android_battery',
'networkMonitor': 'android_network',
@@ -2370,6 +2372,8 @@ class AIService:
'productivity_agent': 'ONE-SHOT delegation to Productivity Agent. Call ONCE per task, returns task_id. Agent works in background - do NOT re-call.',
'payments_agent': 'ONE-SHOT delegation to Payments Agent. Call ONCE per task, returns task_id. Agent works in background - do NOT re-call.',
'consumer_agent': 'ONE-SHOT delegation to Consumer Agent. Call ONCE per task, returns task_id. Agent works in background - do NOT re-call.',
+ 'autonomous_agent': 'ONE-SHOT delegation to Autonomous Agent. Call ONCE per task, returns task_id. Agent works in background using Code Mode patterns - do NOT re-call.',
+ 'orchestrator_agent': 'ONE-SHOT delegation to Orchestrator Agent. Call ONCE per task, returns task_id. Coordinates multiple agents - do NOT re-call.',
# Android service nodes (direct tool usage)
'batteryMonitor': 'Monitor Android battery status, level, charging state, temperature, and health.',
'networkMonitor': 'Monitor Android network connectivity, type, and internet availability.',
@@ -2929,7 +2933,7 @@ class AIService:
return CheckDelegatedTasksSchema
# AI Agent delegation schema (fire-and-forget async delegation)
- if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'):
+ if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent'):
agent_label = params.get('label', node_type)
class DelegateToAgentSchema(BaseModel):
diff --git a/server/services/android/client.py b/server/services/android/client.py
index 678b1950..8cae4a94 100644
--- a/server/services/android/client.py
+++ b/server/services/android/client.py
@@ -119,7 +119,7 @@ class RelayWebSocketClient:
# Broadcast QR data to frontend
if self.qr_data:
- await broadcast_qr_code(self.qr_data)
+ await broadcast_qr_code(self.qr_data, self.session_token)
# Start background tasks
self._receive_task = asyncio.create_task(self._receive_loop())
@@ -329,7 +329,7 @@ class RelayWebSocketClient:
self.session_token = params.get("session_token")
self.qr_data = params.get("qr_data")
if self.qr_data:
- await broadcast_qr_code(self.qr_data)
+ await broadcast_qr_code(self.qr_data, self.session_token)
async def _handle_pairing_connected(self, params: dict):
"""Handle pairing.connected event."""
diff --git a/server/services/compaction.py b/server/services/compaction.py
index 3ec09ea1..443709f6 100644
--- a/server/services/compaction.py
+++ b/server/services/compaction.py
@@ -18,6 +18,35 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+def _extract_text_from_response(content) -> str:
+ """Extract text content from various LLM response formats.
+
+ Handles:
+ - String content (OpenAI, Anthropic)
+ - List of content blocks (Gemini format: [{"type": "text", "text": "..."}])
+ - Other complex formats
+ """
+ # Handle list content (Gemini format)
+ if isinstance(content, list):
+ text_parts = []
+ for block in content:
+ if isinstance(block, dict):
+ if block.get('type') == 'text' and block.get('text'):
+ text_parts.append(block['text'])
+ elif 'text' in block:
+ text_parts.append(str(block['text']))
+ elif isinstance(block, str):
+ text_parts.append(block)
+ return '\n'.join(text_parts)
+
+ # Handle string content
+ if isinstance(content, str):
+ return content
+
+ # Fallback
+ return str(content) if content else ""
+
+
class CompactionConfig(BaseModel):
"""Provider-agnostic compaction configuration."""
enabled: bool = True
@@ -161,7 +190,8 @@ Provide a concise but complete summary."""
from langchain_core.messages import HumanMessage
response = await llm.ainvoke([HumanMessage(content=prompt)])
- summary = response.content if hasattr(response, 'content') else str(response)
+ raw_content = response.content if hasattr(response, 'content') else str(response)
+ summary = _extract_text_from_response(raw_content)
new_memory = f"# Conversation Summary (Compacted)\n*Generated: {datetime.now(timezone.utc).isoformat()}*\n\n{summary}"
diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.py
index 33d08d25..413c59b3 100644
--- a/server/services/handlers/ai.py
+++ b/server/services/handlers/ai.py
@@ -79,7 +79,13 @@ async def _collect_agent_connections(
if target_handle == 'input-memory':
if source_node.get('type') == 'simpleMemory':
memory_params = await database.get_node_parameters(source_node_id) or {}
- memory_session_id = memory_params.get('sessionId', 'default')
+ # Auto-derive session from connected AI Agent's node_id
+ # Memory node's sessionId is used only if explicitly set (not empty or 'default')
+ configured_session = memory_params.get('sessionId', '')
+ if configured_session and configured_session != 'default':
+ memory_session_id = configured_session # Explicit override
+ else:
+ memory_session_id = node_id # Auto: use AI Agent's node_id
window_size = int(memory_params.get('windowSize', 10))
memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')
long_term_enabled = memory_params.get('longTermEnabled', False)
@@ -93,7 +99,7 @@ async def _collect_agent_connections(
'long_term_enabled': long_term_enabled,
'retrieval_count': retrieval_count
}
- logger.debug(f"{log_prefix} Connected memory node: session={memory_session_id}, content_length={len(memory_content)}")
+ logger.debug(f"{log_prefix} Connected memory node: session={memory_session_id} (auto={not configured_session or configured_session == 'default'}), content_length={len(memory_content)}")
# Skill detection - nodes connected to input-skill handle
elif target_handle == 'input-skill':
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 47eec2a6..4fa38973 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -133,8 +133,8 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
return await _execute_check_delegated_tasks(tool_args, config)
# AI Agent delegation (fire-and-forget async delegation)
- # Includes specialized agents: android_agent, coding_agent, web_agent, task_agent, social_agent
- if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'):
+ # Includes specialized agents: android_agent, coding_agent, web_agent, task_agent, social_agent, autonomous_agent
+ if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent'):
return await _execute_delegated_agent(tool_args, config)
# Generic fallback for unknown node types
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index b9ac1c7a..518c993f 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -120,6 +120,8 @@ class NodeExecutor:
'productivity_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
'payments_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
'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),
'simpleMemory': handle_simple_memory,
# Maps
'gmaps_create': partial(handle_create_map, maps_service=self.maps_service),
diff --git a/server/services/skill_loader.py b/server/services/skill_loader.py
index bb67bba0..1b4cb8c5 100644
--- a/server/services/skill_loader.py
+++ b/server/services/skill_loader.py
@@ -184,9 +184,9 @@ class SkillLoader:
if name in self._cache:
return self._cache[name]
- # Check registry
+ # Check registry (filesystem skills only - use load_skill_async for user skills)
if name not in self._registry:
- logger.warning(f"[SkillLoader] Skill not found: {name}")
+ logger.debug(f"[SkillLoader] Skill not in registry: {name}")
return None
metadata = self._registry[name]
@@ -275,20 +275,24 @@ class SkillLoader:
# Load from database
if self._database:
try:
- user_skill = await self._database.get_user_skill_by_name(name)
+ user_skill = await self._database.get_user_skill(name)
if user_skill:
- allowed_tools = []
- if user_skill.allowed_tools:
- allowed_tools = [t.strip() for t in user_skill.allowed_tools.split(',')]
+ # user_skill is a dict from _skill_to_dict()
+ allowed_tools = user_skill.get('allowed_tools', [])
+ if isinstance(allowed_tools, str):
+ allowed_tools = [t.strip() for t in allowed_tools.split(',') if t.strip()]
- metadata_dict = {}
- if user_skill.metadata_json:
+ metadata_dict = user_skill.get('metadata', {})
+ if isinstance(metadata_dict, str):
import json
- metadata_dict = json.loads(user_skill.metadata_json)
+ try:
+ metadata_dict = json.loads(metadata_dict) if metadata_dict else {}
+ except json.JSONDecodeError:
+ metadata_dict = {}
metadata = SkillMetadata(
- name=user_skill.name,
- description=user_skill.description,
+ name=user_skill.get('name', name),
+ description=user_skill.get('description', ''),
allowed_tools=allowed_tools,
metadata=metadata_dict,
path=None
@@ -296,11 +300,12 @@ class SkillLoader:
skill = Skill(
metadata=metadata,
- instructions=user_skill.instructions,
+ instructions=user_skill.get('instructions', ''),
scripts={},
references={}
)
+ logger.info(f"[SkillLoader] Loaded user skill from database: {name}")
self._cache[name] = skill
return skill
except Exception as e:
diff --git a/server/services/temporal/__init__.py b/server/services/temporal/__init__.py
index 9cd29db2..757c23c4 100644
--- a/server/services/temporal/__init__.py
+++ b/server/services/temporal/__init__.py
@@ -15,9 +15,19 @@ When TEMPORAL_ENABLED=true:
When TEMPORAL_ENABLED=false (default):
- Falls back to the existing parallel/sequential executor
-"""
-from .executor import TemporalExecutor
-from .client import TemporalClientWrapper
+Note: temporalio is an optional dependency. Import with try/except.
+"""
__all__ = ["TemporalExecutor", "TemporalClientWrapper"]
+
+# Lazy imports - temporalio is optional
+TemporalExecutor = None
+TemporalClientWrapper = None
+
+try:
+ from .executor import TemporalExecutor
+ from .client import TemporalClientWrapper
+except ImportError:
+ # temporalio not installed - Temporal features disabled
+ pass
diff --git a/server/skills/assistant/compaction-skill/SKILL.md b/server/skills/assistant/compaction-skill/SKILL.md
new file mode 100644
index 00000000..55ebe0a1
--- /dev/null
+++ b/server/skills/assistant/compaction-skill/SKILL.md
@@ -0,0 +1,157 @@
+---
+name: compaction-skill
+description: Manage memory compaction by summarizing conversation history when approaching token limits
+allowed-tools: memory-save memory-get
+metadata:
+ author: machina
+ version: "1.0"
+ category: memory
+ icon: "📦"
+ color: "#8B5CF6"
+---
+
+# Memory Compaction Skill
+
+You have the ability to compact conversation memory when it grows too large. Compaction transforms verbose conversation history into a structured summary that preserves essential context while reducing token usage.
+
+## When to Compact
+
+Compact memory when:
+- The system indicates token threshold is approaching
+- Conversation history becomes repetitive or verbose
+- You need to preserve important context but reduce size
+- Starting a new phase of work after completing a major task
+
+## Compaction Summary Structure
+
+When compacting, create a summary with these 5 sections:
+
+### 1. Task Overview
+What the user is trying to accomplish. Include:
+- Primary goal or objective
+- Key constraints or requirements
+- Scope of the work
+
+### 2. Current State
+What's been completed and what's in progress:
+- Completed tasks and their outcomes
+- Work currently in flight
+- Pending decisions or blockers
+
+### 3. Important Discoveries
+Key findings, decisions, or problems encountered:
+- Technical discoveries or insights
+- Decisions made and their rationale
+- Problems encountered and solutions applied
+- User preferences learned
+
+### 4. Next Steps
+What needs to happen next:
+- Immediate actions required
+- Planned approach for remaining work
+- Dependencies or prerequisites
+
+### 5. Context to Preserve
+Critical details that must be retained:
+- Specific values, IDs, or references
+- User preferences or constraints
+- Technical details needed for continuity
+- Any warnings or caveats
+
+## Compaction Format
+
+Output the compacted summary in this format:
+
+```markdown
+# Conversation Summary (Compacted)
+*Generated: [ISO timestamp]*
+
+## Task Overview
+[1-3 sentences describing the goal]
+
+## Current State
+- [Completed item 1]
+- [Completed item 2]
+- [In progress: description]
+
+## Important Discoveries
+- [Discovery 1 with context]
+- [Decision made: rationale]
+- [Problem solved: approach]
+
+## Next Steps
+1. [Next action]
+2. [Following action]
+
+## Context to Preserve
+- [Critical detail 1]
+- [Critical detail 2]
+```
+
+## Best Practices
+
+1. **Be Concise**: Each section should be brief but complete
+2. **Preserve Specifics**: Keep exact values, names, and references
+3. **Capture Decisions**: Record WHY decisions were made, not just WHAT
+4. **Include Failures**: Document what didn't work to avoid repetition
+5. **Maintain Continuity**: Summary should allow seamless continuation
+
+## What NOT to Include
+
+- Verbose back-and-forth dialogue
+- Redundant information
+- Superseded decisions (only keep final decisions)
+- Exploratory tangents that didn't lead anywhere
+- Standard pleasantries or acknowledgments
+
+## Example Compaction
+
+**Before** (verbose history):
+```
+Human: Can you help me debug this Python function?
+AI: Of course! Please share the function.
+Human: Here's the function: def calculate(x): return x * 2
+AI: I see the function. What issue are you experiencing?
+Human: It returns None sometimes
+AI: That's interesting. Can you show me an example input?
+Human: calculate("5") returns None
+AI: Ah, I see the issue! When you pass a string...
+[continues for 50+ messages]
+```
+
+**After** (compacted):
+```markdown
+# Conversation Summary (Compacted)
+*Generated: 2025-02-13T10:30:00Z*
+
+## Task Overview
+Debug Python function `calculate(x)` that returns None for some inputs.
+
+## Current State
+- Identified root cause: string inputs cause implicit None return
+- Implemented fix with type checking and conversion
+- Tests passing for int, float, and string inputs
+
+## Important Discoveries
+- Original function had no type validation
+- String multiplication in Python doesn't raise error but behaves unexpectedly
+- User prefers explicit error messages over silent failures
+
+## Next Steps
+1. Add input validation for edge cases (None, empty string)
+2. Write unit tests for the fixed function
+
+## Context to Preserve
+- Function location: `utils/math_helpers.py:45`
+- User wants to maintain backward compatibility
+- Prefer raising ValueError over returning None
+```
+
+## Integration with Memory System
+
+When compaction is triggered:
+1. The compacted summary replaces the current memory content
+2. New conversation messages are appended after the summary
+3. The summary header indicates when compaction occurred
+
+This allows conversation to continue naturally while maintaining reduced token usage.
diff --git a/server/skills/assistant/humanify-skill/SKILL.md b/server/skills/assistant/humanify-skill/SKILL.md
new file mode 100644
index 00000000..47bd446c
--- /dev/null
+++ b/server/skills/assistant/humanify-skill/SKILL.md
@@ -0,0 +1,210 @@
+---
+name: humanify-skill
+description: Output human-readable text in pretty formats instead of raw markdown or code blocks
+metadata:
+ author: machina
+ version: "1.0"
+ category: formatting
+ icon: "✨"
+ color: "#F59E0B"
+---
+
+# Humanify Output Skill
+
+Format your responses for human readability. Output clean, pretty text that's easy to scan and understand - not raw markdown syntax or code-heavy formatting.
+
+## Core Principles
+
+1. **Plain Language First**: Write naturally, as if speaking to someone
+2. **Visual Clarity**: Use spacing, indentation, and structure for scannability
+3. **No Raw Syntax**: Avoid showing markdown symbols, JSON, or code unless specifically requested
+4. **Progressive Detail**: Lead with key information, details follow
+
+## Formatting Guidelines
+
+### Instead of Markdown Headers
+```
+Bad: ## Section Title
+Good: SECTION TITLE
+ -------------
+```
+
+### Instead of Bullet Lists with Symbols
+```
+Bad: - Item one
+ - Item two
+
+Good: Item one
+ Item two
+
+ or: * Item one
+ * Item two
+```
+
+### Instead of Code Blocks for Data
+```
+Bad: ```json
+ {"name": "John", "age": 30}
+ ```
+
+Good: Name: John
+ Age: 30
+```
+
+### Instead of Tables with Pipes
+```
+Bad: | Name | Value |
+ |------|-------|
+ | Foo | 123 |
+
+Good: Name Value
+ ---- -----
+ Foo 123
+```
+
+### Instead of Raw URLs
+```
+Bad: Check https://example.com/very/long/path/to/resource
+
+Good: Check the resource page (link available)
+ or: Resource: example.com
+```
+
+## Response Patterns
+
+### For Status Updates
+```
+Status: Complete
+Time: 2.3 seconds
+Result: Successfully processed 15 items
+
+Details:
+ Processed: 15
+ Skipped: 2
+ Errors: 0
+```
+
+### For Lists of Items
+```
+Found 3 matching files:
+
+ 1. config.json
+ Location: /app/settings
+ Modified: Today
+
+ 2. config.backup.json
+ Location: /app/backups
+ Modified: Yesterday
+
+ 3. config.old.json
+ Location: /archive
+ Modified: Last week
+```
+
+### For Explanations
+```
+The function calculates the total by:
+
+ First, it gathers all input values
+ Then, it filters out any invalid entries
+ Finally, it sums the remaining numbers
+
+Note: Empty inputs are treated as zero.
+```
+
+### For Errors or Warnings
+```
+Could not complete the request.
+
+Reason: The file was not found at the specified location.
+
+Suggestions:
+ Check if the file path is correct
+ Verify the file exists
+ Ensure you have read permissions
+```
+
+### For Confirmations
+```
+Done! Created new user account.
+
+ Username: jsmith
+ Role: Editor
+
+Next: The user will receive a welcome email shortly.
+```
+
+## When to Use Each Style
+
+### Use Pretty Formatting When:
+- Showing results or status
+- Explaining concepts
+- Listing options or items
+- Providing instructions
+- Displaying data summaries
+
+### Keep Technical Formatting When:
+- User explicitly requests code/markdown
+- Showing code that needs to be copied
+- Displaying configuration files
+- Technical documentation
+- API responses that need exact format
+
+## Typography Tips
+
+### Visual Separators
+```
+Section breaks: ---------------
+Light dividers: . . . . . . . .
+Box drawing: +-------------+
+ | Content |
+ +-------------+
+```
+
+### Emphasis Without Markdown
+```
+Instead of **bold**: Use CAPS or spacing
+Instead of *italic*: Use quotes or context
+Instead of `code`: Use clear naming
+```
+
+### Spacing for Clarity
+```
+Group related items with spacing:
+
+ Primary Actions
+ Save changes
+ Submit form
+
+ Secondary Actions
+ Cancel
+ Reset
+```
+
+## Examples
+
+### Bad (Raw Markdown)
+```
+### Results
+- **Found**: 5 files
+- **Size**: 2.3MB
+- **Status**: `complete`
+
+See [documentation](https://docs.example.com) for more info.
+```
+
+### Good (Humanified)
+```
+RESULTS
+-------
+Found: 5 files
+Size: 2.3 MB
+Status: Complete
+
+See the documentation for more details.
+```
+
+## Remember
+
+The goal is communication, not formatting. Choose the clearest way to convey information to a human reader. When in doubt, write it as you would explain it to a colleague standing next to you.