Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend/copilot): TodoWrite for baseline copilot (#12879)

Zamil Majdy4f11867d9279
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index ca7e4355f6..d317d677a5 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -75,6 +75,7 @@ from backend.copilot.tools.models import (
NoResultsResponse,
SetupRequirementsResponse,
SuggestedGoalResponse,
+ TodoWriteResponse,
UnderstandingUpdatedResponse,
)
from backend.copilot.tracking import track_user_message
@@ -1419,6 +1420,7 @@ ToolResponseUnion = (
| MemorySearchResponse
| MemoryForgetCandidatesResponse
| MemoryForgetConfirmResponse
+ | TodoWriteResponse
)
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index 9f9153ffaf..beb1af3f74 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -82,7 +82,7 @@ from backend.copilot.service import (
from backend.copilot.session_cleanup import prune_orphan_tool_calls
from backend.copilot.thinking_stripper import ThinkingStripper as _ThinkingStripper
from backend.copilot.token_tracking import persist_and_record_usage
-from backend.copilot.tools import execute_tool, get_available_tools
+from backend.copilot.tools import ToolGroup, execute_tool, get_available_tools
from backend.copilot.tracking import track_user_message
from backend.copilot.transcript import (
STOP_REASON_END_TURN,
@@ -1624,7 +1624,10 @@ async def stream_chat_completion_baseline(
openai_messages[i]["content"] = text
break
- tools = get_available_tools()
+ disabled_tool_groups: list[ToolGroup] = []
+ if not graphiti_enabled:
+ disabled_tool_groups.append("graphiti")
+ tools = get_available_tools(disabled_groups=disabled_tool_groups)
# --- Permission filtering ---
if permissions is not None:
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index 58cce98fbf..df837c0173 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -52,10 +52,15 @@ is at most as permissive as the parent:
from __future__ import annotations
import re
-from typing import Literal, get_args
+from typing import TYPE_CHECKING, Literal, get_args
from pydantic import BaseModel, PrivateAttr
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from backend.copilot.tools import ToolGroup
+
# ---------------------------------------------------------------------------
# Constants — single source of truth for all accepted tool names
# ---------------------------------------------------------------------------
@@ -124,9 +129,16 @@ ToolName = Literal[
# Frozen set of all valid tool names — derived from the Literal.
ALL_TOOL_NAMES: frozenset[str] = frozenset(get_args(ToolName))
-# SDK built-in tool names — uppercase-initial names are SDK built-ins.
+# SDK built-in tool names — tools provided by the Claude Code CLI that our
+# code does not implement directly. ``TodoWrite`` is DELIBERATELY excluded:
+# baseline mode ships an MCP-wrapped platform version
+# (``tools/todo_write.py``), while SDK mode still uses the CLI-native
+# original via ``_SDK_BUILTIN_ALWAYS`` in ``sdk/tool_adapter.py`` — the
+# MCP copy is filtered out there. ``Task`` remains an SDK-only built-in
+# (for queue-backed context-isolation on baseline, use ``run_sub_session``
+# instead).
SDK_BUILTIN_TOOL_NAMES: frozenset[str] = frozenset(
- n for n in ALL_TOOL_NAMES if n[0].isupper()
+ {"Agent", "Edit", "Glob", "Grep", "Read", "Task", "WebSearch", "Write"}
)
# Platform tool names — everything that isn't an SDK built-in.
@@ -363,13 +375,17 @@ def apply_tool_permissions(
permissions: CopilotPermissions,
*,
use_e2b: bool = False,
+ disabled_groups: Iterable[ToolGroup] = (),
) -> tuple[list[str], list[str]]:
"""Compute (allowed_tools, extra_disallowed) for :class:`ClaudeAgentOptions`.
Takes the base allowed/disallowed lists from
:func:`~backend.copilot.sdk.tool_adapter.get_copilot_tool_names` /
:func:`~backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools` and
- applies *permissions* on top.
+ applies *permissions* on top. Tools belonging to any *disabled_groups*
+ are hidden from the base allowed list — use this to gate capability
+ groups (e.g. ``"graphiti"`` when the memory backend is off for the
+ current user).
Returns:
``(allowed_tools, extra_disallowed)`` where *allowed_tools* is the
@@ -379,13 +395,16 @@ def apply_tool_permissions(
"""
from backend.copilot.sdk.tool_adapter import (
_READ_TOOL_NAME,
+ BASELINE_ONLY_MCP_TOOLS,
MCP_TOOL_PREFIX,
get_copilot_tool_names,
get_sdk_disallowed_tools,
)
from backend.copilot.tools import TOOL_REGISTRY
- base_allowed = get_copilot_tool_names(use_e2b=use_e2b)
+ base_allowed = get_copilot_tool_names(
+ use_e2b=use_e2b, disabled_groups=disabled_groups
+ )
base_disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)
if permissions.is_empty():
@@ -419,7 +438,14 @@ def apply_tool_permissions(
# keeping only those present in the original base_allowed list.
def to_sdk_names(short: str) -> list[str]:
names: list[str] = []
- if short in TOOL_REGISTRY:
+ if short in BASELINE_ONLY_MCP_TOOLS:
+ # Baseline ships MCP versions of these (Task/TodoWrite) for
+ # model-flexibility parity, but SDK mode uses the CLI-native
+ # originals. Permissions target the CLI built-in here so
+ # ``base_allowed`` (which excludes the MCP wrappers) still
+ # matches.
+ names.append(short)
+ elif short in TOOL_REGISTRY:
names.append(f"{MCP_TOOL_PREFIX}{short}")
elif short in _SDK_TO_MCP:
# Map SDK built-in file tool to its MCP equivalent.
diff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.py
index 5289ea8d22..367c1c7a2c 100644
--- a/autogpt_platform/backend/backend/copilot/permissions_test.py
+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py
@@ -582,6 +582,11 @@ class TestApplyToolPermissions:
class TestSdkBuiltinToolNames:
def test_expected_builtins_present(self):
+ # ``TodoWrite`` is DELIBERATELY absent: baseline ships an MCP-wrapped
+ # platform version for model-flexibility parity, so it appears in
+ # PLATFORM_TOOL_NAMES / TOOL_REGISTRY instead. ``Task`` remains
+ # SDK-only — baseline uses ``run_sub_session`` for the equivalent
+ # context-isolation role.
expected = {
"Agent",
"Read",
@@ -591,9 +596,9 @@ class TestSdkBuiltinToolNames:
"Grep",
"Task",
"WebSearch",
- "TodoWrite",
}
assert expected.issubset(SDK_BUILTIN_TOOL_NAMES)
+ assert "TodoWrite" not in SDK_BUILTIN_TOOL_NAMES
def test_platform_names_match_tool_registry(self):
"""PLATFORM_TOOL_NAMES (derived from ToolName Literal) must match TOOL_REGISTRY keys."""
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index 399d31c1cc..6bad8f895f 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -145,31 +145,12 @@ When the user asks to interact with a service or API, follow this order:
**Never skip step 1.** Built-in blocks are more reliable, tested, and user-friendly than MCP or raw API calls.
-### Sub-agent tasks
-- When using the Task tool, NEVER set `run_in_background` to true.
- All tasks must run in the foreground.
-
-### Delegating to another autopilot (sub-autopilot pattern)
-Use the **`run_sub_session`** tool to delegate a task to a fresh
-sub-AutoPilot. The sub has its own full tool set and can perform
-multi-step work autonomously.
-
-- `prompt` (required): the task description.
-- `system_context` (optional): extra context prepended to the prompt.
-- `sub_autopilot_session_id` (optional): continue an existing
- sub-AutoPilot — pass the `sub_autopilot_session_id` returned by a
- previous completed run.
-- `wait_for_result` (default 60, max 300): seconds to wait inline. If
- the sub isn't done by then you get `status="running"` + a
- `sub_session_id` — call **`get_sub_session_result`** with that id
- (wait up to 300s more per call) until it returns `completed` or
- `error`. Works across turns — safe to reconnect in a later message.
-
-Use this when a task is complex enough to benefit from a separate
-autopilot context, e.g. "research X and write a report" while the
-parent autopilot handles orchestration. Do NOT invoke `AutoPilotBlock`
-via `run_block` — it's hidden from `run_block` by design because the
-dedicated tool handles the async lifecycle correctly.
+### Complex multi-step work
+- Use `TodoWrite` to track the plan once the job has 3+ distinct steps.
+- Delegate self-contained subtasks to `run_sub_session` to keep their
+ intermediate tool calls out of the parent context.
+- Do NOT invoke `AutoPilotBlock` via `run_block`; use `run_sub_session`
+ instead.
"""
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index ca0d69e6ba..eb6babba2a 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -109,6 +109,7 @@ from ..service import (
)
from ..thinking_stripper import ThinkingStripper
from ..token_tracking import persist_and_record_usage
+from ..tools import ToolGroup
from ..tools.e2b_sandbox import get_or_create_sandbox, pause_sandbox_direct
from ..tools.sandbox import WORKSPACE_PREFIX, make_session_path
from ..tracking import track_user_message
@@ -3072,10 +3073,18 @@ async def stream_chat_completion_sdk(
on_compact=compaction.on_compact,
)
+ disabled_tool_groups: list[ToolGroup] = []
+ if not graphiti_enabled:
+ disabled_tool_groups.append("graphiti")
+
if permissions is not None:
- allowed, disallowed = apply_tool_permissions(permissions, use_e2b=use_e2b)
+ allowed, disallowed = apply_tool_permissions(
+ permissions, use_e2b=use_e2b, disabled_groups=disabled_tool_groups
+ )
else:
- allowed = get_copilot_tool_names(use_e2b=use_e2b)
+ allowed = get_copilot_tool_names(
+ use_e2b=use_e2b, disabled_groups=disabled_tool_groups
+ )
disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)
def _on_stderr(line: str) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
index 7e1fa0396d..ca1f1f821e 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py
@@ -10,6 +10,7 @@ import json
import logging
import os
import uuid
+from collections.abc import Iterable
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any
@@ -33,7 +34,7 @@ from backend.copilot.sdk.file_ref import (
expand_file_refs_in_args,
read_file_bytes,
)
-from backend.copilot.tools import TOOL_REGISTRY
+from backend.copilot.tools import TOOL_REGISTRY, ToolGroup, tool_names_in_groups
from backend.copilot.tools.base import BaseTool
from backend.util.truncate import truncate
@@ -853,9 +854,29 @@ DANGEROUS_PATTERNS = [
r"subprocess",
]
+# Platform-tool names whose MCP wrappers must NOT be exposed to SDK mode.
+# Baseline ships an MCP ``TodoWrite`` for model-flexibility parity; SDK mode
+# keeps using the CLI-native built-in listed in ``_SDK_BUILTIN_ALWAYS`` so
+# there is no double exposure. Public (no leading underscore) so a future
+# refactor renaming it is visible at both call sites —
+# ``permissions.apply_tool_permissions`` maps short tool names back to the
+# CLI built-in form for SDK mode.
+BASELINE_ONLY_MCP_TOOLS: frozenset[str] = frozenset({"TodoWrite"})
+
+
+def _registry_mcp_tools(*, hidden: frozenset[str] = frozenset()) -> list[str]:
+ return [
+ f"{MCP_TOOL_PREFIX}{name}"
+ for name in TOOL_REGISTRY.keys()
+ if name not in BASELINE_ONLY_MCP_TOOLS and name not in hidden
+ ]
+
+
# Static tool name list for the non-E2B case (backward compatibility).
+# Includes all capability-gated tools; per-user filtering happens in
+# ``get_copilot_tool_names`` when the caller passes ``disabled_groups``.
COPILOT_TOOL_NAMES = [
- *[f"{MCP_TOOL_PREFIX}{name}" for name in TOOL_REGISTRY.keys()],
+ *_registry_mcp_tools(),
f"{MCP_TOOL_PREFIX}{WRITE_TOOL_NAME}",
f"{MCP_TOOL_PREFIX}{READ_TOOL_NAME}",
f"{MCP_TOOL_PREFIX}{EDIT_TOOL_NAME}",
@@ -864,20 +885,31 @@ COPILOT_TOOL_NAMES = [
]
-def get_copilot_tool_names(*, use_e2b: bool = False) -> list[str]:
+def get_copilot_tool_names(
+ *,
+ use_e2b: bool = False,
+ disabled_groups: Iterable[ToolGroup] = (),
+) -> list[str]:
"""Build the ``allowed_tools`` list for :class:`ClaudeAgentOptions`.
When *use_e2b* is True the SDK built-in file tools are replaced by MCP
- equivalents that route to the E2B sandbox.
+ equivalents that route to the E2B sandbox. Tools belonging to any of
+ *disabled_groups* are filtered out — see ``ToolGroup`` / ``TOOL_GROUPS``
+ in ``backend.copilot.tools`` for the full list.
"""
+ hidden_short_names = tool_names_in_groups(disabled_groups)
+ hidden_mcp_names = {f"{MCP_TOOL_PREFIX}{n}" for n in hidden_short_names}
+
if not use_e2b:
- return list(COPILOT_TOOL_NAMES)
+ if not hidden_mcp_names:
+ return list(COPILOT_TOOL_NAMES)
+ return [n for n in COPILOT_TOOL_NAMES if n not in hidden_mcp_names]
# In E2B mode, Write/Edit are NOT registered (E2B uses write_file/edit_file
# from E2B_FILE_TOOLS instead), so don't include them here.
# _READ_TOOL_NAME is still needed for SDK tool-result reads.
return [
- *[f"{MCP_TOOL_PREFIX}{name}" for name in TOOL_REGISTRY.keys()],
+ *_registry_mcp_tools(hidden=hidden_short_names),
f"{MCP_TOOL_PREFIX}{_READ_TOOL_NAME}",
*[f"{MCP_TOOL_PREFIX}{name}" for name in E2B_FILE_TOOL_NAMES],
*_SDK_BUILTIN_ALWAYS,
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 7aace646a6..1b2635a54b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -1,7 +1,8 @@
from __future__ import annotations
import logging
-from typing import TYPE_CHECKING, Any
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Any, Literal
from openai.types.chat import ChatCompletionToolParam
@@ -43,6 +44,7 @@ from .run_block import RunBlockTool
from .run_mcp_tool import RunMCPToolTool
from .run_sub_session import RunSubSessionTool
from .search_docs import SearchDocsTool
+from .todo_write import TodoWriteTool
from .validate_agent import ValidateAgentGraphTool
from .web_fetch import WebFetchTool
from .web_search import WebSearchTool
@@ -86,6 +88,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"continue_run_block": ContinueRunBlockTool(),
"run_sub_session": RunSubSessionTool(),
"get_sub_session_result": GetSubSessionResultTool(),
+ "TodoWrite": TodoWriteTool(),
"run_mcp_tool": RunMCPToolTool(),
"get_mcp_guide": GetMCPGuideTool(),
"view_agent_output": AgentOutputTool(),
@@ -121,15 +124,45 @@ find_agent_tool = TOOL_REGISTRY["find_agent"]
run_agent_tool = TOOL_REGISTRY["run_agent"]
-def get_available_tools() -> list[ChatCompletionToolParam]:
+# Capability groups a tool may belong to. The service layer can hide all
+# tools in a group when the backing capability isn't available to this user
+# (e.g. Graphiti memory behind a feature flag), so the model doesn't reach
+# for tools whose backend is off and then hit opaque runtime errors. Add
+# a new group by extending ``ToolGroup`` and registering its members in
+# ``TOOL_GROUPS`` below.
+ToolGroup = Literal["graphiti"]
+
+TOOL_GROUPS: dict[str, ToolGroup] = {
+ "memory_store": "graphiti",
+ "memory_search": "graphiti",
+ "memory_forget_search": "graphiti",
+ "memory_forget_confirm": "graphiti",
+}
+
+
+def tool_names_in_groups(groups: Iterable[ToolGroup]) -> frozenset[str]:
+ """Return the set of tool short-names belonging to any of *groups*."""
+ group_set = frozenset(groups)
+ return frozenset(name for name, g in TOOL_GROUPS.items() if g in group_set)
+
+
+def get_available_tools(
+ *,
+ disabled_groups: Iterable[ToolGroup] = (),
+) -> list[ChatCompletionToolParam]:
"""Return OpenAI tool schemas for tools available in the current environment.
Called per-request so that env-var or binary availability is evaluated
fresh each time (e.g. browser_* tools are excluded when agent-browser
- CLI is not installed).
+ CLI is not installed). Tools belonging to any *disabled_groups* are
+ also filtered out — use this to hide capability-gated tools (e.g.
+ ``graphiti`` when the memory backend is off for the current user).
"""
+ hidden = tool_names_in_groups(disabled_groups)
return [
- tool.as_openai_tool() for tool in TOOL_REGISTRY.values() if tool.is_available
+ tool.as_openai_tool()
+ for name, tool in TOOL_REGISTRY.items()
+ if tool.is_available and name not in hidden
]
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 39a84cfa49..e45ff19e34 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -88,6 +88,9 @@ class ResponseType(str, Enum):
MEMORY_FORGET_CANDIDATES = "memory_forget_candidates"
MEMORY_FORGET_CONFIRM = "memory_forget_confirm"
+ # Planning
+ TODO_WRITE = "todo_write"
+
# Base response model
class ToolResponseBase(BaseModel):
@@ -841,3 +844,36 @@ class MemoryForgetConfirmResponse(ToolResponseBase):
type: ResponseType = ResponseType.MEMORY_FORGET_CONFIRM
deleted_uuids: list[str] = Field(default_factory=list)
failed_uuids: list[str] = Field(default_factory=list)
+
+
+# --- Planning ---
+
+
+class TodoItem(BaseModel):
+ """One entry in a ``TodoWrite`` checklist.
+
+ Mirrors the schema used by Claude Code's built-in ``TodoWrite`` tool so
+ the frontend's ``GenericTool`` accordion renders baseline-emitted todos
+ identically to SDK-emitted ones.
+ """
+
+ content: str = Field(description="Imperative description of the task.")
+ activeForm: str = Field(
+ description="Present-continuous form shown while the task is running.",
+ )
+ status: Literal["pending", "in_progress", "completed"] = Field(
+ default="pending",
+ )
+
+
+class TodoWriteResponse(ToolResponseBase):
+ """Ack returned by ``TodoWrite``.
+
+ The tool is effectively stateless — the authoritative task list lives in
+ the assistant's latest tool-call arguments, which are replayed from the
+ transcript on each turn. The tool output only needs to confirm that the
+ update was accepted so the model can proceed.
+ """
+
+ type: ResponseType = ResponseType.TODO_WRITE
+ todos: list[TodoItem] = Field(default_factory=list)
diff --git a/autogpt_platform/backend/backend/copilot/tools/todo_write.py b/autogpt_platform/backend/backend/copilot/tools/todo_write.py
new file mode 100644
index 0000000000..6047281e10
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/todo_write.py
@@ -0,0 +1,120 @@
+"""Task-list tool for baseline copilot mode.
+
+Mirrors the schema and UX of Claude Code's built-in ``TodoWrite`` tool so
+the frontend's generic tool renderer draws baseline-emitted checklists the
+same way it draws SDK-emitted ones. The tool is stateless: the model's
+latest ``todos`` argument IS the canonical list, replayed from transcript
+on subsequent turns.
+
+Baseline needs this as a platform tool because OpenAI-compatible providers
+(Kimi, GPT, Grok, Gemini) do not ship a built-in equivalent. The SDK path
+continues to use the CLI's native ``TodoWrite`` — the MCP-wrapped version
+of this tool is filtered out of SDK's allowed_tools list (see
+``sdk/tool_adapter.py``) to avoid name shadowing.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from backend.copilot.model import ChatSession
+
+from .base import BaseTool
+from .models import ErrorResponse, TodoItem, TodoWriteResponse, ToolResponseBase
+
+logger = logging.getLogger(__name__)
+
+
+class TodoWriteTool(BaseTool):
+ """Maintain a step-by-step task checklist visible to the user."""
+
+ @property
+ def name(self) -> str:
+ # Capitalised to match the frontend's switch on ``"TodoWrite"``
+ # (see ``copilot/tools/GenericTool/helpers.ts``).
+ return "TodoWrite"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Plan and track multi-step work as a visible checklist. Send "
+ "the full list every call; exactly one item in_progress at a time."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "todos": {
+ "type": "array",
+ "description": "Full updated task list (not a delta).",
+ "items": {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "Imperative (e.g. 'Run tests').",
+ },
+ "activeForm": {
+ "type": "string",
+ "description": (
+ "Present-continuous (e.g. 'Running tests')."
+ ),
+ },
+ "status": {
+ "type": "string",
+ "enum": ["pending", "in_progress", "completed"],
+ "default": "pending",
+ },
+ },
+ "required": ["content", "activeForm"],
+ },
+ },
+ },
+ "required": ["todos"],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs: Any,
+ ) -> ToolResponseBase:
+ del user_id
+ raw_todos = kwargs.get("todos")
+ if raw_todos is None:
+ return ErrorResponse(
+ message="`todos` is required.",
+ session_id=session.session_id,
+ )
+ if not isinstance(raw_todos, list):
+ return ErrorResponse(
+ message="`todos` must be an array.",
+ session_id=session.session_id,
+ )
+
+ try:
+ parsed = [TodoItem.model_validate(item) for item in raw_todos]
+ except Exception as exc:
+ return ErrorResponse(
+ message=f"Invalid todo entry: {exc}",
+ session_id=session.session_id,
+ )
+
+ in_progress = sum(1 for t in parsed if t.status == "in_progress")
+ if in_progress > 1:
+ return ErrorResponse(
+ message=(
+ "Only one todo may be 'in_progress' at a time "
+ f"(found {in_progress})."
+ ),
+ session_id=session.session_id,
+ )
+
+ return TodoWriteResponse(
+ message="Task list updated.",
+ session_id=session.session_id,
+ todos=parsed,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/todo_write_test.py b/autogpt_platform/backend/backend/copilot/tools/todo_write_test.py
new file mode 100644
index 0000000000..60c14f81d0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/todo_write_test.py
@@ -0,0 +1,125 @@
+"""Tests for TodoWriteTool."""
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse, TodoItem, TodoWriteResponse
+from backend.copilot.tools.todo_write import TodoWriteTool
+
+
+def tool() -> TodoWriteTool:
+ return TodoWriteTool()
+
+
+def session() -> ChatSession:
+ return ChatSession.new(user_id="test-user", dry_run=False)
+
+
+async def test_valid_todo_list(tool: TodoWriteTool, session: ChatSession):
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ todos=[
+ {
+ "content": "Write tests",
+ "activeForm": "Writing tests",
+ "status": "pending",
+ },
+ {
+ "content": "Ship PR",
+ "activeForm": "Shipping PR",
+ "status": "in_progress",
+ },
+ ],
+ )
+
+ assert isinstance(result, TodoWriteResponse)
+ assert result.session_id == session.session_id
+ assert len(result.todos) == 2
+ assert result.todos[0] == TodoItem(
+ content="Write tests",
+ activeForm="Writing tests",
+ status="pending",
+ )
+ assert result.todos[1].status == "in_progress"
+
+
+async def test_default_status_is_pending(tool: TodoWriteTool, session: ChatSession):
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ todos=[{"content": "Write tests", "activeForm": "Writing tests"}],
+ )
+
+ assert isinstance(result, TodoWriteResponse)
+ assert result.todos[0].status == "pending"
+
+
+async def test_missing_todos_returns_error(tool: TodoWriteTool, session: ChatSession):
+ result = await tool._execute(user_id=None, session=session)
+
+ assert isinstance(result, ErrorResponse)
+ assert "todos" in result.message.lower()
+
+
+async def test_non_list_todos_returns_error(tool: TodoWriteTool, session: ChatSession):
+ result = await tool._execute(user_id=None, session=session, todos="not a list")
+
+ assert isinstance(result, ErrorResponse)
+
+
+async def test_invalid_item_returns_error(tool: TodoWriteTool, session: ChatSession):
+ # Missing required `activeForm` field.
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ todos=[{"content": "Missing active form"}],
+ )
+
+ assert isinstance(result, ErrorResponse)
+
+
+async def test_multiple_in_progress_rejected(tool: TodoWriteTool, session: ChatSession):
+ """Exactly one item should be in_progress at a time — SDK parity rule."""
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ todos=[
+ {
+ "content": "A",
+ "activeForm": "Doing A",
+ "status": "in_progress",
+ },
+ {
+ "content": "B",
+ "activeForm": "Doing B",
+ "status": "in_progress",
+ },
+ ],
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert "in_progress" in result.message
+
+
+def test_openai_schema_shape(tool: TodoWriteTool):
+ schema = tool.as_openai_tool()
+ assert schema["type"] == "function"
+ assert schema["function"]["name"] == "TodoWrite"
+ params = schema["function"]["parameters"]
+ assert params["required"] == ["todos"]
+ items = params["properties"]["todos"]["items"]
+ assert items["required"] == ["content", "activeForm"]
+ assert items["properties"]["status"]["enum"] == [
+ "pending",
+ "in_progress",
+ "completed",
+ ]
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index f64a7550cd..ae1b9a715b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -32,7 +32,11 @@ from backend.copilot.tools import TOOL_REGISTRY
# synthesised-answer wording in the top-level description so the LLM
# reads the answer before reaching for `web_fetch`. Both are
# LLM-decision-critical copy, not bloat.
-_CHAR_BUDGET = 33_200
+# Bumped 33200 -> 34000 when baseline gained the MCP `TodoWrite` tool
+# for parity with the Claude Code SDK's built-in (PR #12879). The new
+# schema adds ~600 chars; description already trimmed to the minimum
+# viable copy.
+_CHAR_BUDGET = 34_000
@pytest.fixture(scope="module")
@@ -122,9 +126,10 @@ def test_total_schema_char_budget() -> None:
This locks in the 34% token reduction from #12398 and prevents future
description bloat from eroding the gains. Uses character count with a
- ~4 chars/token heuristic (budget of 32000 chars ≈ 8000 tokens).
- Character count is tokenizer-agnostic — no dependency on GPT or Claude
- tokenizers — while still providing a stable regression gate.
+ ~4 chars/token heuristic; see ``_CHAR_BUDGET`` above for the current
+ value and its change history. Character count is tokenizer-agnostic
+ — no dependency on GPT or Claude tokenizers — while still providing a
+ stable regression gate.
"""
schemas = [tool.as_openai_tool() for tool in TOOL_REGISTRY.values()]
serialized = json.dumps(schemas)
@@ -134,3 +139,60 @@ def test_total_schema_char_budget() -> None:
f"exceeding budget of {_CHAR_BUDGET} chars (~{_CHAR_BUDGET // 4} tokens). "
f"Description bloat detected — trim descriptions or raise the budget intentionally."
)
+
+
+# ── Capability-group filtering (ToolGroup / disabled_groups) ───────────
+
+
+def test_get_available_tools_hides_graphiti_when_disabled() -> None:
+ """When the ``graphiti`` group is disabled, the memory_* tools must
+ not appear in the OpenAI schema list — they'd just confuse the model
+ and produce opaque runtime errors."""
+ from backend.copilot.tools import get_available_tools
+
+ memory_tool_names = {
+ "memory_store",
+ "memory_search",
+ "memory_forget_search",
+ "memory_forget_confirm",
+ }
+
+ default = {t["function"]["name"] for t in get_available_tools()}
+ assert memory_tool_names.issubset(
+ default
+ ), "sanity: memory_* tools should be present when no groups disabled"
+
+ filtered = {
+ t["function"]["name"] for t in get_available_tools(disabled_groups=["graphiti"])
+ }
+ assert not (
+ memory_tool_names & filtered
+ ), f"graphiti disabled but memory_* still present: {memory_tool_names & filtered}"
+ # Non-graphiti tools stay visible.
+ assert "find_block" in filtered
+ assert "TodoWrite" in filtered
+
+
+def test_get_copilot_tool_names_hides_graphiti_when_disabled() -> None:
+ """Same invariant for the SDK tool-name list."""
+ from backend.copilot.sdk.tool_adapter import MCP_TOOL_PREFIX, get_copilot_tool_names
+
+ memory_mcp_names = {
+ f"{MCP_TOOL_PREFIX}memory_store",
+ f"{MCP_TOOL_PREFIX}memory_search",
+ f"{MCP_TOOL_PREFIX}memory_forget_search",
+ f"{MCP_TOOL_PREFIX}memory_forget_confirm",
+ }
+
+ default = set(get_copilot_tool_names())
+ assert memory_mcp_names.issubset(default)
+
+ filtered = set(get_copilot_tool_names(disabled_groups=["graphiti"]))
+ assert not (
+ memory_mcp_names & filtered
+ ), f"graphiti disabled but memory MCP names still present: {memory_mcp_names & filtered}"
+ # E2B path stays consistent.
+ filtered_e2b = set(
+ get_copilot_tool_names(use_e2b=True, disabled_groups=["graphiti"])
+ )
+ assert not (memory_mcp_names & filtered_e2b)
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 83fa19af10..780285b0a1 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2116,7 +2116,8 @@
},
{
"$ref": "#/components/schemas/MemoryForgetConfirmResponse"
- }
+ },
+ { "$ref": "#/components/schemas/TodoWriteResponse" }
],
"title": "Response Getv2[Dummy] Tool Response Type Export For Codegen"
}
@@ -14570,7 +14571,8 @@
"memory_store",
"memory_search",
"memory_forget_candidates",
- "memory_forget_confirm"
+ "memory_forget_confirm",
+ "todo_write"
],
"title": "ResponseType",
"description": "Types of tool responses."
@@ -16682,6 +16684,52 @@
"required": ["timezone"],
"title": "TimezoneResponse"
},
+ "TodoItem": {
+ "properties": {
+ "content": {
+ "type": "string",
+ "title": "Content",
+ "description": "Imperative description of the task."
+ },
+ "activeForm": {
+ "type": "string",
+ "title": "Activeform",
+ "description": "Present-continuous form shown while the task is running."
+ },
+ "status": {
+ "type": "string",
+ "enum": ["pending", "in_progress", "completed"],
+ "title": "Status",
+ "default": "pending"
+ }
+ },
+ "type": "object",
+ "required": ["content", "activeForm"],
+ "title": "TodoItem",
+ "description": "One entry in a ``TodoWrite`` checklist.\n\nMirrors the schema used by Claude Code's built-in ``TodoWrite`` tool so\nthe frontend's ``GenericTool`` accordion renders baseline-emitted todos\nidentically to SDK-emitted ones."
+ },
+ "TodoWriteResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "todo_write"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "todos": {
+ "items": { "$ref": "#/components/schemas/TodoItem" },
+ "type": "array",
+ "title": "Todos"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "TodoWriteResponse",
+ "description": "Ack returned by ``TodoWrite``.\n\nThe tool is effectively stateless — the authoritative task list lives in\nthe assistant's latest tool-call arguments, which are replayed from the\ntranscript on each turn. The tool output only needs to confirm that the\nupdate was accepted so the model can proceed."
+ },
"TokenIntrospectionResult": {
"properties": {
"active": { "type": "boolean", "title": "Active" },