File size: 11,996 Bytes
068bc7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""TaskManagementTool β€” create, list, update, and delete tasks.

Tasks are stored in ~/.stack-2.9/tasks.json.
"""

from __future__ import annotations

import json
import os
import uuid
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from typing import Any

from .base import BaseTool, ToolResult
from .registry import get_registry

TOOL_NAME = "TaskManagement"
DATA_DIR = os.path.expanduser("~/.stack-2.9")
TASKS_FILE = os.path.join(DATA_DIR, "tasks.json")


def _load_tasks() -> list[dict[str, Any]]:
    """Load tasks from disk."""
    os.makedirs(DATA_DIR, exist_ok=True)
    if os.path.exists(TASKS_FILE):
        try:
            with open(TASKS_FILE) as f:
                return json.load(f)
        except Exception:
            pass
    return []


def _save_tasks(tasks: list[dict[str, Any]]) -> None:
    """Persist tasks to disk."""
    os.makedirs(DATA_DIR, exist_ok=True)
    with open(TASKS_FILE, "w") as f:
        json.dump(tasks, f, indent=2, default=str)


# ── sub-commands as separate tool classes ─────────────────────────────────────


class TaskCreateTool(BaseTool[dict[str, Any], dict[str, Any]]):
    """Create a new task.

    Parameters
    ----------
    subject : str
        Brief, actionable title (required).
    description : str
        Detailed description of what needs to be done.
    status : str, optional
        One of "pending" (default), "in_progress", "completed", "cancelled".
    priority : str, optional
        One of "low", "medium", "high", "urgent" (default "medium").
    tags : list[str], optional
        Arbitrary labels for the task.
    metadata : dict, optional
        Arbitrary extra data to attach.
    """

    name = "TaskCreate"
    description = "Create a new task in the task list."
    search_hint = "create a task in the task list"

    @property
    def input_schema(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "subject": {"type": "string", "description": "Brief title for the task"},
                "description": {"type": "string", "description": "What needs to be done"},
                "status": {
                    "type": "string",
                    "enum": ["pending", "in_progress", "completed", "cancelled"],
                    "description": "Task status (default: pending)",
                    "default": "pending",
                },
                "priority": {
                    "type": "string",
                    "enum": ["low", "medium", "high", "urgent"],
                    "description": "Priority level (default: medium)",
                    "default": "medium",
                },
                "tags": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Labels to attach to the task",
                },
                "metadata": {
                    "type": "object",
                    "description": "Arbitrary extra data",
                },
            },
            "required": ["subject"],
        }

    def validate_input(self, input_data: dict[str, Any]) -> tuple[bool, str | None]:
        if not input_data.get("subject"):
            return False, "Error: subject is required"
        return True, None

    def execute(self, input_data: dict[str, Any]) -> ToolResult[dict[str, Any]]:
        tasks = _load_tasks()
        task_id = str(uuid.uuid4())[:8]

        task = {
            "id": task_id,
            "subject": input_data["subject"],
            "description": input_data.get("description", ""),
            "status": input_data.get("status", "pending"),
            "priority": input_data.get("priority", "medium"),
            "tags": input_data.get("tags", []),
            "metadata": input_data.get("metadata", {}),
            "created_at": datetime.now(timezone.utc).isoformat(),
            "updated_at": datetime.now(timezone.utc).isoformat(),
        }

        tasks.append(task)
        _save_tasks(tasks)

        return ToolResult(
            success=True,
            data={"id": task_id, "subject": task["subject"], "status": task["status"]},
        )

    def map_result_to_message(self, result: dict, tool_use_id: str | None = None) -> str:
        return f"Task #{result['id']} created: {result['subject']} [{result['status']}]"


class TaskListTool(BaseTool[dict[str, Any], dict[str, Any]]):
    """List tasks, optionally filtered by status.

    Parameters
    ----------
    status : str, optional
        Filter by status: "pending", "in_progress", "completed", "cancelled".
    tag : str, optional
        Filter by tag.
    limit : int, optional
        Maximum number of tasks to return (default 50).
    """

    name = "TaskList"
    description = "List tasks from the task list, optionally filtered."
    search_hint = "list tasks in the task list"

    @property
    def input_schema(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["pending", "in_progress", "completed", "cancelled"],
                    "description": "Filter by status",
                },
                "tag": {"type": "string", "description": "Filter by tag"},
                "limit": {
                    "type": "integer",
                    "description": "Maximum tasks to return (default 50)",
                    "default": 50,
                    "minimum": 1,
                    "maximum": 200,
                },
            },
            "properties": {
                "status": {"type": "string"},
                "tag": {"type": "string"},
                "limit": {"type": "integer", "default": 50},
            },
        }

    def execute(self, input_data: dict[str, Any]) -> ToolResult[dict[str, Any]]:
        tasks = _load_tasks()
        status_filter = input_data.get("status")
        tag_filter = input_data.get("tag")
        limit = input_data.get("limit", 50)

        if status_filter:
            tasks = [t for t in tasks if t.get("status") == status_filter]
        if tag_filter:
            tasks = [t for t in tasks if tag_filter in t.get("tags", [])]

        tasks = tasks[:limit]

        return ToolResult(
            success=True,
            data={
                "tasks": [
                    {
                        "id": t["id"],
                        "subject": t["subject"],
                        "status": t["status"],
                        "priority": t.get("priority", "medium"),
                        "tags": t.get("tags", []),
                        "created_at": t.get("created_at", ""),
                    }
                    for t in tasks
                ],
                "total": len(tasks),
            },
        )

    def map_result_to_message(self, result: dict, tool_use_id: str | None = None) -> str:
        tasks = result.get("tasks", [])
        if not tasks:
            return "No tasks found."

        lines = [f"{result['total']} task(s):\n"]
        for t in tasks:
            tags = ", ".join(t.get("tags", [])) if t.get("tags") else ""
            lines.append(f"  [{t['status']:12}] #{t['id']} {t['subject']} {'| ' + tags if tags else ''}")
        return "\n".join(lines)


class TaskUpdateTool(BaseTool[dict[str, Any], dict[str, Any]]):
    """Update a task by ID.

    Parameters
    ----------
    id : str
        The task ID (required).
    subject : str, optional
        New title.
    description : str, optional
        New description.
    status : str, optional
        New status.
    priority : str, optional
        New priority.
    tags : list[str], optional
        New tags (replaces existing).
    """

    name = "TaskUpdate"
    description = "Update an existing task by ID."
    search_hint = "update a task in the task list"

    @property
    def input_schema(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "id": {"type": "string", "description": "Task ID (required)"},
                "subject": {"type": "string", "description": "New title"},
                "description": {"type": "string", "description": "New description"},
                "status": {
                    "type": "string",
                    "enum": ["pending", "in_progress", "completed", "cancelled"],
                },
                "priority": {"type": "string", "enum": ["low", "medium", "high", "urgent"]},
                "tags": {"type": "array", "items": {"type": "string"}, "description": "Replace tags"},
                "metadata": {"type": "object", "description": "Merge into metadata"},
            },
            "required": ["id"],
        }

    def validate_input(self, input_data: dict[str, Any]) -> tuple[bool, str | None]:
        if not input_data.get("id"):
            return False, "Error: id is required"
        return True, None

    def execute(self, input_data: dict[str, Any]) -> ToolResult[dict[str, Any]]:
        tasks = _load_tasks()
        task_id = input_data["id"]

        found = False
        for t in tasks:
            if t["id"] == task_id:
                if "subject" in input_data:
                    t["subject"] = input_data["subject"]
                if "description" in input_data:
                    t["description"] = input_data["description"]
                if "status" in input_data:
                    t["status"] = input_data["status"]
                if "priority" in input_data:
                    t["priority"] = input_data["priority"]
                if "tags" in input_data:
                    t["tags"] = input_data["tags"]
                if "metadata" in input_data:
                    t["metadata"] = {**t.get("metadata", {}), **input_data["metadata"]}
                t["updated_at"] = datetime.now(timezone.utc).isoformat()
                found = True
                break

        if not found:
            return ToolResult(success=False, error=f"Task #{task_id} not found")

        _save_tasks(tasks)
        return ToolResult(success=True, data={"id": task_id, "status": t.get("status")})

    def map_result_to_message(self, result: dict, tool_use_id: str | None = None) -> str:
        return f"Task #{result['id']} updated."


class TaskDeleteTool(BaseTool[dict[str, Any], dict[str, Any]]):
    """Delete a task by ID.

    Parameters
    ----------
    id : str
        The task ID to delete (required).
    """

    name = "TaskDelete"
    description = "Delete a task by ID."
    search_hint = "delete a task"

    @property
    def input_schema(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "id": {"type": "string", "description": "Task ID to delete"},
            },
            "required": ["id"],
        }

    def validate_input(self, input_data: dict[str, Any]) -> tuple[bool, str | None]:
        if not input_data.get("id"):
            return False, "Error: id is required"
        return True, None

    def execute(self, input_data: dict[str, Any]) -> ToolResult[dict[str, Any]]:
        tasks = _load_tasks()
        task_id = input_data["id"]
        original_len = len(tasks)
        tasks = [t for t in tasks if t["id"] != task_id]

        if len(tasks) == original_len:
            return ToolResult(success=False, error=f"Task #{task_id} not found")

        _save_tasks(tasks)
        return ToolResult(success=True, data={"id": task_id, "deleted": True})

    def map_result_to_message(self, result: dict, tool_use_id: str | None = None) -> str:
        return f"Task #{result['id']} deleted."


# Register all task tools
_registry = get_registry()
_registry.register(TaskCreateTool())
_registry.register(TaskListTool())
_registry.register(TaskUpdateTool())
_registry.register(TaskDeleteTool())