Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(task): add task related tools in agentscope 2.0 (#1549)
DavdGao8b05c3f93298
diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.pyindex 31cda97ce..69dbdbf0e 100644--- a/src/agentscope/__init__.py+++ b/src/agentscope/__init__.py@@ -2,14 +2,6 @@"""The agentscope serialization module"""import warnings-from . import exception-from . import message-from . import model-from . import tool-from . import formatter-from . import agent-from . import embedding-from . import tracingfrom ._logging import (logger,setup_logger,@@ -21,17 +13,7 @@ warnings.filterwarnings("once", category=DeprecationWarning)__all__ = [- # modules- "exception",- "message",- "model",- "tool",- "formatter",- "agent","logger",- "embedding",- "tracing",- # functions"setup_logger","__version__",]diff --git a/src/agentscope/agent/__init__.py b/src/agentscope/agent/__init__.pyindex ac4165b0f..b7e02c1ec 100644--- a/src/agentscope/agent/__init__.py+++ b/src/agentscope/agent/__init__.py@@ -1,7 +1,6 @@# -*- coding: utf-8 -*-"""Initialize the agent module."""-from ._state import AgentStatefrom ._agent import Agentfrom ._config import CompressionConfig-__all__ = ["Agent", "AgentState", "CompressionConfig"]+__all__ = ["Agent", "CompressionConfig"]diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex 32e46aaae..99dbd6499 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -16,7 +16,7 @@ from pydantic import ()from ._config import CompressionConfig-from ._state import AgentState+from ..state import AgentStatefrom ._utils import _ToolCallBatchfrom .._logging import loggerfrom .._utils._common import _json_loads_with_repair@@ -73,8 +73,10 @@ from ..tool import (Toolkit,ToolChunk,ToolChoice,- PermissionBehavior,ToolResponse,+)+from ..permission import (+ PermissionBehavior,PermissionEngine,PermissionDecision,)diff --git a/src/agentscope/event/__init__.py b/src/agentscope/event/__init__.pyindex d05d143aa..b0f0f6dca 100644--- a/src/agentscope/event/__init__.py+++ b/src/agentscope/event/__init__.py@@ -30,6 +30,7 @@ from ._event import (UserConfirmResultEvent,ExternalExecutionResultEvent,AgentEvent,+ ConfirmResult,)@@ -62,4 +63,5 @@ __all__ = ["UserConfirmResultEvent","ExternalExecutionResultEvent","AgentEvent",+ "ConfirmResult",]diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.pyindex c53850611..41ef96075 100644--- a/src/agentscope/event/_event.py+++ b/src/agentscope/event/_event.py@@ -8,7 +8,7 @@ from typing import Literal, List, TypeAliasfrom pydantic import BaseModel, Field, ConfigDictfrom ..message import ToolCallBlock, ToolResultBlock, ToolResultState-from ..tool import PermissionRule+from ..permission import PermissionRuleclass EventType(StrEnum):diff --git a/src/agentscope/tool/_permission/__init__.py b/src/agentscope/permission/__init__.pysimilarity index 100%rename from src/agentscope/tool/_permission/__init__.pyrename to src/agentscope/permission/__init__.pydiff --git a/src/agentscope/tool/_permission/_context.py b/src/agentscope/permission/_context.pysimilarity index 100%rename from src/agentscope/tool/_permission/_context.pyrename to src/agentscope/permission/_context.pydiff --git a/src/agentscope/tool/_permission/_decision.py b/src/agentscope/permission/_decision.pysimilarity index 100%rename from src/agentscope/tool/_permission/_decision.pyrename to src/agentscope/permission/_decision.pydiff --git a/src/agentscope/tool/_permission/_engine.py b/src/agentscope/permission/_engine.pysimilarity index 99%rename from src/agentscope/tool/_permission/_engine.pyrename to src/agentscope/permission/_engine.pyindex 56f22ecff..600e893c4 100644--- a/src/agentscope/tool/_permission/_engine.py+++ b/src/agentscope/permission/_engine.py@@ -8,7 +8,7 @@ from ._decision import PermissionDecision, PermissionBehaviorfrom ._types import PermissionModeif TYPE_CHECKING:- from .._base import ToolBase+ from ..tool import ToolBaseelse:ToolBase = "ToolBase"diff --git a/src/agentscope/tool/_permission/_rule.py b/src/agentscope/permission/_rule.pysimilarity index 100%rename from src/agentscope/tool/_permission/_rule.pyrename to src/agentscope/permission/_rule.pydiff --git a/src/agentscope/tool/_permission/_types.py b/src/agentscope/permission/_types.pysimilarity index 100%rename from src/agentscope/tool/_permission/_types.pyrename to src/agentscope/permission/_types.pydiff --git a/src/agentscope/tool/_skill/__init__.py b/src/agentscope/skill/__init__.pysimilarity index 76%rename from src/agentscope/tool/_skill/__init__.pyrename to src/agentscope/skill/__init__.pyindex 4e84844f0..98bd09a30 100644--- a/src/agentscope/tool/_skill/__init__.py+++ b/src/agentscope/skill/__init__.py@@ -1,10 +1,11 @@# -*- coding: utf-8 -*-"""The skill related classes and functions."""-from ._base import SkillLoaderBase+from ._base import SkillLoaderBase, Skillfrom ._local_loader import LocalSkillLoader__all__ = [+ "Skill","SkillLoaderBase","LocalSkillLoader",]diff --git a/src/agentscope/skill/_base.py b/src/agentscope/skill/_base.pynew file mode 100644index 000000000..9069073a8--- /dev/null+++ b/src/agentscope/skill/_base.py@@ -0,0 +1,29 @@+# -*- coding: utf-8 -*-+"""The skill loader base class."""+from abc import abstractmethod, ABC+from dataclasses import dataclass+++@dataclass+class Skill:+ """The agent skill class"""++ name: str+ """The name of the skill."""+ description: str+ """The description of the skill."""+ dir: str+ """The directory of the agent skill."""+ markdown: str+ """The markdown content of the agent skill."""+ updated_at: float+ """The last updated time of the skill."""+++class SkillLoaderBase(ABC):+ """The base class for skill loader."""++ @abstractmethod+ async def list_skills(self) -> list[Skill]:+ """List all the skills that can be loaded by this loader."""+ raise NotImplementedErrordiff --git a/src/agentscope/tool/_skill/_local_loader.py b/src/agentscope/skill/_local_loader.pysimilarity index 98%rename from src/agentscope/tool/_skill/_local_loader.pyrename to src/agentscope/skill/_local_loader.pyindex 7f109d790..04f3205e3 100644--- a/src/agentscope/tool/_skill/_local_loader.py+++ b/src/agentscope/skill/_local_loader.py@@ -8,8 +8,8 @@ import aiofiles.ospathimport frontmatterfrom ._base import SkillLoaderBase-from ..._logging import logger-from .._types import Skill+from .._logging import logger+from ..skill import Skillclass LocalSkillLoader(SkillLoaderBase):diff --git a/src/agentscope/state/__init__.py b/src/agentscope/state/__init__.pynew file mode 100644index 000000000..a640f6ff4--- /dev/null+++ b/src/agentscope/state/__init__.py@@ -0,0 +1,10 @@+# -*- coding: utf-8 -*-+"""The agent state module in agentscope."""++from ._state import AgentState+from ._task import Task++__all__ = [+ "Task",+ "AgentState",+]diff --git a/src/agentscope/agent/_state.py b/src/agentscope/state/_state.pysimilarity index 90%rename from src/agentscope/agent/_state.pyrename to src/agentscope/state/_state.pyindex 592c38cca..b20c85cbb 100644--- a/src/agentscope/agent/_state.py+++ b/src/agentscope/state/_state.py@@ -6,8 +6,9 @@ from pydantic import BaseModel, Fieldimport aiofiles.os+from ._task import Taskfrom ..message import TextBlock, DataBlock, Msg-from ..tool import PermissionContext+from ..permission import PermissionContextclass ReadCacheEntry(BaseModel):@@ -110,6 +111,13 @@ class ToolContext(BaseModel):)+class TaskContext(BaseModel):+ """The task context."""++ tasks: list[Task] = Field(default_factory=lambda: [])+ """The task context."""++class AgentState(BaseModel):"""The agent state that should be saved and loaded from storage."""@@ -141,3 +149,9 @@ class AgentState(BaseModel):# The tool context# =================================================================tool_context: ToolContext = Field(default_factory=ToolContext)++ # =================================================================+ # The tasks context+ # =================================================================+ tasks_context: TaskContext = Field(default_factory=TaskContext)+ """The task context that records the agent tasks."""diff --git a/src/agentscope/state/_task.py b/src/agentscope/state/_task.pynew file mode 100644index 000000000..d07eb03c9--- /dev/null+++ b/src/agentscope/state/_task.py@@ -0,0 +1,38 @@+# -*- coding: utf-8 -*-+"""The task class."""+import uuid+from datetime import datetime+from typing import Any, Literal++from pydantic import BaseModel, Field+++class Task(BaseModel):+ """The agent task."""++ subject: str+ """The subject of the task."""++ description: str+ """The task description."""++ metadata: dict[str, Any]+ """The additional metadata of the task."""++ created_at: str = Field(default_factory=lambda: datetime.now().isoformat())+ """The created timestamp."""++ state: Literal["pending", "in_progress", "completed"] = "pending"+ """The task state."""++ id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The task identifier."""++ owner: str | None = None+ """The owner of the task."""++ blocks: list[str] = Field(default_factory=lambda: [])+ """The task ids blocked by this task."""++ blocked_by: list[str] = Field(default_factory=lambda: [])+ """The task ids blocking this task."""diff --git a/src/agentscope/storage/_base.py b/src/agentscope/storage/_base.pyindex 91210fe27..20f7c3b81 100644--- a/src/agentscope/storage/_base.py+++ b/src/agentscope/storage/_base.py@@ -3,7 +3,7 @@from abc import ABC, abstractmethodfrom typing import Any-from ..agent import AgentState+from ..state import AgentStateclass StorageBase(ABC):diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex f567a559c..9c7355eb3 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -1,24 +1,11 @@# -*- coding: utf-8 -*-"""The tool module in agentscope."""-from ._types import ToolChoice, Function, Skill+from ._types import ToolChoice, Function, RegisteredToolfrom ._response import ToolResponse, ToolChunkfrom ._toolkit import Toolkitfrom ._base import ToolBasefrom ._adapters import MCPTool-from ._permission import (- PermissionContext,- AdditionalWorkingDirectory,- PermissionDecision,- PermissionEngine,- PermissionRule,- PermissionMode,- PermissionBehavior,-)-from ._skill import (- SkillLoaderBase,- LocalSkillLoader,-)from ._builtin import (ResetTools,Bash,@@ -28,6 +15,12 @@ from ._builtin import (Read,Write,)+from ._task import (+ TaskUpdate,+ TaskGet,+ TaskList,+ TaskCreate,+)__all__ = [# Basic tool related types and functions@@ -38,14 +31,7 @@ __all__ = ["Toolkit","ToolChunk","ToolResponse",- # Permission related types and functions- "PermissionContext",- "AdditionalWorkingDirectory",- "PermissionDecision",- "PermissionEngine",- "PermissionRule",- "PermissionMode",- "PermissionBehavior",+ "RegisteredTool",# Builtin tools"ResetTools","Bash",@@ -54,8 +40,8 @@ __all__ = ["Grep","Read","Write",- # Skill related types and functions- "Skill",- "SkillLoaderBase",- "LocalSkillLoader",+ "TaskUpdate",+ "TaskGet",+ "TaskList",+ "TaskCreate",]diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex 7f26b87b8..e447047b2 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -10,7 +10,7 @@ import mcpfrom ._types import Functionfrom ._base import ToolBase-from ._permission import (+from ..permission import (PermissionBehavior,PermissionDecision,)@@ -29,6 +29,15 @@ class _FunctionTool(ToolBase):AsyncGenerator[ToolChunk, None]."""+ is_external_tool: bool = False+ """If this tool is an external tool, which doesn't need to implement the+ __call__ method and the agent will yield the external tool call event."""+ is_mcp: bool = False+ """If this tool is an MCP tool, which will be used in the permission"""+ mcp_name: str | None = None+ """The name of the MCP server this tool belongs to, which is required if+ this tool is an MCP tool."""+def __init__(self,func: Function,@@ -36,7 +45,8 @@ class _FunctionTool(ToolBase):description: str | None = None,is_concurrency_safe: bool = True,is_read_only: bool = False,- ):+ is_state_injected: bool = False,+ ) -> None:"""Initialize the FunctionTool.Args:@@ -50,6 +60,8 @@ class _FunctionTool(ToolBase):Whether this tool is safe to call concurrently.is_read_only (`bool`, optional):Whether this tool only reads data without side effects.+ is_state_injected (`bool`, optional):+ Whether this tool requires agent state injection."""self.name = name or func.__name__self.description = description or _extract_func_description(@@ -58,6 +70,7 @@ class _FunctionTool(ToolBase):self.input_schema = _extract_input_schema(func)self.is_concurrency_safe = is_concurrency_safeself.is_read_only = is_read_only+ self.is_state_injected = is_state_injectedself.is_external_tool = Falseself.is_mcp = Falseself._func = func@@ -109,6 +122,8 @@ class MCPTool(ToolBase):is_mcp: bool = True"""Whether this tool is an MCP tool."""+ is_state_injected: bool = False+ """The mcp tools is prohibited state injection for safety reason."""def __init__(self,diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.pyindex acde293ef..c335b1f5e 100644--- a/src/agentscope/tool/_base.py+++ b/src/agentscope/tool/_base.py@@ -6,14 +6,30 @@ from abc import abstractmethod, ABCfrom pathlib import Pathfrom typing import AsyncGenerator, Any, List+from pydantic import BaseModel+from ._constants import DEFAULT_DANGEROUS_FILES, DEFAULT_DANGEROUS_DIRECTORIES-from ._permission import (+from ..permission import (PermissionContext,PermissionDecision,PermissionRule,PermissionBehavior,)from ._response import ToolChunk+from ._utils import _remove_title_field+++class _ParamsBase(BaseModel):+ """A base class for tool parameters that remove the title field from the+ exported JSON schema.+ """++ @classmethod+ def model_json_schema(cls, *args: Any, **kwargs: Any) -> dict:+ """An override implementation to remove the title field from the+ exported schema.+ """+ return _remove_title_field(super().model_json_schema(*args, **kwargs))class ToolBase(ABC):@@ -30,10 +46,15 @@ class ToolBase(ABC):is_read_only: bool"""If this tool is read-only, which will be used in the permissionchecking."""- is_external_tool: bool+ is_external_tool: bool = False"""If this tool is an external tool, which doesn't need to implement the__call__ method and the agent will yield the external tool call event."""- is_mcp: bool+ is_state_injected: bool = False+ """If this tool requires agent state to be injected when called. If `True`,+ the state will be injected by an argument named `_agent_state`. Note your+ tool should be able to accept such argument.+ """+ is_mcp: bool = False"""If this tool is an MCP tool, which will be used in the permission"""mcp_name: str | None = None"""The name of the MCP server this tool belongs to, which is required ifdiff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.pyindex b975ead29..646abab6f 100644--- a/src/agentscope/tool/_builtin/_bash.py+++ b/src/agentscope/tool/_builtin/_bash.py@@ -7,7 +7,7 @@ import asynciofrom ._bash_parser import BashCommandParserfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -128,6 +128,7 @@ easier to review tool calls and give permission.is_read_only: bool = Falseis_concurrency_safe: bool = Falseis_external_tool: bool = False+ is_state_injected: bool = Falsedef __init__(self,diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.pyindex 5bef1ddb9..1b3871635 100644--- a/src/agentscope/tool/_builtin/_edit.py+++ b/src/agentscope/tool/_builtin/_edit.py@@ -2,12 +2,12 @@"""The edit tool in agentscope."""import fnmatchimport os-from typing import Any, List, TYPE_CHECKING+from typing import Any, Listimport aiofilesfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -15,12 +15,8 @@ from .._permission import (PermissionRule,)from .._response import ToolChunk-from ...message import TextBlock--if TYPE_CHECKING:- from ...agent import AgentState-else:- AgentState = Any+from ...message import TextBlock, ToolResultState+from ...state import AgentStateclass Edit(ToolBase):@@ -83,6 +79,7 @@ Usage:is_read_only: bool = Falseis_concurrency_safe: bool = Falseis_external_tool: bool = False+ is_state_injected: bool = Truedef __init__(self,@@ -297,7 +294,7 @@ Usage:),),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -307,7 +304,7 @@ Usage:content=[TextBlock(text=f"Error: File not found: {file_path}"),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -322,7 +319,7 @@ Usage:),),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -338,7 +335,7 @@ Usage:"it using the Read tool.",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)content = "".join(cache.lines)@@ -354,7 +351,7 @@ Usage:except Exception as e:return ToolChunk(content=[TextBlock(text=f"Error reading file: {str(e)}")],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -369,7 +366,7 @@ Usage:text=f"Error: old_string not found in {file_path}",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -386,7 +383,7 @@ Usage:),),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -411,7 +408,7 @@ Usage:except Exception as e:return ToolChunk(content=[TextBlock(text=f"Error writing file: {str(e)}")],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -426,6 +423,6 @@ Usage:f"in {file_path}",),],- state="running",+ state=ToolResultState.RUNNING,is_last=True,)diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.pyindex 9dd98d97c..cf7531d30 100644--- a/src/agentscope/tool/_builtin/_glob.py+++ b/src/agentscope/tool/_builtin/_glob.py@@ -6,7 +6,7 @@ import refrom typing import Any, Listfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -53,6 +53,7 @@ codebase.""" # ignore: E501is_read_only: bool = Trueis_concurrency_safe: bool = Trueis_external_tool: bool = False+ is_state_injected: bool = Falsedef __init__(self) -> None:"""Initialize the glob tool."""diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.pyindex 1566b2696..83a589bfe 100644--- a/src/agentscope/tool/_builtin/_grep.py+++ b/src/agentscope/tool/_builtin/_grep.py@@ -7,7 +7,7 @@ import shutilfrom typing import Any, List, Literalfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -155,6 +155,7 @@ class Grep(ToolBase):is_read_only: bool = Trueis_concurrency_safe: bool = Trueis_external_tool: bool = False+ is_state_injected: bool = Falsedef __init__(self) -> None:"""Initialize the grep tool."""diff --git a/src/agentscope/tool/_builtin/_meta.py b/src/agentscope/tool/_builtin/_meta.pyindex 893762ac2..29a3855fc 100644--- a/src/agentscope/tool/_builtin/_meta.py+++ b/src/agentscope/tool/_builtin/_meta.py@@ -1,11 +1,11 @@# -*- coding: utf-8 -*-"""The meta tool class."""-from typing import Any, TYPE_CHECKING+from typing import Anyfrom pydantic import Field, create_modelfrom jinja2 import Template-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -15,12 +15,7 @@ from .._base import ToolBasefrom .._types import ToolGroupfrom ...exception import DeveloperOrientedExceptionfrom ...message import TextBlock---if TYPE_CHECKING:- from ...agent import AgentState-else:- AgentState = Any+from ...state import AgentStateclass ResetTools(ToolBase):@@ -48,6 +43,7 @@ class ResetTools(ToolBase):is_read_only: bool = Falseis_concurrency_safe: bool = Trueis_external_tool: bool = False+ is_state_injected: bool = Truedef __init__(self,diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.pyindex 75aa549a5..d85daac25 100644--- a/src/agentscope/tool/_builtin/_read.py+++ b/src/agentscope/tool/_builtin/_read.py@@ -2,24 +2,20 @@"""The read tool in agentscope."""import fnmatchimport os-from typing import Any, List, TYPE_CHECKING+from typing import Any, Listimport aiofilesfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,PermissionRule,)from .._response import ToolChunk-from ...message import TextBlock--if TYPE_CHECKING:- from ...agent import AgentState-else:- AgentState = Any+from ...message import TextBlock, ToolResultState+from ...state import AgentStateclass Read(ToolBase):@@ -71,6 +67,7 @@ Usage:is_read_only: bool = Trueis_concurrency_safe: bool = Trueis_external_tool: bool = False+ is_state_injected: bool = Falsedef __init__(self,@@ -188,7 +185,7 @@ Usage:f"got: {file_path}",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -198,7 +195,7 @@ Usage:content=[TextBlock(text=f"Error: File does not exist: {file_path}"),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -211,7 +208,7 @@ Usage:f"{file_path}",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -266,13 +263,13 @@ Usage:return ToolChunk(content=[TextBlock(text=result)],- state="running",+ state=ToolResultState.RUNNING,is_last=True,)except Exception as e:return ToolChunk(content=[TextBlock(text=f"Error reading file: {str(e)}")],- state="error",+ state=ToolResultState.ERROR,is_last=True,)diff --git a/src/agentscope/tool/_builtin/_skill.py b/src/agentscope/tool/_builtin/_skill.pyindex d10d0dae8..bc3eef881 100644--- a/src/agentscope/tool/_builtin/_skill.py+++ b/src/agentscope/tool/_builtin/_skill.py@@ -2,15 +2,15 @@"""The builtin skill viewer tool."""from typing import Any, Callable, Awaitable-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,)from .._response import ToolChunkfrom .._base import ToolBase-from .._types import Skill-from ...message import TextBlock+from ...skill import Skill+from ...message import TextBlock, ToolResultStateclass SkillViewer(ToolBase):@@ -45,6 +45,9 @@ class SkillViewer(ToolBase):is_external_tool: bool = False"""The skill viewer is not an external tool."""+ is_state_injected: bool = False+ """The skill viewer doesn't require state injection."""+is_read_only: bool = True"""The skill viewer is read-only."""@@ -99,7 +102,7 @@ class SkillViewer(ToolBase):f"not found.",),],- state="error",+ state=ToolResultState.ERROR,)return ToolChunk(content=[TextBlock(text=target_skill.markdown)])diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.pyindex 45aff0ca8..f13082361 100644--- a/src/agentscope/tool/_builtin/_write.py+++ b/src/agentscope/tool/_builtin/_write.py@@ -3,12 +3,12 @@import fnmatchimport osfrom pathlib import Path-from typing import Any, List, TYPE_CHECKING+from typing import Any, Listimport aiofilesfrom .._base import ToolBase-from .._permission import (+from ...permission import (PermissionContext,PermissionDecision,PermissionBehavior,@@ -16,12 +16,8 @@ from .._permission import (PermissionRule,)from .._response import ToolChunk-from ...message import TextBlock--if TYPE_CHECKING:- from ...agent import AgentState-else:- AgentState = Any+from ...message import TextBlock, ToolResultState+from ...state import AgentStateclass Write(ToolBase):@@ -61,6 +57,7 @@ Usage:is_read_only: bool = Falseis_concurrency_safe: bool = Falseis_external_tool: bool = False+ is_state_injected: bool = Falsedef __init__(self,@@ -271,7 +268,7 @@ Usage:f"got: {file_path}",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -287,7 +284,7 @@ Usage:f"before writing to it.",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -310,6 +307,6 @@ Usage:f"({line_count} lines).",),],- state="running",+ state=ToolResultState.RUNNING,is_last=True,)diff --git a/src/agentscope/tool/_skill/_base.py b/src/agentscope/tool/_skill/_base.pydeleted file mode 100644index 7c3877313..000000000--- a/src/agentscope/tool/_skill/_base.py+++ /dev/null@@ -1,14 +0,0 @@-# -*- coding: utf-8 -*--"""The skill loader base class."""-from abc import abstractmethod, ABC--from .._types import Skill---class SkillLoaderBase(ABC):- """The base class for skill loader."""-- @abstractmethod- async def list_skills(self) -> list[Skill]:- """List all the skills that can be loaded by this loader."""- raise NotImplementedErrordiff --git a/src/agentscope/tool/_task/__init__.py b/src/agentscope/tool/_task/__init__.pynew file mode 100644index 000000000..023b6a670--- /dev/null+++ b/src/agentscope/tool/_task/__init__.py@@ -0,0 +1,13 @@+# -*- coding: utf-8 -*-+"""Task planning tools for agents."""+from ._create_task import TaskCreate+from ._get_task import TaskGet+from ._list_task import TaskList+from ._update_task import TaskUpdate++__all__ = [+ "TaskCreate",+ "TaskGet",+ "TaskList",+ "TaskUpdate",+]diff --git a/src/agentscope/tool/_task/_create_task.py b/src/agentscope/tool/_task/_create_task.pynew file mode 100644index 000000000..177d48520--- /dev/null+++ b/src/agentscope/tool/_task/_create_task.py@@ -0,0 +1,109 @@+# -*- coding: utf-8 -*-+"""The creating task tool class."""+from typing import Any++from pydantic import BaseModel, Field++from ._task_tool_base import _TaskToolBase+from .._response import ToolChunk+from ...state import AgentState, Task+from ...exception import DeveloperOrientedException+from ...message import TextBlock, ToolResultState+++class _TaskCreateParams(BaseModel):+ """The params of the creating task tool."""++ subject: str = Field(description="A brief title for the task")+ description: str = Field(description="What needs to be done")+ metadata: dict[str, Any] | None = Field(+ default=None,+ description="Arbitrary metadata to attach to the task",+ )+++class TaskCreate(_TaskToolBase):+ """Create a task for the agent to perform."""++ name: str = "TaskCreate"++ # pylint: disable=line-too-long+ description: str = """Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.+It also helps the user understand the progress of the task and overall progress of their requests.++## When to Use This Tool++Use this tool proactively in these scenarios:++- Complex multi-step tasks - When a task requires 3 or more distinct steps or actions+- Non-trivial and complex tasks - Tasks that require careful planning or multiple operations+- Plan mode - When using plan mode, create a task list to track the work+- User explicitly requests todo list - When the user directly asks you to use the todo list+- User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)+- After receiving new instructions - Immediately capture user requirements as tasks+- When you start working on a task - Mark it as in_progress BEFORE beginning work+- After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation++## When NOT to Use This Tool++Skip using this tool when:+- There is only a single, straightforward task+- The task is trivial and tracking it provides no organizational benefit+- The task can be completed in less than 3 trivial steps+- The task is purely conversational or informational++NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.++## Task Fields++- **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")+- **description**: What needs to be done++All tasks are created with status `pending`.++## Tips++- Create tasks with clear, specific subjects that describe the outcome+- After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed+- Check TaskList first to avoid creating duplicate tasks""" # noqa: E501++ input_schema: dict = _TaskCreateParams.model_json_schema()++ async def __call__(+ self,+ _agent_state: AgentState,+ subject: str,+ description: str,+ metadata: dict[str, Any] | None = None,+ ) -> ToolChunk:+ """Create the subtask and add it into the agent state."""+ if not isinstance(_agent_state, AgentState):+ # Expose error to the developer+ raise DeveloperOrientedException(+ f"Error: TaskCreate requires AgentState to be provided, got "+ f"{_agent_state} instead.",+ )++ try:+ task = Task(+ subject=subject,+ description=description,+ metadata=metadata or {},+ )+ _agent_state.tasks_context.tasks.append(task)++ return ToolChunk(+ content=[+ TextBlock(+ text=f"Task {task.id} created successfully: "+ f"{task.subject}",+ ),+ ],+ )+ except Exception as e:+ return ToolChunk(+ content=[+ TextBlock(text=f"CreateTaskError: {e}"),+ ],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/tool/_task/_get_task.py b/src/agentscope/tool/_task/_get_task.pynew file mode 100644index 000000000..7d6ab3e29--- /dev/null+++ b/src/agentscope/tool/_task/_get_task.py@@ -0,0 +1,100 @@+# -*- coding: utf-8 -*-+"""The get task tool class."""+from pydantic import BaseModel, Field++from ._task_tool_base import _TaskToolBase+from .._response import ToolChunk+from ...state import AgentState+from ...exception import DeveloperOrientedException+from ...message import TextBlock, ToolResultState+++class _TaskGetParams(BaseModel):+ """The params of the get task."""++ task_id: str = Field(description="The ID of the task to retrieve")+++class TaskGet(_TaskToolBase):+ """Retrieve a task by its ID from the task list."""++ name: str = "TaskGet"++ description: str = """Use this tool to retrieve a task by its ID from the task list.++## When to Use This Tool++- When you need the full description and context before starting work on a task+- To understand task dependencies (what it blocks, what blocks it)+- After being assigned a task, to get complete requirements++## Output++Returns full task details:+- **subject**: Task title+- **description**: Detailed requirements and context+- **status**: 'pending', 'in_progress', or 'completed'+- **blocks**: Tasks waiting on this one to complete+- **blockedBy**: Tasks that must complete before this one can start++## Tips++- After fetching a task, verify its blockedBy list is empty before beginning work.+- Use TaskList to see all tasks in summary form.""" # noqa: E501++ input_schema: dict = _TaskGetParams.model_json_schema()++ async def __call__(+ self,+ task_id: str,+ _agent_state: AgentState,+ ) -> ToolChunk:+ """Retrieve a task by its ID."""+ if not isinstance(_agent_state, AgentState):+ # Expose error to the developer+ raise DeveloperOrientedException(+ f"Error: TaskGet requires AgentState to be provided, got "+ f"{_agent_state} instead.",+ )++ # Find the task by ID+ task = None+ for t in _agent_state.tasks_context.tasks:+ if t.id == task_id:+ task = t+ break++ if task is None:+ return ToolChunk(+ content=[+ TextBlock(text="Task not found"),+ ],+ state=ToolResultState.ERROR,+ )++ # Build the response+ lines = [+ f"Task #{task.id}: {task.subject}",+ f"Status: {task.state}",+ f"Description: {task.description}",+ ]++ if task.owner:+ lines.append(f"Owner: {task.owner}")++ if task.blocked_by:+ blocked_by_str = ", ".join([f"#{bid}" for bid in task.blocked_by])+ lines.append(f"Blocked by: {blocked_by_str}")++ if task.blocks:+ blocks_str = ", ".join([f"#{bid}" for bid in task.blocks])+ lines.append(f"Blocks: {blocks_str}")++ if task.metadata:+ lines.append(f"Metadata: {task.metadata}")++ return ToolChunk(+ content=[+ TextBlock(text="\n".join(lines)),+ ],+ )diff --git a/src/agentscope/tool/_task/_list_task.py b/src/agentscope/tool/_task/_list_task.pynew file mode 100644index 000000000..7e409f91f--- /dev/null+++ b/src/agentscope/tool/_task/_list_task.py@@ -0,0 +1,74 @@+# -*- coding: utf-8 -*-+"""The task list tool class."""++from ._task_tool_base import _TaskToolBase+from .._response import ToolChunk+from .._base import _ParamsBase+from ...state import AgentState+from ...exception import DeveloperOrientedException+from ...message import TextBlock+++class _TaskListParams(_ParamsBase):+ """The params of the list task params."""+++class TaskList(_TaskToolBase):+ """List tasks for the agent to perform."""++ name: str = "TaskList"++ # pylint: disable=line-too-long+ description: str = """Use this tool to list all tasks in the task list.++## When to Use This Tool+- To see what tasks are available to work on (status: 'pending', no owner, not blocked)+- To check overall progress on the project+- To find tasks that are blocked and need dependencies resolved+- After completing a task, to check for newly unblocked work or claim the next available task+- **Prefer working on tasks in ID order** (lowest ID first) when multiple tasks are available, as earlier tasks often set up context for later ones++## Output++Returns a summary of each task:+- **id**: Task identifier (use with TaskGet, TaskUpdate)+- **subject**: Brief description of the task+- **status**: 'pending', 'in_progress', or 'completed'+- **owner**: Agent ID if assigned, empty if available+- **blockedBy**: List of open task IDs that must be resolved first (tasks with blockedBy cannot be claimed until dependencies resolve)++Use TaskGet with a specific task ID to view full details including description and comments.""" # noqa: E501++ input_schema: dict = _TaskListParams.model_json_schema()++ async def __call__(self, _agent_state: AgentState) -> ToolChunk:+ """List tasks for the agent to perform."""+ if not isinstance(_agent_state, AgentState):+ # Expose error to the developer+ raise DeveloperOrientedException(+ f"Error: TaskList requires AgentState to be provided, got "+ f"{_agent_state} instead.",+ )++ if len(_agent_state.tasks_context.tasks) == 0:+ return ToolChunk(+ content=[TextBlock(text="No tasks available.")],+ )++ tasks = []+ for task in _agent_state.tasks_context.tasks:+ owner = f"({task.owner})" if task.owner else ""+ blocked = (+ f'[blocked by {", ".join(task.blocked_by)}]'+ if task.blocked_by+ else ""+ )+ tasks.append(+ f"#{task.id} [{task.state}] {task.subject}{owner}{blocked}",+ )++ return ToolChunk(+ content=[+ TextBlock(text="\n".join(tasks)),+ ],+ )diff --git a/src/agentscope/tool/_task/_task_tool_base.py b/src/agentscope/tool/_task/_task_tool_base.pynew file mode 100644index 000000000..463a04f1b--- /dev/null+++ b/src/agentscope/tool/_task/_task_tool_base.py@@ -0,0 +1,42 @@+# -*- coding: utf-8 -*-+"""The task tool base class, providing unified interface and permission+check for builtin task related tools."""+from typing import Any++from .._base import ToolBase+from ...permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+)+++class _TaskToolBase(ToolBase):+ name: str++ description: str++ input_schema: dict++ is_concurrency_safe: bool = True++ is_read_only: bool = False++ is_state_injected: bool = True++ is_external_tool: bool = False++ is_mcp: bool = False++ mcp_name: str | None = None++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permission for the tool usage."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is always allowed to be called.",+ )diff --git a/src/agentscope/tool/_task/_update_task.py b/src/agentscope/tool/_task/_update_task.pynew file mode 100644index 000000000..bb294df6e--- /dev/null+++ b/src/agentscope/tool/_task/_update_task.py@@ -0,0 +1,291 @@+# -*- coding: utf-8 -*-+"""The task updated tool class."""+from typing import Literal++from pydantic import BaseModel, Field++from ._task_tool_base import _TaskToolBase+from .._response import ToolChunk+from ...state import AgentState+from ...exception import DeveloperOrientedException+from ...message import TextBlock, ToolResultState+++class _TaskUpdateParams(BaseModel):+ """The params of the update task."""++ task_id: str = Field(description="The task id.")+ subject: str | None = Field(+ default=None,+ description="New subject for the task",+ )+ description: str | None = Field(+ default=None,+ description="New description for the task",+ )+ add_blocks: list[str] | None = Field(+ default=None,+ description="Task IDs that this task blocks",+ )+ status: Literal[+ "pending",+ "in_progress",+ "completed",+ "deleted",+ ] | None = Field(+ default=None,+ description="New status for the task",+ )+ add_blocked_by: list[str] | None = Field(+ default=None,+ description="Task IDs that block this task",+ )+ owner: str | None = Field(+ default=None,+ description="New owner for the task",+ )+ metadata: dict | None = Field(+ default=None,+ description="Metadata keys to merge into the task. "+ "Set a key to null to delete it.",+ )+++class TaskUpdate(_TaskToolBase):+ """The tool to update the agent task."""++ name: str = "TaskUpdate"++ description: str = """Use this tool to update a task in the task list.++## When to Use This Tool++**Mark tasks as resolved:**+- When you have completed the work described in a task+- When a task is no longer needed or has been superseded+- IMPORTANT: Always mark your assigned tasks as resolved when you finish them+- After resolving, call TaskList to find your next task++- ONLY mark a task as completed when you have FULLY accomplished it+- If you encounter errors, blockers, or cannot finish, keep the task as in_progress+- When blocked, create a new task describing what needs to be resolved+- Never mark a task as completed if:+ - Tests are failing+ - Implementation is partial+ - You encountered unresolved errors+ - You couldn't find necessary files or dependencies++**Delete tasks:**+- When a task is no longer relevant or was created in error+- Setting status to `deleted` permanently removes the task++**Update task details:**+- When requirements change or become clearer+- When establishing dependencies between tasks++## Fields You Can Update++- **status**: The task status (see Status Workflow below)+- **subject**: Change the task title (imperative form, e.g., "Run tests")+- **description**: Change the task description+- **owner**: Change the task owner (agent name)+- **metadata**: Merge metadata keys into the task (set a key to null to delete it)+- **add_blocks**: Mark tasks that cannot start until this one completes+- **add_blocked_by**: Mark tasks that must complete before this one can start++## Status Workflow++Status progresses: `pending` → `in_progress` → `completed`++Use `deleted` to permanently remove a task.++## Staleness++Make sure to read a task's latest state using `TaskGet` before updating it.++## Examples++Mark task as in progress when starting work:+```json+{"task_id": "1", "status": "in_progress"}+```++Mark task as completed after finishing work:+```json+{"task_id": "1", "status": "completed"}+```++Delete a task:+```json+{"task_id": "1", "status": "deleted"}+```++Claim a task by setting owner:+```json+{"task_id": "1", "owner": "my-name"}+```++Set up task dependencies:+```json+{"task_id": "2", "add_blocked_by": ["1"]}+```""" # noqa: E501++ input_schema: dict = _TaskUpdateParams.model_json_schema()++ async def __call__(+ self,+ _agent_state: AgentState,+ task_id: str,+ subject: str | None = None,+ description: str | None = None,+ add_blocks: list[str] | None = None,+ status: Literal["pending", "completed", "in_progress", "deleted"]+ | None = None,+ add_blocked_by: list[str] | None = None,+ owner: str | None = None,+ metadata: dict | None = None,+ ) -> ToolChunk:+ """Update the agent task."""+ if not isinstance(_agent_state, AgentState):+ # Expose error to the developer+ raise DeveloperOrientedException(+ f"Error: {self.name} requires AgentState to be provided, got "+ f"{_agent_state} instead.",+ )++ index = None+ for i, task in enumerate(_agent_state.tasks_context.tasks):+ if task.id == task_id:+ index = i++ if index is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"TaskNotFoundError: "+ f"The task {task_id} does not exist.",+ ),+ ],+ state=ToolResultState.ERROR,+ )++ updated_fields = []++ if subject:+ updated_fields.append("subject")+ _agent_state.tasks_context.tasks[index].subject = subject++ if description is not None:+ updated_fields.append("description")+ _agent_state.tasks_context.tasks[index].description = description++ existed_ids = [_.id for _ in _agent_state.tasks_context.tasks]+ if add_blocks:+ current_blocks = _agent_state.tasks_context.tasks[index].blocks+ new_blocks = [+ _+ for _ in add_blocks+ if _ not in current_blocks and _ in existed_ids+ ]+ if new_blocks:+ updated_fields.append("add_blocks")+ for block_id in new_blocks:+ self._update_block_relation(+ task_id,+ block_id,+ _agent_state,+ )++ if add_blocked_by is not None:+ current_blocked_by = _agent_state.tasks_context.tasks[+ index+ ].blocked_by+ new_blocked_by = [+ _+ for _ in add_blocked_by+ if _ not in current_blocked_by and _ in existed_ids+ ]+ if new_blocked_by:+ updated_fields.append("add_blocked_by")+ for blocked_by_id in new_blocked_by:+ self._update_block_relation(+ blocked_by_id,+ task_id,+ _agent_state,+ )++ if status:+ if status == "deleted":+ # Permanently remove the task+ _agent_state.tasks_context.tasks.pop(index)+ # Remove task id from all the blocks and blocked_by+ for task in _agent_state.tasks_context.tasks:+ if task_id in task.blocks:+ task.blocks.remove(task_id)++ if task_id in task.blocked_by:+ task.blocked_by.remove(task_id)+ return ToolChunk(+ content=[+ TextBlock(text=f"Task {task_id} has been deleted."),+ ],+ )+ # Update the status+ updated_fields.append("status")+ _agent_state.tasks_context.tasks[index].state = status++ if owner is not None:+ updated_fields.append("owner")+ _agent_state.tasks_context.tasks[index].owner = owner++ if metadata:+ updated_fields.append("metadata")+ for k, v in metadata.items():+ if v is None:+ _agent_state.tasks_context.tasks[index].metadata.pop(+ k,+ None,+ )+ else:+ _agent_state.tasks_context.tasks[index].metadata[k] = v++ if updated_fields:+ res = f'Update task #{task_id} {", ".join(updated_fields)}.'+ else:+ res = (+ f"No updates were made to the task #{task_id}. "+ f"Make sure you provided at least one field to update and "+ f"the values are correct."+ )++ if _agent_state.tasks_context.tasks[index].state == "completed":+ res += (+ "\n\nTask completed. Call TaskList now to find your next "+ "available task or see if your work unblocked others."+ )++ return ToolChunk(content=[TextBlock(text=res)])++ @staticmethod+ def _update_block_relation(+ block_id: str,+ blocked_by_id: str,+ _agent_state: AgentState,+ ) -> None:+ """Update the block relationship between the tasks.++ Args:+ block_id (`str`):+ The id of the task that blocks the other tasks.+ blocked_by_id (`str`):+ The id of the task blocked by the task of `block_id`.+ _agent_state (`AgentState`):+ The agent state to update.+ """+ # Update the blocks+ for task in _agent_state.tasks_context.tasks:+ if task.id == block_id and blocked_by_id not in task.blocks:+ task.blocks.append(blocked_by_id)++ if task.id == blocked_by_id and block_id not in task.blocked_by:+ task.blocked_by.append(block_id)diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex f593235d3..266a60191 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -5,7 +5,6 @@ import inspectimport warningsfrom collections import OrderedDictfrom copy import deepcopy-from functools import wrapsfrom typing import (AsyncGenerator,Any,@@ -13,7 +12,6 @@ from typing import (Generator,Callable,Coroutine,- TYPE_CHECKING,)import mcp@@ -24,12 +22,12 @@ from pydantic import (create_model,)-from ._builtin import ResetTools, Edit, Write, Read, SkillViewer+from ._builtin import ResetTools, SkillViewerfrom ._base import ToolBasefrom ._adapters import _FunctionToolfrom ._response import ToolResponse, ToolChunk-from ._skill import SkillLoaderBase, LocalSkillLoader-from ._types import ToolGroup, Skill, RegisteredTool+from ..skill import SkillLoaderBase, LocalSkillLoader, Skill+from ._types import ToolGroup, RegisteredToolfrom .._utils._common import _json_loads_with_repairfrom ..exception import (DeveloperOrientedException,@@ -46,71 +44,7 @@ from ..message import (ToolResultState,)from .._logging import logger--if TYPE_CHECKING:- from ..agent import AgentState-else:- AgentState = "AgentState"---def _apply_middlewares(- func: Callable[- ...,- Coroutine[Any, Any, AsyncGenerator[ToolResponse, None]],- ],-) -> Callable[..., AsyncGenerator[ToolResponse, None]]:- """Decorator that applies registered middlewares at runtime.-- This decorator reads the middleware list from the instance and constructs- the middleware chain dynamically during each invocation.-- .. note:: Middlewares must be async generator functions that yield- `ToolResponse` objects.- """-- @wraps(func)- async def wrapper(- self: "Toolkit",- tool_call: ToolCallBlock,- ) -> AsyncGenerator[ToolResponse, None]:- """Wrapper that applies middleware chain."""- middlewares = getattr(self, "_middlewares", [])-- if not middlewares:- # No middlewares, call the original function directly- async for chunk in await func(self, tool_call):- yield chunk- return-- # Build the middleware chain from innermost to outermost- async def base_handler(- **kwargs: Any,- ) -> AsyncGenerator[ToolResponse, None]:- """Base handler that calls the original function."""- return await func(self, **kwargs)-- # Wrap with each middleware in reverse order- current_handler = base_handler- for middleware in reversed(middlewares):-- def make_handler(mw: Callable, handler: Callable) -> Callable:- """Create wrapped handler for middleware."""-- async def wrapped(- **kwargs: Any,- ) -> AsyncGenerator[ToolResponse, None]:- """Handler that applies middleware."""- return mw(kwargs, handler)-- return wrapped-- current_handler = make_handler(middleware, current_handler)-- # Execute the middleware chain- async for chunk in await current_handler(tool_call=tool_call):- yield chunk-- return wrapper+from ..state import AgentState# pylint: disable=line-too-long@@ -520,7 +454,6 @@ class Toolkit:)# @trace_toolkit- # @_apply_middlewaresasync def call_tool(self,tool_call: ToolCallBlock,@@ -535,7 +468,7 @@ class Toolkit:Args:tool_call (`ToolCallBlock`):A tool call block.- state: AgentState:+ state (`AgentState`):The current agent state, used to state injection.Yields:@@ -566,7 +499,7 @@ class Toolkit:),),],- state="error",+ state=ToolResultState.ERROR,)yield chunkyield tool_response.append_chunk(chunk)@@ -580,7 +513,7 @@ class Toolkit:f"'{tool_call.name}' doesn't exist.",),],- state="error",+ state=ToolResultState.ERROR,)yield chunkyield tool_response.append_chunk(chunk)@@ -594,9 +527,12 @@ class Toolkit:# Prepare keyword argumentskwargs = _json_loads_with_repair(tool_call.input)- # TODO: we should be build a mechanism to support state injection- # in the future instead of hard coding here.- if isinstance(tool_func, (ResetTools, Read, Write, Edit)):+ # State injection+ if (+ tool_func.is_state_injected+ and not tool_func.is_mcp+ and not tool_func.is_external_tool+ ):kwargs["_agent_state"] = stateif inspect.iscoroutinefunction(tool_func.__call__):diff --git a/src/agentscope/tool/_types.py b/src/agentscope/tool/_types.pyindex e020a653f..07e8e645c 100644--- a/src/agentscope/tool/_types.py+++ b/src/agentscope/tool/_types.py@@ -169,22 +169,6 @@ class ToolGroup:activated."""-@dataclass-class Skill:- """The agent skill class"""-- name: str- """The name of the skill."""- description: str- """The description of the skill."""- dir: str- """The directory of the agent skill."""- markdown: str- """The markdown content of the agent skill."""- updated_at: float- """The last updated time of the skill."""--# The function types that can be registered as tools in AgentScope.Function: TypeAlias = (# Sync functiondiff --git a/src/agentscope/tool/_utils.py b/src/agentscope/tool/_utils.pyindex 6061626c6..3d98b0211 100644--- a/src/agentscope/tool/_utils.py+++ b/src/agentscope/tool/_utils.py@@ -7,7 +7,7 @@ from docstring_parser import parsefrom pydantic import Field, create_model, ConfigDict-def _remove_title_field(schema: dict) -> None:+def _remove_title_field(schema: dict) -> dict:"""Remove the title field from the JSON schema to avoidmisleading the LLM."""# The top level title field@@ -33,6 +33,8 @@ def _remove_title_field(schema: dict) -> None:schema["additionalProperties"],)+ return schema+def _extract_func_description(docstring: str) -> str:"""Extract the function description from the docstring.diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex ccde9bd1b..faeab6ce1 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -12,12 +12,14 @@ from agentscope.tool import (ToolBase,Toolkit,ToolChunk,+ RegisteredTool,+)+from agentscope.permission import (PermissionDecision,PermissionBehavior,PermissionContext,)from agentscope.message import TextBlock, ToolCallBlock, UserMsg-from agentscope.tool._types import RegisteredToolclass MockSequentialTool(ToolBase):diff --git a/tests/builtin_bash_test.py b/tests/builtin_bash_test.pyindex 861f393ea..4091252c5 100644--- a/tests/builtin_bash_test.py+++ b/tests/builtin_bash_test.py@@ -4,7 +4,12 @@ import sysimport unittestfrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import ToolChunk, PermissionContext, Bash+from agentscope.tool import ToolChunk, Bash+from agentscope.permission import (+ PermissionContext,+ PermissionBehavior,+ PermissionRule,+)from agentscope.message import TextBlock@@ -30,7 +35,6 @@ class BashToolTest(IsolatedAsyncioTestCase):async def test_check_permissions(self) -> None:"""Test bash tool permission checking."""- from agentscope.tool import PermissionBehaviorcontext = PermissionContext()tool_input = {"command": "echo hello"}@@ -94,8 +98,6 @@ class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):async def test_command_substitution_blocked(self) -> None:"""Test that command substitution is blocked."""- from agentscope.tool import PermissionBehavior-test_cases = ["ls $(pwd)","rm $(find . -name '*.tmp')",@@ -112,7 +114,6 @@ class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):async def test_control_flow_blocked(self) -> None:"""Test that control flow structures are blocked."""- from agentscope.tool import PermissionBehaviortest_cases = ["for f in *.txt; do cat $f; done",@@ -133,7 +134,6 @@ class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):async def test_subshell_blocked(self) -> None:"""Test that subshells are blocked."""- from agentscope.tool import PermissionBehaviorcmd = "(cd /tmp && ls)"decision = await self.bash_tool.check_permissions(@@ -145,7 +145,6 @@ class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):async def test_injection_check_before_readonly(self) -> None:"""Test that injection check runs before read-only check."""- from agentscope.tool import PermissionBehavior# ls is read-only, but $(rm -rf /) is dangerouscmd = "ls $(rm -rf /)"@@ -159,7 +158,6 @@ class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):async def test_safe_commands_pass(self) -> None:"""Test that safe commands pass injection check."""- from agentscope.tool import PermissionBehaviorsafe_commands = ["ls -la",@@ -280,7 +278,6 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):async def test_generate_suggestions(self) -> None:"""Test generate_suggestions for bash commands."""- from agentscope.tool import PermissionRule# Test two-word commandsuggestions = self.bash_tool.generate_suggestions(@@ -326,7 +323,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_rm_root_blocked(self) -> None:"""Test that rm -rf / is blocked."""- from agentscope.tool import PermissionBehaviorcmd = "rm -rf /"decision = await self.bash_tool.check_permissions(@@ -343,7 +339,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_rm_root_children_blocked(self) -> None:"""Test that rm -rf /usr, /etc, etc. are blocked."""- from agentscope.tool import PermissionBehaviortest_cases = ["rm -rf /usr",@@ -368,7 +363,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_rm_home_blocked(self) -> None:"""Test that rm -rf ~ is blocked."""- from agentscope.tool import PermissionBehaviorcmd = "rm -rf ~"decision = await self.bash_tool.check_permissions(@@ -385,7 +379,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_rm_wildcard_blocked(self) -> None:"""Test that rm -rf * and rm -rf /* are blocked."""- from agentscope.tool import PermissionBehaviortest_cases = ["rm -rf *",@@ -408,7 +401,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_rmdir_dangerous_paths_blocked(self) -> None:"""Test that rmdir on dangerous paths is blocked."""- from agentscope.tool import PermissionBehaviortest_cases = ["rmdir /",@@ -426,7 +418,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_safe_rm_commands_pass(self) -> None:"""Test that safe rm commands pass dangerous removal check."""- from agentscope.tool import PermissionBehaviorsafe_commands = ["rm file.txt",@@ -450,7 +441,6 @@ class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):async def test_compound_commands_with_dangerous_removal(self) -> None:"""Test compound commands containing dangerous removal."""- from agentscope.tool import PermissionBehaviortest_cases = ["ls && rm -rf /",diff --git a/tests/builtin_edit_test.py b/tests/builtin_edit_test.pyindex 529350272..b342d1e6e 100644--- a/tests/builtin_edit_test.py+++ b/tests/builtin_edit_test.py@@ -4,7 +4,12 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import PermissionContext, PermissionBehavior, Edit+from agentscope.tool import Edit+from agentscope.permission import (+ PermissionContext,+ PermissionBehavior,+ PermissionRule,+)class EditToolTest(IsolatedAsyncioTestCase):@@ -156,7 +161,6 @@ class EditToolTest(IsolatedAsyncioTestCase):async def test_generate_suggestions(self) -> None:"""Test generate_suggestions for file operations."""- from agentscope.tool import PermissionRule# Test suggestion for file in subdirectorysuggestions = self.edit_tool.generate_suggestions(diff --git a/tests/builtin_file_cache_test.py b/tests/builtin_file_cache_test.pyindex 069c3c3f5..9e77019f1 100644--- a/tests/builtin_file_cache_test.py+++ b/tests/builtin_file_cache_test.py@@ -4,7 +4,7 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.agent import AgentState+from agentscope.state import AgentStatefrom agentscope.tool import Read, Write, Editdiff --git a/tests/builtin_glob_test.py b/tests/builtin_glob_test.pyindex c3069dd9e..eb9fe563d 100644--- a/tests/builtin_glob_test.py+++ b/tests/builtin_glob_test.py@@ -4,7 +4,12 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import PermissionContext, PermissionBehavior, Glob+from agentscope.tool import Glob+from agentscope.permission import (+ PermissionContext,+ PermissionBehavior,+ PermissionRule,+)class GlobToolTest(IsolatedAsyncioTestCase):@@ -171,7 +176,6 @@ class GlobToolTest(IsolatedAsyncioTestCase):async def test_generate_suggestions_with_path(self) -> None:"""Test generate_suggestions for glob with explicit path."""- from agentscope.tool import PermissionRulesuggestions = self.glob_tool.generate_suggestions({"path": self.temp_dir, "pattern": "*.py"},diff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.pyindex a8f2627c8..dc73e01bb 100644--- a/tests/builtin_grep_test.py+++ b/tests/builtin_grep_test.py@@ -4,7 +4,12 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import PermissionContext, PermissionBehavior, Grep+from agentscope.tool import Grep+from agentscope.permission import (+ PermissionContext,+ PermissionBehavior,+ PermissionRule,+)class GrepToolTest(IsolatedAsyncioTestCase):@@ -217,7 +222,6 @@ class GrepToolTest(IsolatedAsyncioTestCase):async def test_generate_suggestions_with_path(self) -> None:"""Test generate_suggestions for grep with explicit path."""- from agentscope.tool import PermissionRulesuggestions = self.grep_tool.generate_suggestions({"path": self.temp_dir, "pattern": "hello"},diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.pyindex 4ea058af9..9c1d623d6 100644--- a/tests/builtin_read_test.py+++ b/tests/builtin_read_test.py@@ -4,11 +4,11 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import (- ToolChunk,+from agentscope.tool import ToolChunk, Read+from agentscope.permission import (PermissionContext,PermissionBehavior,- Read,+ PermissionRule,)from agentscope.message import TextBlock@@ -167,7 +167,6 @@ class ReadToolTest(IsolatedAsyncioTestCase):async def test_generate_suggestions(self) -> None:"""Test generate_suggestions for file operations."""- from agentscope.tool import PermissionRule# Test suggestion for file in subdirectorysuggestions = self.read_tool.generate_suggestions(diff --git a/tests/builtin_write_test.py b/tests/builtin_write_test.pyindex f75a88310..acde4363f 100644--- a/tests/builtin_write_test.py+++ b/tests/builtin_write_test.py@@ -4,7 +4,12 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import PermissionContext, PermissionBehavior, Write+from agentscope.tool import Write+from agentscope.permission import (+ PermissionContext,+ PermissionBehavior,+ PermissionRule,+)class WriteToolTest(IsolatedAsyncioTestCase):@@ -163,7 +168,6 @@ class WriteToolTest(IsolatedAsyncioTestCase):async def test_generate_suggestions(self) -> None:"""Test generate_suggestions for file operations."""- from agentscope.tool import PermissionRule# Test suggestion for file in subdirectorysuggestions = self.write_tool.generate_suggestions(diff --git a/tests/context_compression_test.py b/tests/context_compression_test.pyindex 927d6f28f..ca435f717 100644--- a/tests/context_compression_test.py+++ b/tests/context_compression_test.py@@ -6,7 +6,8 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import MockModel, AnyStringfrom agentscope.model import StructuredResponse-from agentscope.agent import Agent, CompressionConfig, AgentState+from agentscope.agent import Agent, CompressionConfig+from agentscope.state import AgentStatefrom agentscope.message import UserMsg, AssistantMsg, TextBlockfrom agentscope.tool import Toolkitdiff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.pyindex ad46d3762..b37fb0332 100644--- a/tests/hitl_external_execution_test.py+++ b/tests/hitl_external_execution_test.py@@ -12,6 +12,9 @@ from agentscope.tool import (ToolBase,Toolkit,ToolChunk,+ RegisteredTool,+)+from agentscope.permission import (PermissionDecision,PermissionBehavior,PermissionContext,@@ -23,7 +26,6 @@ from agentscope.message import (UserMsg,ToolResultState,)-from agentscope.tool._types import RegisteredToolfrom agentscope.event import ExternalExecutionResultEventdiff --git a/tests/hitl_mixed_interrupt.py b/tests/hitl_mixed_interrupt.pyindex eb21b26ba..6b29fce59 100644--- a/tests/hitl_mixed_interrupt.py+++ b/tests/hitl_mixed_interrupt.py@@ -6,13 +6,15 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.event._event import ConfirmResultfrom agentscope.agent import Agentfrom agentscope.model import ChatResponsefrom agentscope.tool import (ToolBase,Toolkit,ToolChunk,+ RegisteredTool,+)+from agentscope.permission import (PermissionDecision,PermissionBehavior,PermissionContext,@@ -24,10 +26,10 @@ from agentscope.message import (UserMsg,ToolResultState,)-from agentscope.tool._types import RegisteredToolfrom agentscope.event import (UserConfirmResultEvent,ExternalExecutionResultEvent,+ ConfirmResult,)diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.pyindex 723bbc971..1e10734dd 100644--- a/tests/hitl_user_confirmation_test.py+++ b/tests/hitl_user_confirmation_test.py@@ -5,13 +5,15 @@ from typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.event._event import ConfirmResultfrom agentscope.agent import Agentfrom agentscope.model import ChatResponsefrom agentscope.tool import (ToolBase,Toolkit,ToolChunk,+ RegisteredTool,+)+from agentscope.permission import (PermissionDecision,PermissionBehavior,PermissionContext,@@ -21,8 +23,7 @@ from agentscope.message import (ToolCallBlock,UserMsg,)-from agentscope.tool._types import RegisteredTool-from agentscope.event import UserConfirmResultEvent+from agentscope.event import UserConfirmResultEvent, ConfirmResultclass MockUserConfirmSequentialTool(ToolBase):diff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.pyindex 40c8d3c1a..d2de36898 100644--- a/tests/mcp_sse_client_test.py+++ b/tests/mcp_sse_client_test.py@@ -10,7 +10,7 @@ from mcp.server import FastMCPfrom agentscope.mcp import HttpStatelessClient, HttpStatefulClientfrom agentscope.message import ToolCallBlockfrom agentscope.tool import ToolResponse, ToolChunk, Toolkit-from agentscope.agent import AgentState+from agentscope.state import AgentStateasync def tool_1(arg1: str, arg2: list[int]) -> str:diff --git a/tests/permission_engine_test.py b/tests/permission_engine_test.pyindex 2645a80fd..a547be1b7 100644--- a/tests/permission_engine_test.py+++ b/tests/permission_engine_test.py@@ -4,13 +4,15 @@ import sysimport unittestfrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import (+from agentscope.permission import (PermissionEngine,PermissionMode,PermissionContext,PermissionRule,PermissionBehavior,AdditionalWorkingDirectory,+)+from agentscope.tool import (Bash,Write,Read,diff --git a/tests/skill_loader_test.py b/tests/skill_loader_test.pyindex eb653601c..101be4ade 100644--- a/tests/skill_loader_test.py+++ b/tests/skill_loader_test.py@@ -7,7 +7,7 @@ import shutilimport timefrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool import LocalSkillLoader+from agentscope.skill import LocalSkillLoaderclass SkillLoaderTest(IsolatedAsyncioTestCase):diff --git a/tests/task_tool_test.py b/tests/task_tool_test.pynew file mode 100644index 000000000..7366c9e84--- /dev/null+++ b/tests/task_tool_test.py@@ -0,0 +1,956 @@+# -*- coding: utf-8 -*-+"""Unit tests for task tools."""+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.state import AgentState+from agentscope.tool import TaskCreate, TaskGet, TaskList, TaskUpdate+++class TestTaskCreate(IsolatedAsyncioTestCase):+ """Test cases for TaskCreate tool."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.agent_state = AgentState()+ self.task_create = TaskCreate()++ async def test_create_single_task(self) -> None:+ """Test creating a single task."""+ result = await self.task_create(+ subject="Test Task 1",+ description="This is a test task",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ task_id = self.agent_state.tasks_context.tasks[0].id+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Task {task_id} created successfully: "+ f"Test Task 1",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task was added to agent state using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Test Task 1",+ "description": "This is a test task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_create_multiple_tasks(self) -> None:+ """Test creating multiple tasks."""+ # Create first task+ result1 = await self.task_create(+ subject="Task 1",+ description="First task",+ _agent_state=self.agent_state,+ )+ task1_id = self.agent_state.tasks_context.tasks[0].id+ expected_result1 = {+ "content": [+ {+ "text": f"Task {task1_id} created successfully: Task 1",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result1.model_dump(mode="json"), expected_result1)++ # Create second task+ result2 = await self.task_create(+ subject="Task 2",+ description="Second task",+ _agent_state=self.agent_state,+ )+ task2_id = self.agent_state.tasks_context.tasks[1].id+ expected_result2 = {+ "content": [+ {+ "text": f"Task {task2_id} created successfully: Task 2",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result2.model_dump(mode="json"), expected_result2)++ # Create third task with metadata+ result3 = await self.task_create(+ subject="Task 3",+ description="Third task",+ metadata={"priority": "high"},+ _agent_state=self.agent_state,+ )+ task3_id = self.agent_state.tasks_context.tasks[2].id+ expected_result3 = {+ "content": [+ {+ "text": f"Task {task3_id} created successfully: Task 3",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result3.model_dump(mode="json"), expected_result3)++ # Check all tasks using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": AnyString(),+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": AnyString(),+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {"priority": "high"},+ "created_at": AnyString(),+ "state": "pending",+ "id": AnyString(),+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_create_task_with_metadata(self) -> None:+ """Test creating a task with metadata."""+ metadata = {"priority": "high", "tags": ["urgent", "bug"]}+ result = await self.task_create(+ subject="Bug Fix",+ description="Fix critical bug",+ metadata=metadata,+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ task_id = self.agent_state.tasks_context.tasks[0].id+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Task {task_id} created successfully: Bug Fix",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Bug Fix",+ "description": "Fix critical bug",+ "metadata": {"priority": "high", "tags": ["urgent", "bug"]},+ "created_at": AnyString(),+ "state": "pending",+ "id": AnyString(),+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)+++class TestTaskList(IsolatedAsyncioTestCase):+ """Test cases for TaskList tool."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.agent_state = AgentState()+ self.task_list = TaskList()+ self.task_create = TaskCreate()++ async def test_list_no_tasks(self) -> None:+ """Test listing when there are no tasks."""+ result = await self.task_list(_agent_state=self.agent_state)++ self.assertEqual(len(result.content), 1)+ self.assertEqual(result.content[0].text, "No tasks available.")++ async def test_list_with_tasks(self) -> None:+ """Test listing when there are tasks."""+ # Create multiple tasks+ await self.task_create(+ subject="Task 1",+ description="First task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 2",+ description="Second task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 3",+ description="Third task",+ _agent_state=self.agent_state,+ )++ task1_id = self.agent_state.tasks_context.tasks[0].id+ task2_id = self.agent_state.tasks_context.tasks[1].id+ task3_id = self.agent_state.tasks_context.tasks[2].id++ # List tasks+ result = await self.task_list(_agent_state=self.agent_state)++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"#{task1_id} [pending] Task 1\n"+ f"#{task2_id} [pending] Task 2\n"+ f"#{task3_id} [pending] Task 3",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)+++class TestTaskGet(IsolatedAsyncioTestCase):+ """Test cases for TaskGet tool."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.agent_state = AgentState()+ self.task_get = TaskGet()+ self.task_create = TaskCreate()++ async def test_get_existing_task(self) -> None:+ """Test getting an existing task."""+ # Create a task+ await self.task_create(+ subject="Test Task",+ description="This is a test task with details",+ metadata={"priority": "high"},+ _agent_state=self.agent_state,+ )++ task_id = self.agent_state.tasks_context.tasks[0].id++ # Get the task+ result = await self.task_get(+ task_id=task_id,+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Task #{task_id}: Test Task\n"+ f"Status: pending\n"+ f"Description: This is a test task with details\n"+ f"Metadata: {{'priority': 'high'}}",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ async def test_get_nonexistent_task(self) -> None:+ """Test getting a task that doesn't exist."""+ result = await self.task_get(+ task_id="nonexistent-id",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": "Task not found",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)+++class TestTaskUpdate(IsolatedAsyncioTestCase):+ """Test cases for TaskUpdate tool."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.agent_state = AgentState()+ self.task_update = TaskUpdate()+ self.task_create = TaskCreate()++ async def test_update_subject(self) -> None:+ """Test updating task subject."""+ # Create a task+ await self.task_create(+ subject="Original Subject",+ description="Test description",+ _agent_state=self.agent_state,+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ # Update subject+ result = await self.task_update(+ task_id=task_id,+ subject="Updated Subject",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} subject.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Updated Subject",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_description(self) -> None:+ """Test updating task description."""+ # Create a task+ await self.task_create(+ subject="Test Task",+ description="Original description",+ _agent_state=self.agent_state,+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ # Update description+ result = await self.task_update(+ task_id=task_id,+ description="Updated description",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} description.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Test Task",+ "description": "Updated description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_status(self) -> None:+ """Test updating task status."""+ # Create a task+ await self.task_create(+ subject="Test Task",+ description="Test description",+ _agent_state=self.agent_state,+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ # Update status to in_progress+ result = await self.task_update(+ task_id=task_id,+ status="in_progress",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} status.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "in_progress",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ # Update status to completed+ result = await self.task_update(+ task_id=task_id,+ status="completed",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} status.\n\n"+ f"Task completed. "+ f"Call TaskList now to find your next available "+ f"task or see if your work unblocked others.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected[0]["state"] = "completed"+ self.assertEqual(tasks_dump, expected)++ # Test deleted status - create a new task first+ await self.task_create(+ subject="Task to Delete",+ description="This task will be deleted",+ _agent_state=self.agent_state,+ )+ task_to_delete_id = self.agent_state.tasks_context.tasks[1].id++ # Update status to deleted+ result = await self.task_update(+ task_id=task_to_delete_id,+ status="deleted",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Task {task_to_delete_id} has been deleted.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check that only the first task remains+ self.assertEqual(len(self.agent_state.tasks_context.tasks), 1)+ self.assertEqual(self.agent_state.tasks_context.tasks[0].id, task_id)++ async def test_update_owner(self) -> None:+ """Test updating task owner."""+ # Create a task+ await self.task_create(+ subject="Test Task",+ description="Test description",+ _agent_state=self.agent_state,+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ # Update owner+ result = await self.task_update(+ task_id=task_id,+ owner="agent-1",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} owner.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": "agent-1",+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_metadata(self) -> None:+ """Test updating task metadata."""+ # Create a task with initial metadata+ await self.task_create(+ subject="Test Task",+ description="Test description",+ metadata={"priority": "low", "tags": ["test"]},+ _agent_state=self.agent_state,+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ # Update metadata+ result = await self.task_update(+ task_id=task_id,+ metadata={"priority": "high", "new_field": "value"},+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task_id} metadata.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {+ "priority": "high",+ "tags": ["test"],+ "new_field": "value",+ },+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_add_blocks(self) -> None:+ """Test updating task blocks relationship."""+ # Create two tasks+ await self.task_create(+ subject="Task 1",+ description="First task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 2",+ description="Second task",+ _agent_state=self.agent_state,+ )++ task1_id = self.agent_state.tasks_context.tasks[0].id+ task2_id = self.agent_state.tasks_context.tasks[1].id++ # Update task1 to block task2+ result = await self.task_update(+ task_id=task1_id,+ add_blocks=[task2_id],+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task1_id} add_blocks.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check tasks using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task1_id,+ "owner": None,+ "blocks": [task2_id],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [task1_id],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_add_blocked_by(self) -> None:+ """Test updating task blockedBy relationship."""+ # Create two tasks+ await self.task_create(+ subject="Task 1",+ description="First task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 2",+ description="Second task",+ _agent_state=self.agent_state,+ )++ task1_id = self.agent_state.tasks_context.tasks[0].id+ task2_id = self.agent_state.tasks_context.tasks[1].id++ # Update task2 to be blocked by task1+ result = await self.task_update(+ task_id=task2_id,+ add_blocked_by=[task1_id],+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Update task #{task2_id} add_blocked_by.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check tasks using model_dump+ tasks_dump = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ expected = [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task1_id,+ "owner": None,+ "blocks": [task2_id],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [task1_id],+ },+ ]+ self.assertEqual(tasks_dump, expected)++ async def test_update_delete_task(self) -> None:+ """Test deleting a task and removing it from blocks/blocked_by."""+ # Create three tasks with dependencies+ await self.task_create(+ subject="Task 1",+ description="First task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 2",+ description="Second task",+ _agent_state=self.agent_state,+ )+ await self.task_create(+ subject="Task 3",+ description="Third task",+ _agent_state=self.agent_state,+ )++ task1_id = self.agent_state.tasks_context.tasks[0].id+ task2_id = self.agent_state.tasks_context.tasks[1].id+ task3_id = self.agent_state.tasks_context.tasks[2].id++ # Set up dependencies: Task 1 blocks Task 2, Task 2 blocks Task 3+ await self.task_update(+ task_id=task1_id,+ add_blocks=[task2_id],+ _agent_state=self.agent_state,+ )+ await self.task_update(+ task_id=task2_id,+ add_blocks=[task3_id],+ _agent_state=self.agent_state,+ )++ # Verify dependencies are set up correctly+ tasks_before = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ self.assertEqual(tasks_before[0]["blocks"], [task2_id])+ self.assertEqual(tasks_before[1]["blocked_by"], [task1_id])+ self.assertEqual(tasks_before[1]["blocks"], [task3_id])+ self.assertEqual(tasks_before[2]["blocked_by"], [task2_id])++ # Delete task 2 (which is in the middle of the dependency chain)+ result = await self.task_update(+ task_id=task2_id,+ status="deleted",+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": f"Task {task2_id} has been deleted.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)++ # Check task was removed and task2_id was removed from+ # blocks/blocked_by+ self.assertEqual(len(self.agent_state.tasks_context.tasks), 2)++ tasks_after = [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+ # Task 1 should no longer have task2_id in blocks+ self.assertEqual(tasks_after[0]["id"], task1_id)+ self.assertEqual(tasks_after[0]["blocks"], [])++ # Task 3 should no longer have task2_id in blocked_by+ self.assertEqual(tasks_after[1]["id"], task3_id)+ self.assertEqual(tasks_after[1]["blocked_by"], [])++ async def test_update_nonexistent_task(self) -> None:+ """Test updating a task that doesn't exist."""+ result = await self.task_update(+ task_id="nonexistent-id",+ subject="New Subject",+ description=None,+ _agent_state=self.agent_state,+ )++ # Check result using model_dump+ result_dump = result.model_dump(mode="json")+ expected_result = {+ "content": [+ {+ "text": "TaskNotFoundError: "+ "The task nonexistent-id does not exist.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+ self.assertDictEqual(result_dump, expected_result)diff --git a/tests/toolkit_skill_test.py b/tests/toolkit_skill_test.pyindex 17509d086..41a25ba76 100644--- a/tests/toolkit_skill_test.py+++ b/tests/toolkit_skill_test.py@@ -6,11 +6,10 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString-from agentscope.tool import SkillLoaderBase, LocalSkillLoader-from agentscope.tool import Toolkit-from agentscope.tool import Skill, ToolChunk, ToolResponse+from agentscope.skill import SkillLoaderBase, LocalSkillLoader, Skill+from agentscope.tool import Toolkit, ToolChunk, ToolResponsefrom agentscope.message import ToolCallBlock-from agentscope.agent import AgentState+from agentscope.state import AgentStatedef _make_skill(diff --git a/tests/toolkit_task_test.py b/tests/toolkit_task_test.pynew file mode 100644index 000000000..bcb78552b--- /dev/null+++ b/tests/toolkit_task_test.py@@ -0,0 +1,1186 @@+# -*- coding: utf-8 -*-+"""Unit tests for task tools executed through toolkit."""+import json+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.message import ToolCallBlock+from agentscope.state import AgentState+from agentscope.tool import (+ Toolkit,+ ToolResponse,+ TaskCreate,+ TaskGet,+ TaskList,+ TaskUpdate,+)+++class _ToolkitTaskTestBase(IsolatedAsyncioTestCase):+ """Shared helpers for toolkit task tool tests."""++ async def asyncSetUp(self) -> None:+ """Set up shared test fixtures."""+ self.maxDiff = None+ self.agent_state = AgentState()+ self.toolkit = Toolkit(+ tools=[+ TaskCreate(),+ TaskList(),+ TaskGet(),+ TaskUpdate(),+ ],+ )++ async def _call_tool(+ self,+ name: str,+ tool_input: dict[str, Any],+ tool_call_id: str,+ ) -> ToolResponse:+ """Call a task tool through toolkit and return the final response."""+ response = None+ async for result in self.toolkit.call_tool(+ ToolCallBlock(+ id=tool_call_id,+ name=name,+ input=json.dumps(tool_input),+ ),+ self.agent_state,+ ):+ if isinstance(result, ToolResponse):+ response = result++ self.assertIsNotNone(response)+ return response++ def _dump_tasks(self) -> list[dict[str, Any]]:+ """Dump all tasks from the agent state for assertions."""+ return [+ task.model_dump() for task in self.agent_state.tasks_context.tasks+ ]+++class TestToolkitTaskCreate(_ToolkitTaskTestBase):+ """Test cases for TaskCreate through toolkit."""++ async def test_create_single_task(self) -> None:+ """Test creating a single task."""+ response = await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task 1",+ "description": "This is a test task",+ },+ tool_call_id="task-create-single",+ )++ task_id = self.agent_state.tasks_context.tasks[0].id+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_id} created successfully: "+ "Test Task 1",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-create-single",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task 1",+ "description": "This is a test task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_create_multiple_tasks(self) -> None:+ """Test creating multiple tasks."""+ response_1 = await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 1",+ "description": "First task",+ },+ tool_call_id="task-create-1",+ )+ task_1_id = self.agent_state.tasks_context.tasks[0].id+ self.assertDictEqual(+ response_1.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_1_id} created successfully: "+ f"Task 1",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-create-1",+ },+ )++ response_2 = await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 2",+ "description": "Second task",+ },+ tool_call_id="task-create-2",+ )+ task_2_id = self.agent_state.tasks_context.tasks[1].id+ self.assertDictEqual(+ response_2.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_2_id} created successfully: "+ f"Task 2",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-create-2",+ },+ )++ response_3 = await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {"priority": "high"},+ },+ tool_call_id="task-create-3",+ )+ task_3_id = self.agent_state.tasks_context.tasks[2].id+ self.assertDictEqual(+ response_3.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_3_id} created successfully: "+ f"Task 3",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-create-3",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {"priority": "high"},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_3_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_create_task_with_metadata(self) -> None:+ """Test creating a task with metadata."""+ response = await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Bug Fix",+ "description": "Fix critical bug",+ "metadata": {+ "priority": "high",+ "tags": ["urgent", "bug"],+ },+ },+ tool_call_id="task-create-metadata",+ )++ task_id = self.agent_state.tasks_context.tasks[0].id+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_id} created successfully: "+ f"Bug Fix",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-create-metadata",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Bug Fix",+ "description": "Fix critical bug",+ "metadata": {+ "priority": "high",+ "tags": ["urgent", "bug"],+ },+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )+++class TestToolkitTaskList(_ToolkitTaskTestBase):+ """Test cases for TaskList through toolkit."""++ async def test_list_no_tasks(self) -> None:+ """Test listing when there are no tasks."""+ response = await self._call_tool(+ name="TaskList",+ tool_input={},+ tool_call_id="task-list-empty",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": "No tasks available.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-list-empty",+ },+ )+ self.assertEqual(self._dump_tasks(), [])++ async def test_list_with_tasks(self) -> None:+ """Test listing when there are tasks."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 1",+ "description": "First task",+ },+ tool_call_id="task-list-create-1",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 2",+ "description": "Second task",+ },+ tool_call_id="task-list-create-2",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 3",+ "description": "Third task",+ },+ tool_call_id="task-list-create-3",+ )++ task_1_id = self.agent_state.tasks_context.tasks[0].id+ task_2_id = self.agent_state.tasks_context.tasks[1].id+ task_3_id = self.agent_state.tasks_context.tasks[2].id++ response = await self._call_tool(+ name="TaskList",+ tool_input={},+ tool_call_id="task-list-with-tasks",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"#{task_1_id} [pending] Task 1\n"+ f"#{task_2_id} [pending] Task 2\n"+ f"#{task_3_id} [pending] Task 3",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-list-with-tasks",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_3_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )+++class TestToolkitTaskGet(_ToolkitTaskTestBase):+ """Test cases for TaskGet through toolkit."""++ async def test_get_existing_task(self) -> None:+ """Test getting an existing task."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task",+ "description": "This is a test task with details",+ "metadata": {"priority": "high"},+ },+ tool_call_id="task-get-create",+ )++ task_id = self.agent_state.tasks_context.tasks[0].id+ response = await self._call_tool(+ name="TaskGet",+ tool_input={"task_id": task_id},+ tool_call_id="task-get-existing",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Task #{task_id}: Test Task\n"+ "Status: pending\n"+ "Description: This is a test task with details\n"+ "Metadata: {'priority': 'high'}",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-get-existing",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "This is a test task with details",+ "metadata": {"priority": "high"},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_get_nonexistent_task(self) -> None:+ """Test getting a task that does not exist."""+ response = await self._call_tool(+ name="TaskGet",+ tool_input={"task_id": "nonexistent-id"},+ tool_call_id="task-get-missing",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": "Task not found",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "error",+ "metadata": {},+ "id": "task-get-missing",+ },+ )+ self.assertEqual(self._dump_tasks(), [])+++class TestToolkitTaskUpdate(_ToolkitTaskTestBase):+ """Test cases for TaskUpdate through toolkit."""++ async def test_update_subject(self) -> None:+ """Test updating task subject."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Original Subject",+ "description": "Test description",+ },+ tool_call_id="task-update-subject-create",+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "subject": "Updated Subject",+ },+ tool_call_id="task-update-subject",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} subject.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-subject",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Updated Subject",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_description(self) -> None:+ """Test updating task description."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task",+ "description": "Original description",+ },+ tool_call_id="task-update-description-create",+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "description": "Updated description",+ },+ tool_call_id="task-update-description",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} description.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-description",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Updated description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_status(self) -> None:+ """Test updating task status."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task",+ "description": "Test description",+ },+ tool_call_id="task-update-status-create",+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "status": "in_progress",+ },+ tool_call_id="task-update-status-in-progress",+ )+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} status.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-status-in-progress",+ },+ )+ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "in_progress",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "status": "completed",+ },+ tool_call_id="task-update-status-completed",+ )+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} status.\n\n"+ "Task completed. Call TaskList now to find your "+ "next available task or see if your work "+ "unblocked others.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-status-completed",+ },+ )+ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "completed",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task to Delete",+ "description": "This task will be deleted",+ },+ tool_call_id="task-update-status-create-delete",+ )+ task_to_delete_id = self.agent_state.tasks_context.tasks[1].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_to_delete_id,+ "status": "deleted",+ },+ tool_call_id="task-update-status-deleted",+ )+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_to_delete_id} has been deleted.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-status-deleted",+ },+ )+ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "completed",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_owner(self) -> None:+ """Test updating task owner."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task",+ "description": "Test description",+ },+ tool_call_id="task-update-owner-create",+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "owner": "agent-1",+ },+ tool_call_id="task-update-owner",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} owner.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-owner",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": "agent-1",+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_metadata(self) -> None:+ """Test updating task metadata."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {+ "priority": "low",+ "tags": ["test"],+ },+ },+ tool_call_id="task-update-metadata-create",+ )+ task_id = self.agent_state.tasks_context.tasks[0].id++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_id,+ "metadata": {+ "priority": "high",+ "new_field": "value",+ },+ },+ tool_call_id="task-update-metadata",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_id} metadata.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-metadata",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Test Task",+ "description": "Test description",+ "metadata": {+ "priority": "high",+ "tags": ["test"],+ "new_field": "value",+ },+ "created_at": AnyString(),+ "state": "pending",+ "id": task_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_add_blocks(self) -> None:+ """Test updating task blocks relationship."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 1",+ "description": "First task",+ },+ tool_call_id="task-update-add-blocks-create-1",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 2",+ "description": "Second task",+ },+ tool_call_id="task-update-add-blocks-create-2",+ )++ task_1_id = self.agent_state.tasks_context.tasks[0].id+ task_2_id = self.agent_state.tasks_context.tasks[1].id+ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_1_id,+ "add_blocks": [task_2_id],+ },+ tool_call_id="task-update-add-blocks",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_1_id} add_blocks.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-add-blocks",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [task_2_id],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [task_1_id],+ },+ ],+ )++ async def test_update_add_blocked_by(self) -> None:+ """Test updating task blocked_by relationship."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 1",+ "description": "First task",+ },+ tool_call_id="task-update-add-blocked-by-create-1",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 2",+ "description": "Second task",+ },+ tool_call_id="task-update-add-blocked-by-create-2",+ )++ task_1_id = self.agent_state.tasks_context.tasks[0].id+ task_2_id = self.agent_state.tasks_context.tasks[1].id+ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_2_id,+ "add_blocked_by": [task_1_id],+ },+ tool_call_id="task-update-add-blocked-by",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Update task #{task_2_id} add_blocked_by.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-add-blocked-by",+ },+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [task_2_id],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_2_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [task_1_id],+ },+ ],+ )++ async def test_update_delete_task(self) -> None:+ """Test deleting a task and cleaning dependency relations."""+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 1",+ "description": "First task",+ },+ tool_call_id="task-update-delete-create-1",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 2",+ "description": "Second task",+ },+ tool_call_id="task-update-delete-create-2",+ )+ await self._call_tool(+ name="TaskCreate",+ tool_input={+ "subject": "Task 3",+ "description": "Third task",+ },+ tool_call_id="task-update-delete-create-3",+ )++ task_1_id = self.agent_state.tasks_context.tasks[0].id+ task_2_id = self.agent_state.tasks_context.tasks[1].id+ task_3_id = self.agent_state.tasks_context.tasks[2].id++ await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_1_id,+ "add_blocks": [task_2_id],+ },+ tool_call_id="task-update-delete-link-1",+ )+ await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_2_id,+ "add_blocks": [task_3_id],+ },+ tool_call_id="task-update-delete-link-2",+ )++ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [task_2_id],+ "blocked_by": [],+ },+ {+ "subject": "Task 2",+ "description": "Second task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_2_id,+ "owner": None,+ "blocks": [task_3_id],+ "blocked_by": [task_1_id],+ },+ {+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_3_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [task_2_id],+ },+ ],+ )++ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": task_2_id,+ "status": "deleted",+ },+ tool_call_id="task-update-delete",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": f"Task {task_2_id} has been deleted.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "task-update-delete",+ },+ )+ self.assertEqual(+ self._dump_tasks(),+ [+ {+ "subject": "Task 1",+ "description": "First task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_1_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ {+ "subject": "Task 3",+ "description": "Third task",+ "metadata": {},+ "created_at": AnyString(),+ "state": "pending",+ "id": task_3_id,+ "owner": None,+ "blocks": [],+ "blocked_by": [],+ },+ ],+ )++ async def test_update_nonexistent_task(self) -> None:+ """Test updating a task that does not exist."""+ response = await self._call_tool(+ name="TaskUpdate",+ tool_input={+ "task_id": "nonexistent-id",+ "subject": "New Subject",+ "description": None,+ },+ tool_call_id="task-update-missing",+ )++ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "text": "TaskNotFoundError: "+ "The task nonexistent-id does not exist.",+ "type": "text",+ "id": AnyString(),+ },+ ],+ "state": "error",+ "metadata": {},+ "id": "task-update-missing",+ },+ )+ self.assertEqual(self._dump_tasks(), [])diff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex f6b326cc6..f02c7422e 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -6,7 +6,7 @@ from typing import Any, AsyncGenerator, Generatorfrom unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString-from agentscope.agent import AgentState+from agentscope.state import AgentStatefrom agentscope.message import (TextBlock,ToolCallBlock,@@ -17,9 +17,11 @@ from agentscope.tool import (Toolkit,ToolBase,ToolChunk,+ ToolResponse,+)+from agentscope.permission import (PermissionDecision,PermissionBehavior,- ToolResponse,)