---
name: python-plugin-dev
description: Python 插件开发指南。当用户说"创建 Python 插件"、"用 Python 写插件"时立即调用此 skill。注意：只适合python 开发插件
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---

# Python 插件开发

## 概述

Python 插件允许用 Python 语言开发工具，插件代码运行在 Python 环境中，可以调用所有 Python 库。

## 插件存放位置

`.agent/plugins/*.py`

## 插件结构

```python
# .agent/plugins/my-plugin.py

PLUGIN = {
    "name": "my-plugin",
    "version": "1.0.0",
    "description": "我的 Python 插件"
}

TOOLS = [
    {
        "name": "hello",
        "description": "问候工具",
        "params": {"name": "string"}
    },
    {
        "name": "calc",
        "description": "计算器工具",
        "params": {"a": "number", "b": "number", "op": "string"}
    }
]

# === 工具实现 ===

def hello(params):
    """问候工具"""
    name = params.get("name", "World")
    return {"success": True, "result": f"Hello, {name}!"}

def calc(params):
    """计算器工具"""
    a = params.get("a", 0)
    b = params.get("b", 0)
    op = params.get("op", "add")

    if op == "add":
        result = a + b
    elif op == "sub":
        result = a - b
    elif op == "mul":
        result = a * b
    elif op == "div":
        if b == 0:
            return {"success": False, "error": "Division by zero"}
        result = a / b
    else:
        return {"success": False, "error": f"Unknown operation: {op}"}

    return {"success": True, "result": result}
```

**重要**：`tools` 字段定义了插件提供的所有工具。框架会自动：

1. 将这些工具注册到 ExtensionExecutor
2. 附加到系统提示词【Extensions 扩展工具】部分
3. 可通过 `ext_call` 调用

## 工具函数规范

| 规范         | 说明                 |
| ------------ | -------------------- |
| 返回 dict    | 必须是 Python 字典   |
| success 字段 | `true` 或 `false`    |
| result 字段  | 成功时返回的结果     |
| error 字段   | 失败时返回的错误信息 |

## 返回值格式

```python
# 成功
{"success": True, "result": "返回值"}

# 失败
{"success": False, "error": "错误信息"}

# 返回复杂数据
{"success": True, "result": {"key": "value", "list": [1, 2, 3]}}
```

## 使用方式

通过 `ext_call` 调用：

```javascript
ext_call({
  plugin: 'my-plugin', // 插件名称
  tool: 'hello', // 工具名称
  args: { name: 'Foliko' }, // 工具参数
});
```

工具会自动出现在系统提示词的【Extensions 扩展工具】部分。

## 示例：天气查询插件

```python
# .agent/plugins/weather.py

PLUGIN = {
    "name": "weather",
    "version": "1.0.0",
    "description": "天气查询插件"
}

TOOLS = [
    {
        "name": "get_weather",
        "description": "查询天气",
        "params": {"city": "string"}
    }
]

def get_weather(params):
    import requests

    city = params.get("city", "北京")

    try:
        response = requests.get(
            f"https://wttr.in/{city}?format=j1",
            timeout=5
        )
        data = response.json()

        return {
            "success": True,
            "result": {
                "city": city,
                "temperature": data["current_condition"][0]["temp_C"],
                "weather": data["current_condition"][0]["weatherDesc"][0]["value"]
            }
        }
    except Exception as e:
        return {"success": False, "error": str(e)}
```

## 示例：文件处理插件

```python
# .agent/plugins/file_processor.py

PLUGIN = {
    "name": "file_processor",
    "version": "1.0.0",
    "description": "文件处理插件"
}

TOOLS = [
    {
        "name": "read_file",
        "description": "读取文件",
        "params": {"path": "string"}
    },
    {
        "name": "write_file",
        "description": "写入文件",
        "params": {"path": "string", "content": "string"}
    }
]

def read_file(params):
    import os

    filepath = params.get("path")
    if not filepath:
        return {"success": False, "error": "path is required"}

    try:
        with open(filepath, "r", encoding="utf-8") as f:
            content = f.read()
        return {"success": True, "result": content}
    except Exception as e:
        return {"success": False, "error": str(e)}

def write_file(params):
    import os

    filepath = params.get("path")
    content = params.get("content", "")

    if not filepath:
        return {"success": False, "error": "path is required"}

    try:
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(content)
        return {"success": True, "result": f"Written to {filepath}"}
    except Exception as e:
        return {"success": False, "error": str(e)}
```

## 注意事项

1. **文件格式** - 必须是单个 `.py` 文件
2. **必须定义 `PLUGIN`** - 插件元信息
3. **必须定义 `TOOLS`** - 工具列表
4. **工具函数名** - 必须与 TOOLS 中定义的 name 一致
5. **异常处理** - 所有可能出错的地方都要 try-except
6. **编码** - 文件使用 UTF-8 编码

## 开发流程

1. **编写插件代码** - 在 `.agent/plugins/` 下创建 `.py` 文件
2. **自动加载** - 框架启动时自动注册工具
3. **调试** - 查看返回的 `success` 和 `error` 信息

## 常用 Python 库

插件中可以使用的常用库：

| 库       | 用途       | 导入方式                        |
| -------- | ---------- | ------------------------------- |
| requests | HTTP 请求  | `import requests`               |
| json     | JSON 处理  | `import json`                   |
| os       | 系统操作   | `import os`                     |
| pathlib  | 路径处理   | `from pathlib import Path`      |
| datetime | 日期时间   | `from datetime import datetime` |
| re       | 正则表达式 | `import re`                     |
| csv      | CSV 处理   | `import csv`                    |
