TronCode Tron CLI 插件开发

概述

插件系统允许深度扩展 Tron 功能,包括新工具、新命令、新 UI 组件。与自定义工具相比,插件拥有更完整的生命周期管理和更丰富的扩展点,适合构建复杂、可复用的功能模块。

插件基于 Node.js 开发,通过标准 npm 包分发,可以在技能市场或 npm 注册表中发布,供其他 Tron 用户安装使用。

插件结构

一个标准的 Tron 插件目录结构如下:

text
tron-plugin-my-plugin/
├── package.json        # npm 包元数据
├── manifest.json       # 插件声明文件
├── index.js            # 插件入口
└── README.md           # 文档(可选)

manifest.json 声明插件的元数据、扩展点和权限:

json
{
  "name": "tron-plugin-my-plugin",
  "version": "1.0.0",
  "description": "我的 Tron 插件示例",
  "author": "your-name",
  "tronVersion": ">=0.2.0",
  "contributes": {
    "tools": [
      {
        "name": "my_custom_tool",
        "description": "自定义工具描述"
      }
    ],
    "commands": [
      {
        "name": "my-command",
        "description": "自定义命令描述"
      }
    ]
  },
  "permissions": ["read_file", "write_file", "network"]
}

生命周期钩子

Tron 在关键节点触发钩子事件,插件可以监听并响应这些事件:

javascript
// index.js
module.exports = {
  // 插件激活时调用
  activate(context) {
    // 监听每条消息发送
    context.hooks.on('onMessage', async (message, next) => {
      console.log(`用户发送消息: ${message.content}`);
      return next(message);
    });

    // 监听工具调用
    context.hooks.on('onToolCall', async (tool, next) => {
      console.log(`调用工具: ${tool.name}`, tool.input);
      const result = await next(tool);
      // 可以修改工具返回值
      return result;
    });

    // 监听文件写入
    context.hooks.on('onFileWrite', async (file, next) => {
      // 在文件写入前进行校验
      if (file.path.endsWith('.env')) {
        throw new Error('禁止修改 .env 文件');
      }
      return next(file);
    });

    // 注册自定义工具
    context.tools.register({
      name: 'my_custom_tool',
      handler: async (input) => {
        // 工具实现逻辑
        return { result: '工具执行完成' };
      }
    });
  },

  // 插件停用时调用(清理资源)
  deactivate() {
    console.log('插件已停用');
  }
};

注册插件

从本地目录安装开发中的插件:

终端
tron plugin install ./tron-plugin-my-plugin
已安装插件:tron-plugin-my-plugin@1.0.0

从 npm 安装已发布的插件:

终端
tron plugin install tron-plugin-my-plugin

发布插件

通过 npm 发布插件,让其他 Tron 用户安装使用。包名必须遵循 tron-plugin-* 规范:

1
确保 package.json 配置正确

名称格式为 tron-plugin-your-name,包含正确的 main 字段指向 index.js

2
登录 npm 账号
终端
npm login
3
发布到 npm
终端
npm publish
+ tron-plugin-my-plugin@1.0.0
💡
命名规范

所有 Tron 插件包名应以 tron-plugin- 开头,便于用户在 npm 搜索时发现你的插件。