File size: 8,684 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
"""SkillTool - Skill execution framework for Stack 2.9"""

import json
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

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

SKILLS_FILE = Path.home() / ".stack-2.9" / "skills.json"
SKILL_DIRS = [
    Path.home() / ".npm-global" / "lib" / "node_modules" / "openclaw" / "skills",
    Path.home() / ".openclaw" / "workspace" / "skills",
]


def _load_skills() -> Dict[str, Any]:
    """Load skills inventory from disk."""
    SKILLS_FILE.parent.mkdir(parents=True, exist_ok=True)
    if SKILLS_FILE.exists():
        return json.loads(SKILLS_FILE.read_text())
    return {"skills": [], "inventory": {}}


def _save_skills(data: Dict[str, Any]) -> None:
    """Save skills inventory to disk."""
    SKILLS_FILE.write_text(json.dumps(data, indent=2))


def _discover_skills() -> List[Dict[str, str]]:
    """Discover available skills from skill directories."""
    discovered = []
    for skill_dir in SKILL_DIRS:
        if skill_dir.exists():
            for item in skill_dir.iterdir():
                if item.is_dir() and (item / "SKILL.md").exists():
                    discovered.append({
                        "name": item.name,
                        "path": str(item),
                        "description": _get_skill_description(item)
                    })
    return discovered


def _get_skill_description(skill_path: Path) -> str:
    """Extract description from SKILL.md."""
    skill_md = skill_path / "SKILL.md"
    if skill_md.exists():
        content = skill_md.read_text()[:200]
        return content.split("\n")[0] if content else "No description"
    return "No description"


class SkillListTool(BaseTool):
    """List all available skills."""

    name = "skill_list"
    description = "List all available skills that can be executed"

    input_schema = {
        "type": "object",
        "properties": {
            "search": {
                "type": "string",
                "description": "Search term to filter skills"
            }
        },
        "required": []
    }

    async def execute(self, search: str = "") -> ToolResult:
        """List skills."""
        data = _load_skills()
        discovered = _discover_skills()

        skills = discovered
        if search:
            skills = [s for s in skills if search.lower() in s["name"].lower() or search.lower() in s.get("description", "").lower()]

        return ToolResult(success=True, data={
            "skills": skills,
            "count": len(skills)
        })


class SkillExecuteTool(BaseTool):
    """Execute a specific skill."""

    name = "skill_execute"
    description = "Execute a skill with given parameters"

    input_schema = {
        "type": "object",
        "properties": {
            "skill_name": {
                "type": "string",
                "description": "Name of the skill to execute"
            },
            "parameters": {
                "type": "object",
                "description": "Parameters to pass to the skill"
            },
            "chain": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Optional chain of skills to execute in sequence"
            }
        },
        "required": ["skill_name"]
    }

    async def execute(self, skill_name: str, parameters: Optional[Dict] = None, chain: Optional[List[str]] = None) -> ToolResult:
        """Execute a skill."""
        skill_path = None
        for dir in SKILL_DIRS:
            potential = dir / skill_name
            if potential.exists():
                skill_path = potential
                break

        if not skill_path:
            return ToolResult(success=False, error=f"Skill '{skill_name}' not found")

        data = _load_skills()
        result = {"skill": skill_name, "executed_at": datetime.now().isoformat(), "parameters": parameters or {}}

        # Log execution
        if "inventory" not in data:
            data["inventory"] = {}
        if skill_name not in data["inventory"]:
            data["inventory"][skill_name] = {"executions": [], "last_run": None}
        data["inventory"][skill_name]["executions"].append(result["executed_at"])
        data["inventory"][skill_name]["last_run"] = result["executed_at"]
        _save_skills(data)

        # Execute chain if provided
        if chain:
            result["chain"] = chain
            result["chain_results"] = []

        return ToolResult(success=True, data=result)


class SkillInfoTool(BaseTool):
    """Get detailed info about a skill."""

    name = "skill_info"
    description = "Get detailed information about a specific skill"

    input_schema = {
        "type": "object",
        "properties": {
            "skill_name": {
                "type": "string",
                "description": "Name of the skill"
            }
        },
        "required": ["skill_name"]
    }

    async def execute(self, skill_name: str) -> ToolResult:
        """Get skill info."""
        skill_path = None
        for dir in SKILL_DIRS:
            potential = dir / skill_name
            if potential.exists():
                skill_path = potential
                break

        if not skill_path:
            return ToolResult(success=False, error=f"Skill '{skill_name}' not found")

        skill_md = skill_path / "SKILL.md"
        description = ""
        if skill_md.exists():
            content = skill_md.read_text()
            lines = content.split("\n")
            description = lines[0] if lines else ""

        return ToolResult(success=True, data={
            "name": skill_name,
            "path": str(skill_path),
            "description": description,
            "has_script": (skill_path / "script.sh").exists() or (skill_path / "script.py").exists()
        })


class SkillChainTool(BaseTool):
    """Execute a chain of skills in sequence."""

    name = "skill_chain"
    description = "Execute multiple skills in sequence, passing output of each to the next"

    input_schema = {
        "type": "object",
        "properties": {
            "skills": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "skill_name": {"type": "string"},
                        "parameters": {"type": "object"}
                    }
                },
                "description": "List of skills to execute in order"
            }
        },
        "required": ["skills"]
    }

    async def execute(self, skills: List[Dict]) -> ToolResult:
        """Execute skill chain."""
        results = []
        for i, step in enumerate(skills):
            skill_name = step.get("skill_name")
            params = step.get("parameters", {})

            skill_path = None
            for dir in SKILL_DIRS:
                potential = dir / skill_name
                if potential.exists():
                    skill_path = potential
                    break

            if not skill_path:
                results.append({"step": i + 1, "skill": skill_name, "status": "error", "error": f"Skill not found"})
                continue

            results.append({
                "step": i + 1,
                "skill": skill_name,
                "parameters": params,
                "status": "executed",
                "executed_at": datetime.now().isoformat()
            })

        return ToolResult(success=True, data={
            "chain_length": len(skills),
            "results": results
        })


class SkillSearchTool(BaseTool):
    """Search for skills by keyword."""

    name = "skill_search"
    description = "Search for skills by name or description"

    input_schema = {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "Search query"
            }
        },
        "required": ["query"]
    }

    async def execute(self, query: str) -> ToolResult:
        """Search skills."""
        discovered = _discover_skills()
        matches = [s for s in discovered if query.lower() in s["name"].lower() or query.lower() in s.get("description", "").lower()]

        return ToolResult(success=True, data={
            "query": query,
            "matches": matches,
            "count": len(matches)
        })


# Register tools
tool_registry.register(SkillListTool())
tool_registry.register(SkillExecuteTool())
tool_registry.register(SkillInfoTool())
tool_registry.register(SkillChainTool())
tool_registry.register(SkillSearchTool())