Skip to content

Self-improving AI Employees for everyone

feat: add writeTodos tool node for AI agent task planning

trohitgb9fb9b754119
diff --git a/client/src/nodeDefinitions/toolNodes.ts b/client/src/nodeDefinitions/toolNodes.ts
index 312ad5e9..f27696f7 100644
--- a/client/src/nodeDefinitions/toolNodes.ts
+++ b/client/src/nodeDefinitions/toolNodes.ts
@@ -221,6 +221,50 @@ export const toolNodes: Record<string, INodeTypeDescription> = {
}
}
]
+ },
+
+ // Write Todos Tool - allows AI Agent to plan and track complex multi-step tasks
+ writeTodos: {
+ displayName: 'Write Todos',
+ name: 'writeTodos',
+ icon: '\u{1F4DD}',
+ group: ['tool', 'ai'],
+ version: 1,
+ subtitle: 'Task Planning',
+ description: 'Create and manage a structured task list for complex multi-step operations. Works as AI tool OR standalone workflow node.',
+ defaults: { name: 'Write Todos', color: '#bd93f9' },
+ inputs: [],
+ outputs: [
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ },
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Todo list output for workflow use'
+ }
+ ],
+ properties: [
+ {
+ displayName: 'Tool Name',
+ name: 'toolName',
+ type: 'string',
+ default: 'write_todos',
+ description: 'Name visible to the AI agent'
+ },
+ {
+ displayName: 'Tool Description',
+ name: 'toolDescription',
+ type: 'string',
+ default: 'Create and manage a structured task list. Use for complex multi-step tasks (3+ steps). Each todo has content and status (pending, in_progress, completed).',
+ typeOptions: { rows: 3 },
+ description: 'Description for the AI agent'
+ }
+ ]
}
};
@@ -229,4 +273,4 @@ export const toolNodes: Record<string, INodeTypeDescription> = {
// ============================================================================
// List of tool node types for identification
-export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'duckduckgoSearch', 'taskManager'];
+export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'duckduckgoSearch', 'taskManager', 'writeTodos'];
diff --git a/server/constants.py b/server/constants.py
index df2c8184..e7d2a283 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -53,6 +53,7 @@ AI_TOOL_TYPES: FrozenSet[str] = frozenset([
'currentTimeTool',
'duckduckgoSearch',
'androidTool',
+ 'writeTodos',
])
# Skill node types (connect to Zeenie's input-skill handle)
diff --git a/server/services/ai.py b/server/services/ai.py
index a33631eb..035a2e4c 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2437,6 +2437,7 @@ class AIService:
'serperSearch': 'serper_search',
'perplexitySearch': 'perplexity_search',
'taskManager': 'task_manager',
+ 'writeTodos': 'write_todos',
'timer': 'timer',
'cronScheduler': 'cron_scheduler',
# Filesystem and shell tools (deepagents backends)
@@ -2513,6 +2514,7 @@ class AIService:
'gmaps_locations': 'Geocode addresses to coordinates or reverse geocode coordinates to addresses using Google Maps.',
'gmaps_nearby_places': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.',
'taskManager': 'Track delegated sub-agent tasks. Operations: list_tasks (see all tasks), get_task (check specific task status/result), mark_done (cleanup completed tasks).',
+ 'writeTodos': 'Create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. Only use this tool if you think it will be helpful in staying organized. If the user\'s request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly. Use for complex multi-step tasks (3+ steps), non-trivial planning, or when user explicitly requests a todo list. Task states: pending, in_progress, completed. Mark tasks as in_progress BEFORE beginning work, completed IMMEDIATELY after finishing. Remove irrelevant tasks. Break complex tasks into smaller steps.',
'timer': 'Wait/sleep for a specified duration. Specify duration (1-3600) and unit (seconds, minutes, or hours). Returns timestamp and elapsed time after waiting.',
'cronScheduler': 'Schedule a delayed or recurring execution. Supports seconds, minutes, hours, daily, weekly, monthly frequencies with timezone. Use frequency to set schedule type, then set the relevant interval/time parameters.',
# Filesystem and shell tools (deepagents backends)
@@ -3228,6 +3230,36 @@ class AIService:
file_filter: Optional[str] = Field(default=None, description="Glob to filter files for grep (e.g. '*.py')")
return FsSearchSchema
+ # Write Todos schema (dedicated AI tool for task planning)
+ if node_type == 'writeTodos':
+ from enum import Enum as PyEnum
+
+ class TodoStatus(str, PyEnum):
+ pending = "pending"
+ in_progress = "in_progress"
+ completed = "completed"
+
+ class TodoItem(BaseModel):
+ """A single todo item."""
+ content: str = Field(description="Task description")
+ status: TodoStatus = Field(
+ default=TodoStatus.pending,
+ description="Task status: pending, in_progress, or completed"
+ )
+
+ class WriteTodosSchema(BaseModel):
+ """Create and manage a structured task list for complex multi-step operations.
+
+ Use for tasks requiring 3+ steps. Each todo has content and status.
+ Mark first task(s) as in_progress immediately. Update as you work.
+ Skip this tool for simple tasks that take less than 3 steps.
+ """
+ todos: List[TodoItem] = Field(
+ description="List of todo items with content and status"
+ )
+
+ return WriteTodosSchema
+
# Task Manager schema (dual-purpose: AI tool + workflow node)
if node_type == 'taskManager':
class TaskManagerSchema(BaseModel):
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index e7a98bd7..1c37376e 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -137,6 +137,9 @@ from .tools import (
handle_task_manager,
)
+# Todo handler
+from .todo import execute_write_todos, handle_write_todos
+
__all__ = [
# AI
'handle_ai_agent',
@@ -210,4 +213,7 @@ __all__ = [
# Tools
'execute_tool',
'handle_task_manager',
+ # Todo
+ 'execute_write_todos',
+ 'handle_write_todos',
]
diff --git a/server/services/handlers/todo.py b/server/services/handlers/todo.py
new file mode 100644
index 00000000..c5d58189
--- /dev/null
+++ b/server/services/handlers/todo.py
@@ -0,0 +1,73 @@
+"""Write Todos handler -- manages structured task lists for AI agents.
+
+Dual-purpose: works as a workflow node (handle_write_todos) and as an
+AI Agent tool (execute_write_todos). Follows the pattern of browser.py,
+search.py, etc. Delegates state management to TodoService.
+"""
+
+from typing import Any, Dict
+
+from core.logging import get_logger
+from services.todo_service import get_todo_service
+
+logger = get_logger(__name__)
+
+
+async def handle_write_todos(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Handle writeTodos as a workflow node.
+
+ Standard workflow handler signature matching node_executor registry.
+ """
+ config = {
+ "node_id": node_id,
+ "workflow_id": context.get("workflow_id", ""),
+ "broadcaster": context.get("broadcaster"),
+ }
+ return await execute_write_todos(parameters, config)
+
+
+async def execute_write_todos(
+ tool_args: Dict[str, Any],
+ config: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Execute write_todos tool call from AI Agent.
+
+ Args:
+ tool_args: LLM-provided args matching WriteTodosSchema.
+ config: Tool config (node_id, workflow_id, broadcaster, etc.)
+
+ Returns:
+ Dict with JSON-formatted todo list for LLM.
+ """
+ todos_input = tool_args.get("todos", [])
+ workflow_id = config.get("workflow_id", "")
+ node_id = config.get("node_id", "")
+ broadcaster = config.get("broadcaster")
+
+ session_key = workflow_id or node_id or "default"
+
+ service = get_todo_service()
+ stored = service.write(session_key, todos_input)
+
+ # Broadcast todo update for real-time UI
+ if broadcaster and node_id:
+ await broadcaster.update_node_status(
+ node_id,
+ "executing",
+ {"phase": "todo_update", "todos": stored},
+ workflow_id=workflow_id,
+ )
+
+ logger.info("[WriteTodos] Updated %d todos (session=%s)", len(stored), session_key)
+
+ return {
+ "success": True,
+ "message": f"Updated todo list ({len(stored)} items)",
+ "todos": service.format_for_llm(session_key),
+ "count": len(stored),
+ }
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index abf49371..3c2af1a0 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -184,6 +184,11 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
if node_type == 'gmaps_nearby_places':
return await _execute_nearby_places(tool_args, config.get('parameters', {}))
+ # Write Todos (dedicated AI tool for task planning)
+ if node_type == 'writeTodos':
+ from services.handlers.todo import execute_write_todos
+ return await execute_write_todos(tool_args, config)
+
# Task Manager (dual-purpose: AI tool + workflow node)
if node_type == 'taskManager':
return await _execute_task_manager(tool_args, config)
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 524af87f..ab738fd5 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -48,6 +48,7 @@ from services.handlers.crawlee import handle_crawlee_scraper
from services.handlers.browser import handle_browser
from services.handlers.proxy import handle_proxy_request, handle_proxy_status, handle_proxy_config
from services.handlers.filesystem import handle_file_read, handle_file_modify, handle_shell, handle_fs_search
+from services.handlers.todo import handle_write_todos
# Consolidated Google Workspace handlers (6 services with operation dispatchers)
from services.handlers.gmail import handle_google_gmail, handle_gmail_receive
from services.handlers.calendar import handle_google_calendar
@@ -190,6 +191,8 @@ class NodeExecutor:
'vectorStore': handle_vector_store,
# Task management
'taskManager': handle_task_manager,
+ # Todo planning (dual-purpose: workflow node + AI tool)
+ 'writeTodos': handle_write_todos,
# Team monitoring
'teamMonitor': handle_team_monitor,
# Apify web scraping
diff --git a/server/services/todo_service.py b/server/services/todo_service.py
new file mode 100644
index 00000000..1d2a04bb
--- /dev/null
+++ b/server/services/todo_service.py
@@ -0,0 +1,96 @@
+"""Todo list service -- JSON-based per-session todo state management.
+
+Provides the write_todos tool capability for AI agents to create and manage
+structured task lists during complex multi-step operations.
+
+State is persisted as JSON strings, keyed by session identifier.
+Follows the singleton pattern used by browser_service.py and telegram_service.py.
+"""
+
+import json
+from typing import Dict, List, Optional
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+VALID_STATUSES = frozenset(("pending", "in_progress", "completed"))
+
+
+class TodoService:
+ """Manages per-session todo lists stored as JSON.
+
+ Each session maintains an independent todo list that persists across
+ tool calls within the same execution.
+ """
+
+ def __init__(self):
+ self._store: Dict[str, str] = {} # session_key -> JSON string
+
+ def write(self, session_key: str, todos: List[dict]) -> List[dict]:
+ """Replace the todo list for a session.
+
+ Validates each item, serializes to JSON, and stores.
+
+ Args:
+ session_key: Session identifier (workflow_id or node_id).
+ todos: List of todo dicts with 'content' and 'status' keys.
+
+ Returns:
+ The validated and stored todo list.
+ """
+ validated = []
+ for item in todos:
+ if not isinstance(item, dict):
+ continue
+ content = str(item.get("content", "")).strip()
+ if not content:
+ continue
+ status = item.get("status", "pending")
+ if status not in VALID_STATUSES:
+ status = "pending"
+ validated.append({"content": content, "status": status})
+
+ self._store[session_key] = json.dumps(validated)
+ logger.debug(
+ "[TodoService] Updated session=%s: %d items (%d pending, %d in_progress, %d completed)",
+ session_key,
+ len(validated),
+ sum(1 for t in validated if t["status"] == "pending"),
+ sum(1 for t in validated if t["status"] == "in_progress"),
+ sum(1 for t in validated if t["status"] == "completed"),
+ )
+ return validated
+
+ def get(self, session_key: str) -> List[dict]:
+ """Get current todo list for a session, deserialized from JSON."""
+ raw = self._store.get(session_key)
+ if not raw:
+ return []
+ try:
+ return json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+
+ def get_json(self, session_key: str) -> str:
+ """Get current todo list as a raw JSON string."""
+ return self._store.get(session_key, "[]")
+
+ def clear(self, session_key: str) -> None:
+ """Clear todos for a session."""
+ self._store.pop(session_key, None)
+
+ def format_for_llm(self, session_key: str) -> str:
+ """Format todos as JSON string for LLM consumption."""
+ return self.get_json(session_key)
+
+
+_service: Optional[TodoService] = None
+
+
+def get_todo_service() -> TodoService:
+ """Lazy singleton accessor."""
+ global _service
+ if _service is None:
+ _service = TodoService()
+ return _service