feat: 优化鲁班角色并完善ToolSandbox工具开发体系
## 鲁班角色优化 - 新增tool-best-practices知识模块:工具设计最佳实践、性能优化、安全防护 - 新增dpml-tool-tagging知识模块:DPML工具标签四组件架构精通 - 增强craftsmanship思维模式:现代工具特征完善 - 资源迁移到包级别:支持跨项目共享 ## ToolSandbox架构完善 - 实现ToolSandbox类:支持@tool://协议的三阶段执行流程 - 优化依赖管理:getDependencies()接口标准化 - 完善UserProtocol:支持@user://沙箱目录访问 - 增强工具发现:FilePatternDiscovery支持多种文件模式 ## 工具生态建设 - 添加tool.tag.md:DPML工具标签框架完整定义 - 重构ToolInterface:统一getDependencies()接口规范 - 优化ToolExecutor:集成ToolSandbox执行流程 - 更新注册表:29个资源完整注册发现 ## 技术架构改进 - pnpm依赖集成:自动化沙箱环境管理 - 协议系统完善:@tool://和@user://协议标准化 - 资源结构统一:包级别和项目级别一致性 - 开发流程标准化:从需求分析到质量保证的完整工作流 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@ -67,12 +67,13 @@
|
|||||||
"nodemailer": "^7.0.3",
|
"nodemailer": "^7.0.3",
|
||||||
"ora": "^5.4.1",
|
"ora": "^5.4.1",
|
||||||
"pkg-dir": "^8.0.0",
|
"pkg-dir": "^8.0.0",
|
||||||
|
"pnpm": "^10.12.4",
|
||||||
"resolve": "^1.22.10",
|
"resolve": "^1.22.10",
|
||||||
"resolve-package": "^1.0.1",
|
"resolve-package": "^1.0.1",
|
||||||
"semver": "^7.5.0",
|
"semver": "^7.5.0",
|
||||||
|
"tree-kill": "^1.2.2",
|
||||||
"yaml": "^2.3.0",
|
"yaml": "^2.3.0",
|
||||||
"zod": "^3.25.62",
|
"zod": "^3.25.62"
|
||||||
"tree-kill": "^1.2.2"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@changesets/changelog-github": "^0.5.1",
|
"@changesets/changelog-github": "^0.5.1",
|
||||||
|
|||||||
10
pnpm-lock.yaml
generated
10
pnpm-lock.yaml
generated
@ -68,6 +68,9 @@ importers:
|
|||||||
pkg-dir:
|
pkg-dir:
|
||||||
specifier: ^8.0.0
|
specifier: ^8.0.0
|
||||||
version: 8.0.0
|
version: 8.0.0
|
||||||
|
pnpm:
|
||||||
|
specifier: ^10.12.4
|
||||||
|
version: 10.12.4
|
||||||
resolve:
|
resolve:
|
||||||
specifier: ^1.22.10
|
specifier: ^1.22.10
|
||||||
version: 1.22.10
|
version: 1.22.10
|
||||||
@ -2440,6 +2443,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-4peoBq4Wks0riS0z8741NVv+/8IiTvqnZAr8QGgtdifrtpdXbNw/FxRS1l6NFqm4EMzuS0EDqNNx4XGaz8cuyQ==}
|
resolution: {integrity: sha512-4peoBq4Wks0riS0z8741NVv+/8IiTvqnZAr8QGgtdifrtpdXbNw/FxRS1l6NFqm4EMzuS0EDqNNx4XGaz8cuyQ==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
pnpm@10.12.4:
|
||||||
|
resolution: {integrity: sha512-Xqiw3u2U7WhpHJutTJVUknBcXuuKh++GvGLHSiawN7CP+VcPEIsuTb0d0akYb+qSXlJ/FBxkjoWvRWMQdGgBhA==}
|
||||||
|
engines: {node: '>=18.12'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
possible-typed-array-names@1.1.0:
|
possible-typed-array-names@1.1.0:
|
||||||
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
|
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@ -5945,6 +5953,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
find-up-simple: 1.0.1
|
find-up-simple: 1.0.1
|
||||||
|
|
||||||
|
pnpm@10.12.4: {}
|
||||||
|
|
||||||
possible-typed-array-names@1.1.0: {}
|
possible-typed-array-names@1.1.0: {}
|
||||||
|
|
||||||
prelude-ls@1.2.1: {}
|
prelude-ls@1.2.1: {}
|
||||||
|
|||||||
@ -4,9 +4,9 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"description": "package 级资源注册表",
|
"description": "package 级资源注册表",
|
||||||
"createdAt": "2025-06-28T08:03:43.222Z",
|
"createdAt": "2025-06-28T11:40:17.935Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.234Z",
|
"updatedAt": "2025-06-28T11:40:17.951Z",
|
||||||
"resourceCount": 23
|
"resourceCount": 29
|
||||||
},
|
},
|
||||||
"resources": [
|
"resources": [
|
||||||
{
|
{
|
||||||
@ -17,13 +17,28 @@
|
|||||||
"description": "专业角色,提供特定领域的专业能力",
|
"description": "专业角色,提供特定领域的专业能力",
|
||||||
"reference": "@package://resource/role/assistant/assistant.role.md",
|
"reference": "@package://resource/role/assistant/assistant.role.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.226Z",
|
"createdAt": "2025-06-28T11:40:17.941Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.226Z",
|
"updatedAt": "2025-06-28T11:40:17.941Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.226Z",
|
"scannedAt": "2025-06-28T11:40:17.941Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/assistant.role.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/assistant.role.md",
|
||||||
"fileType": "role"
|
"fileType": "role"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "luban",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "role",
|
||||||
|
"name": "Luban 角色",
|
||||||
|
"description": "专业角色,提供特定领域的专业能力",
|
||||||
|
"reference": "@package://resource/role/luban/luban.role.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.941Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.941Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.941Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/luban.role.md",
|
||||||
|
"fileType": "role"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "noface",
|
"id": "noface",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
@ -32,9 +47,9 @@
|
|||||||
"description": "专业角色,提供特定领域的专业能力",
|
"description": "专业角色,提供特定领域的专业能力",
|
||||||
"reference": "@package://resource/role/noface/noface.role.md",
|
"reference": "@package://resource/role/noface/noface.role.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.226Z",
|
"createdAt": "2025-06-28T11:40:17.942Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.226Z",
|
"updatedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.226Z",
|
"scannedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/noface.role.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/noface.role.md",
|
||||||
"fileType": "role"
|
"fileType": "role"
|
||||||
}
|
}
|
||||||
@ -47,9 +62,9 @@
|
|||||||
"description": "专业角色,提供特定领域的专业能力",
|
"description": "专业角色,提供特定领域的专业能力",
|
||||||
"reference": "@package://resource/role/nuwa/nuwa.role.md",
|
"reference": "@package://resource/role/nuwa/nuwa.role.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.226Z",
|
"createdAt": "2025-06-28T11:40:17.942Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.226Z",
|
"updatedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.226Z",
|
"scannedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/nuwa.role.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/nuwa.role.md",
|
||||||
"fileType": "role"
|
"fileType": "role"
|
||||||
}
|
}
|
||||||
@ -62,310 +77,384 @@
|
|||||||
"description": "专业角色,提供特定领域的专业能力",
|
"description": "专业角色,提供特定领域的专业能力",
|
||||||
"reference": "@package://resource/role/sean/sean.role.md",
|
"reference": "@package://resource/role/sean/sean.role.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.227Z",
|
"createdAt": "2025-06-28T11:40:17.942Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.227Z",
|
"updatedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.227Z",
|
"scannedAt": "2025-06-28T11:40:17.942Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/sean.role.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/sean.role.md",
|
||||||
"fileType": "role"
|
"fileType": "role"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:recall_v1",
|
"id": "recall_v1",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:recall_v1 思维模式",
|
"name": "Recall_v1 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/core/_deprecated/recall_v1.thought.md",
|
"reference": "@package://resource/core/_deprecated/recall_v1.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.227Z",
|
"createdAt": "2025-06-28T11:40:17.943Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.227Z",
|
"updatedAt": "2025-06-28T11:40:17.943Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.227Z",
|
"scannedAt": "2025-06-28T11:40:17.943Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/recall_v1.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/recall_v1.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:remember_v1",
|
"id": "remember_v1",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:remember_v1 思维模式",
|
"name": "Remember_v1 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/core/_deprecated/remember_v1.thought.md",
|
"reference": "@package://resource/core/_deprecated/remember_v1.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.228Z",
|
"createdAt": "2025-06-28T11:40:17.943Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.228Z",
|
"updatedAt": "2025-06-28T11:40:17.943Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.228Z",
|
"scannedAt": "2025-06-28T11:40:17.943Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/remember_v1.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/remember_v1.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:remember-xml",
|
"id": "remember-xml",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:remember Xml 思维模式",
|
"name": "Remember Xml 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/core/remember-xml.thought.md",
|
"reference": "@package://resource/core/remember-xml.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.228Z",
|
"createdAt": "2025-06-28T11:40:17.944Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.228Z",
|
"updatedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.228Z",
|
"scannedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember-xml.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember-xml.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:remember",
|
"id": "remember",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:remember 思维模式",
|
"name": "Remember 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/core/remember.thought.md",
|
"reference": "@package://resource/core/remember.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.229Z",
|
"createdAt": "2025-06-28T11:40:17.944Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.229Z",
|
"updatedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.229Z",
|
"scannedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:assistant",
|
"id": "assistant",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:assistant 思维模式",
|
"name": "Assistant 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/role/assistant/thought/assistant.thought.md",
|
"reference": "@package://resource/role/assistant/thought/assistant.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.229Z",
|
"createdAt": "2025-06-28T11:40:17.944Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.229Z",
|
"updatedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.229Z",
|
"scannedAt": "2025-06-28T11:40:17.944Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/thought/assistant.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/thought/assistant.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "thought:role-creation",
|
"id": "craftsmanship",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "thought",
|
"protocol": "thought",
|
||||||
"name": "Thought:role Creation 思维模式",
|
"name": "Craftsmanship 思维模式",
|
||||||
|
"description": "思维模式,指导AI的思考方式",
|
||||||
|
"reference": "@package://resource/role/luban/thought/craftsmanship.thought.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.944Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.944Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.944Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/craftsmanship.thought.md",
|
||||||
|
"fileType": "thought"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "role-creation",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "thought",
|
||||||
|
"name": "Role Creation 思维模式",
|
||||||
"description": "思维模式,指导AI的思考方式",
|
"description": "思维模式,指导AI的思考方式",
|
||||||
"reference": "@package://resource/role/nuwa/thought/role-creation.thought.md",
|
"reference": "@package://resource/role/nuwa/thought/role-creation.thought.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.229Z",
|
"createdAt": "2025-06-28T11:40:17.945Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.229Z",
|
"updatedAt": "2025-06-28T11:40:17.945Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.229Z",
|
"scannedAt": "2025-06-28T11:40:17.945Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/thought/role-creation.thought.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/thought/role-creation.thought.md",
|
||||||
"fileType": "thought"
|
"fileType": "thought"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:assistant",
|
"id": "assistant",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:assistant 执行模式",
|
"name": "Assistant 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/assistant/execution/assistant.execution.md",
|
"reference": "@package://resource/role/assistant/execution/assistant.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.230Z",
|
"createdAt": "2025-06-28T11:40:17.946Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.230Z",
|
"updatedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.230Z",
|
"scannedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/execution/assistant.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/execution/assistant.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:adaptive-learning",
|
"id": "tool-development-workflow",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:adaptive Learning 执行模式",
|
"name": "Tool Development Workflow 执行模式",
|
||||||
|
"description": "执行模式,定义具体的行为模式",
|
||||||
|
"reference": "@package://resource/role/luban/execution/tool-development-workflow.execution.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/execution/tool-development-workflow.execution.md",
|
||||||
|
"fileType": "execution"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "toolsandbox-mastery",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "execution",
|
||||||
|
"name": "Toolsandbox Mastery 执行模式",
|
||||||
|
"description": "执行模式,定义具体的行为模式",
|
||||||
|
"reference": "@package://resource/role/luban/execution/toolsandbox-mastery.execution.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.946Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/execution/toolsandbox-mastery.execution.md",
|
||||||
|
"fileType": "execution"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "adaptive-learning",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "execution",
|
||||||
|
"name": "Adaptive Learning 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/noface/execution/adaptive-learning.execution.md",
|
"reference": "@package://resource/role/noface/execution/adaptive-learning.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.230Z",
|
"createdAt": "2025-06-28T11:40:17.946Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.230Z",
|
"updatedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.230Z",
|
"scannedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/adaptive-learning.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/adaptive-learning.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:content-preservation",
|
"id": "content-preservation",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:content Preservation 执行模式",
|
"name": "Content Preservation 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/noface/execution/content-preservation.execution.md",
|
"reference": "@package://resource/role/noface/execution/content-preservation.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.230Z",
|
"createdAt": "2025-06-28T11:40:17.946Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.230Z",
|
"updatedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.230Z",
|
"scannedAt": "2025-06-28T11:40:17.946Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/content-preservation.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/content-preservation.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:dpml-authoring",
|
"id": "dpml-authoring",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:dpml Authoring 执行模式",
|
"name": "Dpml Authoring 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/nuwa/execution/dpml-authoring.execution.md",
|
"reference": "@package://resource/role/nuwa/execution/dpml-authoring.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.230Z",
|
"createdAt": "2025-06-28T11:40:17.947Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.230Z",
|
"updatedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.230Z",
|
"scannedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/dpml-authoring.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/dpml-authoring.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:role-design-patterns",
|
"id": "role-design-patterns",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:role Design Patterns 执行模式",
|
"name": "Role Design Patterns 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/nuwa/execution/role-design-patterns.execution.md",
|
"reference": "@package://resource/role/nuwa/execution/role-design-patterns.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.231Z",
|
"createdAt": "2025-06-28T11:40:17.947Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.231Z",
|
"updatedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.231Z",
|
"scannedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-design-patterns.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-design-patterns.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:role-generation",
|
"id": "role-generation",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:role Generation 执行模式",
|
"name": "Role Generation 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/nuwa/execution/role-generation.execution.md",
|
"reference": "@package://resource/role/nuwa/execution/role-generation.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.231Z",
|
"createdAt": "2025-06-28T11:40:17.947Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.231Z",
|
"updatedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.231Z",
|
"scannedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-generation.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-generation.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:visualization-enhancement",
|
"id": "visualization-enhancement",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:visualization Enhancement 执行模式",
|
"name": "Visualization Enhancement 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/nuwa/execution/visualization-enhancement.execution.md",
|
"reference": "@package://resource/role/nuwa/execution/visualization-enhancement.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.231Z",
|
"createdAt": "2025-06-28T11:40:17.947Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.231Z",
|
"updatedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.231Z",
|
"scannedAt": "2025-06-28T11:40:17.947Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/visualization-enhancement.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/visualization-enhancement.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "execution:template-adherence",
|
"id": "template-adherence",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "execution",
|
"protocol": "execution",
|
||||||
"name": "Execution:template Adherence 执行模式",
|
"name": "Template Adherence 执行模式",
|
||||||
"description": "执行模式,定义具体的行为模式",
|
"description": "执行模式,定义具体的行为模式",
|
||||||
"reference": "@package://resource/role/sean/execution/template-adherence.execution.md",
|
"reference": "@package://resource/role/sean/execution/template-adherence.execution.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.231Z",
|
"createdAt": "2025-06-28T11:40:17.948Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.231Z",
|
"updatedAt": "2025-06-28T11:40:17.948Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.231Z",
|
"scannedAt": "2025-06-28T11:40:17.948Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/execution/template-adherence.execution.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/execution/template-adherence.execution.md",
|
||||||
"fileType": "execution"
|
"fileType": "execution"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "knowledge:contradiction-methodology",
|
"id": "dpml-tool-tagging",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "knowledge",
|
"protocol": "knowledge",
|
||||||
"name": "Knowledge:contradiction Methodology 知识库",
|
"name": "Dpml Tool Tagging 知识库",
|
||||||
|
"description": "知识库,提供专业知识和信息",
|
||||||
|
"reference": "@package://resource/role/luban/knowledge/dpml-tool-tagging.knowledge.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/dpml-tool-tagging.knowledge.md",
|
||||||
|
"fileType": "knowledge"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "javascript-ecosystem",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "knowledge",
|
||||||
|
"name": "Javascript Ecosystem 知识库",
|
||||||
|
"description": "知识库,提供专业知识和信息",
|
||||||
|
"reference": "@package://resource/role/luban/knowledge/javascript-ecosystem.knowledge.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/javascript-ecosystem.knowledge.md",
|
||||||
|
"fileType": "knowledge"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "promptx-tool-architecture",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "knowledge",
|
||||||
|
"name": "Promptx Tool Architecture 知识库",
|
||||||
|
"description": "知识库,提供专业知识和信息",
|
||||||
|
"reference": "@package://resource/role/luban/knowledge/promptx-tool-architecture.knowledge.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/promptx-tool-architecture.knowledge.md",
|
||||||
|
"fileType": "knowledge"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "tool-best-practices",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "knowledge",
|
||||||
|
"name": "Tool Best Practices 知识库",
|
||||||
|
"description": "知识库,提供专业知识和信息",
|
||||||
|
"reference": "@package://resource/role/luban/knowledge/tool-best-practices.knowledge.md",
|
||||||
|
"metadata": {
|
||||||
|
"createdAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"updatedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"scannedAt": "2025-06-28T11:40:17.949Z",
|
||||||
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/tool-best-practices.knowledge.md",
|
||||||
|
"fileType": "knowledge"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "contradiction-methodology",
|
||||||
|
"source": "package",
|
||||||
|
"protocol": "knowledge",
|
||||||
|
"name": "Contradiction Methodology 知识库",
|
||||||
"description": "知识库,提供专业知识和信息",
|
"description": "知识库,提供专业知识和信息",
|
||||||
"reference": "@package://resource/role/sean/knowledge/contradiction-methodology.knowledge.md",
|
"reference": "@package://resource/role/sean/knowledge/contradiction-methodology.knowledge.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.232Z",
|
"createdAt": "2025-06-28T11:40:17.949Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.232Z",
|
"updatedAt": "2025-06-28T11:40:17.949Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.232Z",
|
"scannedAt": "2025-06-28T11:40:17.949Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/contradiction-methodology.knowledge.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/contradiction-methodology.knowledge.md",
|
||||||
"fileType": "knowledge"
|
"fileType": "knowledge"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "knowledge:product-philosophy",
|
"id": "product-philosophy",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "knowledge",
|
"protocol": "knowledge",
|
||||||
"name": "Knowledge:product Philosophy 知识库",
|
"name": "Product Philosophy 知识库",
|
||||||
"description": "知识库,提供专业知识和信息",
|
"description": "知识库,提供专业知识和信息",
|
||||||
"reference": "@package://resource/role/sean/knowledge/product-philosophy.knowledge.md",
|
"reference": "@package://resource/role/sean/knowledge/product-philosophy.knowledge.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.232Z",
|
"createdAt": "2025-06-28T11:40:17.950Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.232Z",
|
"updatedAt": "2025-06-28T11:40:17.950Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.232Z",
|
"scannedAt": "2025-06-28T11:40:17.950Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/product-philosophy.knowledge.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/product-philosophy.knowledge.md",
|
||||||
"fileType": "knowledge"
|
"fileType": "knowledge"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "knowledge:promptx-evolution",
|
"id": "promptx-evolution",
|
||||||
"source": "package",
|
"source": "package",
|
||||||
"protocol": "knowledge",
|
"protocol": "knowledge",
|
||||||
"name": "Knowledge:promptx Evolution 知识库",
|
"name": "Promptx Evolution 知识库",
|
||||||
"description": "知识库,提供专业知识和信息",
|
"description": "知识库,提供专业知识和信息",
|
||||||
"reference": "@package://resource/role/sean/knowledge/promptx-evolution.knowledge.md",
|
"reference": "@package://resource/role/sean/knowledge/promptx-evolution.knowledge.md",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"createdAt": "2025-06-28T08:03:43.232Z",
|
"createdAt": "2025-06-28T11:40:17.950Z",
|
||||||
"updatedAt": "2025-06-28T08:03:43.232Z",
|
"updatedAt": "2025-06-28T11:40:17.950Z",
|
||||||
"scannedAt": "2025-06-28T08:03:43.232Z",
|
"scannedAt": "2025-06-28T11:40:17.950Z",
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/promptx-evolution.knowledge.md",
|
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/promptx-evolution.knowledge.md",
|
||||||
"fileType": "knowledge"
|
"fileType": "knowledge"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "tool:calculator",
|
|
||||||
"source": "package",
|
|
||||||
"protocol": "tool",
|
|
||||||
"name": "Tool:calculator tool",
|
|
||||||
"description": "tool类型的资源",
|
|
||||||
"reference": "@package://resource/tool/calculator.tool.js",
|
|
||||||
"metadata": {
|
|
||||||
"createdAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"updatedAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"scannedAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/tool/calculator.tool.js",
|
|
||||||
"fileType": "tool"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "tool:send-email",
|
|
||||||
"source": "package",
|
|
||||||
"protocol": "tool",
|
|
||||||
"name": "Tool:send Email tool",
|
|
||||||
"description": "tool类型的资源",
|
|
||||||
"reference": "@package://resource/tool/send-email.tool.js",
|
|
||||||
"metadata": {
|
|
||||||
"createdAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"updatedAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"scannedAt": "2025-06-28T08:03:43.233Z",
|
|
||||||
"filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/tool/send-email.tool.js",
|
|
||||||
"fileType": "tool"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"stats": {
|
"stats": {
|
||||||
"totalResources": 23,
|
"totalResources": 29,
|
||||||
"byProtocol": {
|
"byProtocol": {
|
||||||
"role": 4,
|
"role": 5,
|
||||||
"thought": 6,
|
"thought": 7,
|
||||||
"execution": 8,
|
"execution": 10,
|
||||||
"knowledge": 3,
|
"knowledge": 7
|
||||||
"tool": 2
|
|
||||||
},
|
},
|
||||||
"bySource": {
|
"bySource": {
|
||||||
"package": 23
|
"package": 29
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
96
resource/protocol/tag/tool.tag.md
Normal file
96
resource/protocol/tag/tool.tag.md
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
# DPML#工具提示单元 框架
|
||||||
|
|
||||||
|
> **TL;DR:** DPML#工具提示单元 框架定义了基于四组件架构的完整#AI工具构建方法,通过#用途说明(purpose)、#使用方法(usage)、#参数定义(parameter) 和#预期结果(outcome) 的组合来创建自包含的#AI工具指导。
|
||||||
|
|
||||||
|
### 目的与功能
|
||||||
|
|
||||||
|
DPML#工具提示单元 框架提供了构建#AI工具的标准化方法,主要功能包括:
|
||||||
|
- 基于四组件架构构建完整的#AI工具定义
|
||||||
|
- 确保#工具定义 的自包含性和完整性
|
||||||
|
- 支持不同领域#AI工具 的灵活定制
|
||||||
|
- 与PromptX工具执行系统完美集成
|
||||||
|
|
||||||
|
## 📝 语法定义
|
||||||
|
|
||||||
|
```ebnf
|
||||||
|
(* EBNF形式化定义 *)
|
||||||
|
tool_element ::= '<tool' attributes? '>' tool_content '</tool>'
|
||||||
|
tool_content ::= purpose_element usage_element parameter_element outcome_element
|
||||||
|
|
||||||
|
(* 四大核心组件 *)
|
||||||
|
purpose_element ::= '<purpose' attributes? '>' purpose_content '</purpose>'
|
||||||
|
usage_element ::= '<usage' attributes? '>' usage_content '</usage>'
|
||||||
|
parameter_element ::= '<parameter' attributes? '>' parameter_content '</parameter>'
|
||||||
|
outcome_element ::= '<outcome' attributes? '>' outcome_content '</outcome>'
|
||||||
|
|
||||||
|
(* 内容定义 *)
|
||||||
|
purpose_content ::= markdown_content
|
||||||
|
usage_content ::= markdown_content
|
||||||
|
parameter_content ::= markdown_content
|
||||||
|
outcome_content ::= markdown_content
|
||||||
|
|
||||||
|
attributes ::= (' ' attribute)+ | ''
|
||||||
|
attribute ::= name '="' value '"'
|
||||||
|
name ::= [a-zA-Z][a-zA-Z0-9_-]*
|
||||||
|
value ::= [^"]*
|
||||||
|
|
||||||
|
markdown_content ::= (* 符合Markdown语法的内容 *)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🧩 语义说明
|
||||||
|
|
||||||
|
`<tool>`标签是DPML中定义#AI工具 的核心#工具提示单元,基于四组件架构构建完整的#AI工具定义。每个#工具 都是自包含的,包含了AI正确使用特定工具所需的全部指导信息。
|
||||||
|
|
||||||
|
### 四组件架构说明
|
||||||
|
|
||||||
|
#### 1. #用途说明(Purpose)
|
||||||
|
- **核心功能**:明确工具解决什么问题,适用什么场景
|
||||||
|
- **内容范围**:问题定义、解决方案、应用领域、核心价值
|
||||||
|
- **设计目标**:让AI清楚知道什么时候应该使用这个工具
|
||||||
|
- **关键要素**:问题描述、价值主张、应用边界
|
||||||
|
|
||||||
|
#### 2. #使用方法(Usage)
|
||||||
|
- **核心功能**:详细说明如何正确使用工具
|
||||||
|
- **内容范围**:操作步骤、使用流程、注意事项、最佳实践
|
||||||
|
- **设计目标**:确保AI能够按照正确的方式使用工具
|
||||||
|
- **关键要素**:步骤说明、时机判断、风险提示、优化建议
|
||||||
|
|
||||||
|
#### 3. #参数定义(Parameter)
|
||||||
|
- **核心功能**:明确工具需要什么输入信息
|
||||||
|
- **内容范围**:必需参数、可选参数、参数格式、默认值、验证规则
|
||||||
|
- **设计目标**:确保AI能够提供正确的工具调用参数
|
||||||
|
- **关键要素**:参数列表、类型定义、示例值、约束条件
|
||||||
|
|
||||||
|
#### 4. #预期结果(Outcome)
|
||||||
|
- **核心功能**:描述工具执行后的预期输出和效果
|
||||||
|
- **内容范围**:返回格式、成功标准、错误处理、结果解读
|
||||||
|
- **设计目标**:帮助AI理解和验证工具执行结果
|
||||||
|
- **关键要素**:输出格式、成功指标、异常情况、后续动作
|
||||||
|
|
||||||
|
### #工具生命周期
|
||||||
|
|
||||||
|
#### 工具使用流程
|
||||||
|
1. **识别需求** - AI判断当前任务是否需要使用工具
|
||||||
|
2. **选择工具** - 根据purpose确定合适的工具
|
||||||
|
3. **准备参数** - 按照parameter要求准备调用参数
|
||||||
|
4. **执行工具** - 通过`promptx_tool`执行具体工具
|
||||||
|
5. **处理结果** - 根据outcome验证和处理执行结果
|
||||||
|
|
||||||
|
#### 系统级支持
|
||||||
|
- **工具执行** - `promptx_tool`执行工具代码
|
||||||
|
- **错误处理** - 系统级异常捕获和处理
|
||||||
|
- **结果验证** - 自动验证工具执行结果
|
||||||
|
|
||||||
|
### 设计理念
|
||||||
|
|
||||||
|
#### 指导与执行分离
|
||||||
|
- 工具定义专注于使用指导,不包含具体代码实现
|
||||||
|
- 代码执行通过MCP工具系统实现
|
||||||
|
- 实现"指导-执行-验证"的完整闭环
|
||||||
|
|
||||||
|
#### 简化原则
|
||||||
|
- **四组件自包含** - 覆盖工具使用的全生命周期
|
||||||
|
- **系统级执行** - 复杂的代码执行通过MCP系统实现
|
||||||
|
- **清晰分离** - 工具定义与系统功能明确分工
|
||||||
|
|
||||||
|
> **注意**:基于指导与执行分离的设计原则,工具文件专注于使用指导,具体的代码实现和执行通过`promptx_tool` MCP工具完成。
|
||||||
@ -0,0 +1,319 @@
|
|||||||
|
<execution>
|
||||||
|
|
||||||
|
<constraint>
|
||||||
|
## 技术架构约束
|
||||||
|
- **单文件工具**:每个工具必须是独立的.tool.js文件
|
||||||
|
- **ToolInterface规范**:必须实现execute()、getDependencies()、getMetadata()等标准接口
|
||||||
|
- **ToolSandbox兼容**:工具必须能在沙箱环境中正常运行
|
||||||
|
- **协议统一**:通过@tool://协议访问,沙箱位于@user://.promptx/toolbox/
|
||||||
|
- **依赖隔离**:每个工具的依赖安装在独立的沙箱目录中
|
||||||
|
</constraint>
|
||||||
|
|
||||||
|
<rule>
|
||||||
|
## 开发强制规则
|
||||||
|
- **接口完整性**:必须实现所有必要的接口方法
|
||||||
|
- **依赖声明**:所有外部依赖必须在getDependencies()中明确声明
|
||||||
|
- **参数验证**:必须实现validate()方法验证输入参数
|
||||||
|
- **错误处理**:必须有完善的异常处理机制
|
||||||
|
- **安全第一**:禁止执行危险操作,确保沙箱安全
|
||||||
|
</rule>
|
||||||
|
|
||||||
|
<guideline>
|
||||||
|
## 开发指导原则
|
||||||
|
- **用户体验优先**:接口设计简洁直观
|
||||||
|
- **性能效率**:优化执行速度和资源使用
|
||||||
|
- **可维护性**:代码结构清晰,注释完整
|
||||||
|
- **渐进式功能**:先实现核心功能,再扩展高级特性
|
||||||
|
- **测试驱动**:每个功能都要有相应的测试验证
|
||||||
|
</guideline>
|
||||||
|
|
||||||
|
<process>
|
||||||
|
## 🛠️ 标准工具开发流程
|
||||||
|
|
||||||
|
### Phase 1: 需求分析与设计 (15分钟)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[用户需求] --> B[功能分析]
|
||||||
|
B --> C[依赖调研]
|
||||||
|
C --> D[接口设计]
|
||||||
|
D --> E[原型验证]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 1.1: 深度需求分析**
|
||||||
|
- 理解用户真实痛点
|
||||||
|
- 分析现有解决方案的不足
|
||||||
|
- 确定工具的核心价值主张
|
||||||
|
- 明确功能边界和使用场景
|
||||||
|
|
||||||
|
**Step 1.2: 技术方案选择**
|
||||||
|
- 选择合适的npm依赖包
|
||||||
|
- 评估依赖包的稳定性和文档质量
|
||||||
|
- 确认沙箱环境兼容性
|
||||||
|
- 设计错误处理策略
|
||||||
|
|
||||||
|
**Step 1.3: 接口规范设计**
|
||||||
|
```javascript
|
||||||
|
// 标准工具接口模板
|
||||||
|
module.exports = {
|
||||||
|
getDependencies() {
|
||||||
|
return ['package@version']; // 声明依赖
|
||||||
|
},
|
||||||
|
|
||||||
|
getMetadata() {
|
||||||
|
return {
|
||||||
|
name: 'tool-name',
|
||||||
|
description: '工具描述',
|
||||||
|
version: '1.0.0',
|
||||||
|
category: '分类'
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
getSchema() {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: { /* JSON Schema */ }
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
validate(params) {
|
||||||
|
// 参数验证逻辑
|
||||||
|
},
|
||||||
|
|
||||||
|
async execute(params) {
|
||||||
|
// 核心执行逻辑
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: 核心实现 (30分钟)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A[创建工具文件] --> B[实现接口方法]
|
||||||
|
B --> C[依赖管理]
|
||||||
|
C --> D[核心逻辑]
|
||||||
|
D --> E[错误处理]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2.1: 工具文件创建**
|
||||||
|
```bash
|
||||||
|
# 标准文件路径
|
||||||
|
.promptx/resource/tool/{tool-name}/{tool-name}.tool.js
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2.2: 依赖管理实现**
|
||||||
|
```javascript
|
||||||
|
getDependencies() {
|
||||||
|
return [
|
||||||
|
'lodash@^4.17.21', // 工具函数库
|
||||||
|
'axios@^1.6.0', // HTTP请求
|
||||||
|
'validator@^13.11.0' // 数据验证
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2.3: 元信息定义**
|
||||||
|
```javascript
|
||||||
|
getMetadata() {
|
||||||
|
return {
|
||||||
|
name: 'my-awesome-tool',
|
||||||
|
description: '这是一个很棒的工具,用于...',
|
||||||
|
version: '1.0.0',
|
||||||
|
category: 'utility',
|
||||||
|
author: '鲁班',
|
||||||
|
tags: ['tool', 'automation', 'utility']
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2.4: Schema定义**
|
||||||
|
```javascript
|
||||||
|
getSchema() {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
input: {
|
||||||
|
type: 'string',
|
||||||
|
description: '输入参数描述'
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
format: { type: 'string', default: 'json' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
required: ['input']
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3: 沙箱测试 (15分钟)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[ToolSandbox创建] --> B[依赖安装]
|
||||||
|
B --> C[功能测试]
|
||||||
|
C --> D[边界测试]
|
||||||
|
D --> E[性能测试]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3.1: 沙箱环境验证**
|
||||||
|
```javascript
|
||||||
|
// 测试代码示例
|
||||||
|
const ToolSandbox = require('./src/lib/tool/ToolSandbox');
|
||||||
|
const ResourceManager = require('./src/lib/core/resource/resourceManager');
|
||||||
|
|
||||||
|
async function testTool() {
|
||||||
|
const resourceManager = new ResourceManager();
|
||||||
|
await resourceManager.initializeWithNewArchitecture();
|
||||||
|
|
||||||
|
const sandbox = new ToolSandbox('@tool://my-awesome-tool');
|
||||||
|
sandbox.setResourceManager(resourceManager);
|
||||||
|
|
||||||
|
// 分析工具
|
||||||
|
await sandbox.analyze();
|
||||||
|
|
||||||
|
// 准备依赖
|
||||||
|
await sandbox.prepareDependencies();
|
||||||
|
|
||||||
|
// 测试执行
|
||||||
|
const result = await sandbox.execute({
|
||||||
|
input: 'test data',
|
||||||
|
options: { format: 'json' }
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('测试结果:', result);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3.2: 完整功能测试矩阵**
|
||||||
|
- ✅ 正常参数测试
|
||||||
|
- ✅ 边界值测试
|
||||||
|
- ✅ 异常参数测试
|
||||||
|
- ✅ 依赖缺失测试
|
||||||
|
- ✅ 性能压力测试
|
||||||
|
|
||||||
|
### Phase 4: 优化与发布 (10分钟)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A[代码优化] --> B[文档完善]
|
||||||
|
B --> C[注册表更新]
|
||||||
|
C --> D[用户验收]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 4.1: 代码质量优化**
|
||||||
|
- 重构冗余代码
|
||||||
|
- 优化性能瓶颈
|
||||||
|
- 完善错误信息
|
||||||
|
- 添加调试日志
|
||||||
|
|
||||||
|
**Step 4.2: 注册表集成**
|
||||||
|
```bash
|
||||||
|
# 重新生成注册表,确保工具被发现
|
||||||
|
node scripts/generate-package-registry.js
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 4.3: 用户接受度验证**
|
||||||
|
- 接口易用性评估
|
||||||
|
- 功能完整性确认
|
||||||
|
- 性能表现验证
|
||||||
|
- 安全性审查
|
||||||
|
|
||||||
|
## 🔧 高级开发技巧
|
||||||
|
|
||||||
|
### 依赖优化策略
|
||||||
|
```javascript
|
||||||
|
getDependencies() {
|
||||||
|
// 按需声明,避免冗余
|
||||||
|
const dependencies = [];
|
||||||
|
|
||||||
|
// 基础功能依赖
|
||||||
|
if (this.needsUtilities()) {
|
||||||
|
dependencies.push('lodash@^4.17.21');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网络功能依赖
|
||||||
|
if (this.needsHttp()) {
|
||||||
|
dependencies.push('axios@^1.6.0');
|
||||||
|
}
|
||||||
|
|
||||||
|
return dependencies;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 智能错误处理
|
||||||
|
```javascript
|
||||||
|
async execute(params) {
|
||||||
|
try {
|
||||||
|
// 核心逻辑
|
||||||
|
return await this.processData(params);
|
||||||
|
} catch (error) {
|
||||||
|
// 分类错误处理
|
||||||
|
if (error.code === 'NETWORK_ERROR') {
|
||||||
|
throw new Error('网络连接失败,请检查网络设置');
|
||||||
|
} else if (error.code === 'VALIDATION_ERROR') {
|
||||||
|
throw new Error(`参数验证失败: ${error.message}`);
|
||||||
|
} else {
|
||||||
|
throw new Error(`工具执行失败: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 性能优化模式
|
||||||
|
```javascript
|
||||||
|
async execute(params) {
|
||||||
|
// 缓存机制
|
||||||
|
const cacheKey = this.generateCacheKey(params);
|
||||||
|
if (this.cache.has(cacheKey)) {
|
||||||
|
return this.cache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行逻辑
|
||||||
|
const result = await this.processData(params);
|
||||||
|
|
||||||
|
// 缓存结果
|
||||||
|
this.cache.set(cacheKey, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</process>
|
||||||
|
|
||||||
|
<criteria>
|
||||||
|
## 工具质量评价标准
|
||||||
|
|
||||||
|
### 功能完整性 (25分)
|
||||||
|
- ✅ 核心功能完全实现
|
||||||
|
- ✅ 边界情况正确处理
|
||||||
|
- ✅ 错误场景优雅降级
|
||||||
|
- ✅ 用户需求完全满足
|
||||||
|
|
||||||
|
### 技术规范性 (25分)
|
||||||
|
- ✅ ToolInterface完全符合
|
||||||
|
- ✅ 依赖声明准确完整
|
||||||
|
- ✅ Schema定义标准规范
|
||||||
|
- ✅ 代码结构清晰可维护
|
||||||
|
|
||||||
|
### 沙箱兼容性 (25分)
|
||||||
|
- ✅ ToolSandbox正常运行
|
||||||
|
- ✅ 依赖自动安装成功
|
||||||
|
- ✅ 资源隔离正确工作
|
||||||
|
- ✅ 协议访问正常响应
|
||||||
|
|
||||||
|
### 用户体验质量 (25分)
|
||||||
|
- ✅ 接口简洁易用
|
||||||
|
- ✅ 错误信息友好
|
||||||
|
- ✅ 性能表现优秀
|
||||||
|
- ✅ 文档描述准确
|
||||||
|
|
||||||
|
### 卓越标准 (附加分)
|
||||||
|
- 🌟 创新功能设计
|
||||||
|
- 🌟 极致性能优化
|
||||||
|
- 🌟 出色的错误处理
|
||||||
|
- 🌟 完美的用户体验
|
||||||
|
</criteria>
|
||||||
|
|
||||||
|
</execution>
|
||||||
250
resource/role/luban/execution/toolsandbox-mastery.execution.md
Normal file
250
resource/role/luban/execution/toolsandbox-mastery.execution.md
Normal file
@ -0,0 +1,250 @@
|
|||||||
|
# ToolSandbox系统精通
|
||||||
|
|
||||||
|
<execution>
|
||||||
|
|
||||||
|
<constraint>
|
||||||
|
## ToolSandbox技术约束
|
||||||
|
- **协议固定**:@tool://和@user://协议不可更改
|
||||||
|
- **沙箱隔离**:每个工具运行在独立的沙箱环境中
|
||||||
|
- **依赖管理**:通过内置pnpm自动管理依赖
|
||||||
|
- **VM限制**:受Node.js VM模块功能限制
|
||||||
|
- **路径规范**:沙箱位置固定在@user://.promptx/toolbox/{toolId}
|
||||||
|
</constraint>
|
||||||
|
|
||||||
|
<rule>
|
||||||
|
## ToolSandbox使用规则
|
||||||
|
- **三阶段必须**:analyze → prepareDependencies → execute顺序执行
|
||||||
|
- **依赖声明强制**:getDependencies()返回的依赖必须准确
|
||||||
|
- **错误处理必须**:每个阶段都要有完善的错误处理
|
||||||
|
- **资源清理**:使用完毕后必须调用cleanup()
|
||||||
|
- **状态检查**:执行前必须检查isPrepared状态
|
||||||
|
</rule>
|
||||||
|
|
||||||
|
<guideline>
|
||||||
|
## ToolSandbox最佳实践
|
||||||
|
- **资源复用**:同一工具的沙箱可跨项目复用
|
||||||
|
- **缓存策略**:合理利用沙箱缓存提升性能
|
||||||
|
- **监控调试**:关注沙箱执行日志和性能指标
|
||||||
|
- **版本管理**:注意依赖版本一致性
|
||||||
|
- **安全优先**:避免在工具中执行危险操作
|
||||||
|
</guideline>
|
||||||
|
|
||||||
|
<process>
|
||||||
|
## 🏗️ ToolSandbox完整掌握流程
|
||||||
|
|
||||||
|
### 架构理解阶段
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[@tool://protocol] --> B[ResourceManager]
|
||||||
|
B --> C[ToolSandbox]
|
||||||
|
C --> D[@user://.promptx/toolbox]
|
||||||
|
D --> E[pnpm dependencies]
|
||||||
|
E --> F[VM execution]
|
||||||
|
```
|
||||||
|
|
||||||
|
**ToolSandbox核心组件**:
|
||||||
|
- **ResourceManager**:资源发现和协议解析
|
||||||
|
- **ToolSandbox**:沙箱环境管理
|
||||||
|
- **UserProtocol**:用户目录协议处理
|
||||||
|
- **内置pnpm**:依赖包管理
|
||||||
|
- **VM沙箱**:安全执行环境
|
||||||
|
|
||||||
|
### 工作流程精通
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[new ToolSandbox] --> B[setResourceManager]
|
||||||
|
B --> C[analyze阶段]
|
||||||
|
C --> D[prepareDependencies阶段]
|
||||||
|
D --> E[execute阶段]
|
||||||
|
E --> F[cleanup清理]
|
||||||
|
|
||||||
|
C --> C1[加载工具内容]
|
||||||
|
C --> C2[提取依赖列表]
|
||||||
|
C --> C3[解析沙箱路径]
|
||||||
|
|
||||||
|
D --> D1[创建沙箱目录]
|
||||||
|
D --> D2[生成package.json]
|
||||||
|
D --> D3[pnpm install]
|
||||||
|
D --> D4[创建智能沙箱]
|
||||||
|
|
||||||
|
E --> E1[参数验证]
|
||||||
|
E --> E2[VM执行]
|
||||||
|
E --> E3[结果返回]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Phase 1: 分析阶段精通**
|
||||||
|
```javascript
|
||||||
|
// ToolSandbox.analyze()内部流程
|
||||||
|
const analysisResult = await sandbox.analyze();
|
||||||
|
// 返回结果包含:
|
||||||
|
{
|
||||||
|
toolId: 'text-analyzer',
|
||||||
|
dependencies: ['lodash@^4.17.21'],
|
||||||
|
sandboxPath: '/Users/sean/.promptx/toolbox/text-analyzer',
|
||||||
|
hasMetadata: true,
|
||||||
|
hasSchema: true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Phase 2: 依赖准备精通**
|
||||||
|
```javascript
|
||||||
|
// ToolSandbox.prepareDependencies()内部流程
|
||||||
|
const prepResult = await sandbox.prepareDependencies();
|
||||||
|
|
||||||
|
// 内部执行步骤:
|
||||||
|
// 1. ensureSandboxDirectory() - 创建沙箱目录
|
||||||
|
// 2. createPackageJson() - 生成package.json
|
||||||
|
// 3. runPnpmInstall() - 执行pnpm install
|
||||||
|
// 4. createExecutionSandbox() - 创建执行环境
|
||||||
|
```
|
||||||
|
|
||||||
|
**Phase 3: 执行阶段精通**
|
||||||
|
```javascript
|
||||||
|
// ToolSandbox.execute()内部流程
|
||||||
|
const result = await sandbox.execute(parameters);
|
||||||
|
|
||||||
|
// 执行环境特性:
|
||||||
|
// - 智能require:优先从沙箱node_modules加载
|
||||||
|
// - 参数验证:自动调用工具的validate()方法
|
||||||
|
// - 错误隔离:沙箱异常不影响主进程
|
||||||
|
// - 结果标准化:统一的成功/失败格式
|
||||||
|
```
|
||||||
|
|
||||||
|
### 沙箱环境深度理解
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
A[工具代码] --> B[基础沙箱]
|
||||||
|
B --> C{有依赖?}
|
||||||
|
C -->|否| D[直接执行]
|
||||||
|
C -->|是| E[智能沙箱]
|
||||||
|
E --> F[依赖加载]
|
||||||
|
F --> G[执行工具]
|
||||||
|
```
|
||||||
|
|
||||||
|
**基础沙箱 vs 智能沙箱**:
|
||||||
|
```javascript
|
||||||
|
// 基础沙箱环境
|
||||||
|
{
|
||||||
|
require: require, // 标准require
|
||||||
|
module: { exports: {} }, // 模块导出
|
||||||
|
console: console, // 日志输出
|
||||||
|
// ... 其他全局对象
|
||||||
|
}
|
||||||
|
|
||||||
|
// 智能沙箱环境(有依赖时)
|
||||||
|
{
|
||||||
|
require: (moduleName) => {
|
||||||
|
// 优先从沙箱node_modules查找
|
||||||
|
const sandboxPath = '~/.promptx/toolbox/tool-id/node_modules';
|
||||||
|
return require.resolve(moduleName, { paths: [sandboxPath] });
|
||||||
|
},
|
||||||
|
// ... 其他环境
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 协议系统集成精通
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A[用户调用] --> B[@tool://text-analyzer]
|
||||||
|
B --> C[ResourceManager.loadResource]
|
||||||
|
C --> D[ToolProtocol.resolve]
|
||||||
|
D --> E[项目注册表查找]
|
||||||
|
E --> F[返回工具内容]
|
||||||
|
F --> G[ToolSandbox处理]
|
||||||
|
```
|
||||||
|
|
||||||
|
**协议解析流程**:
|
||||||
|
1. `@tool://text-analyzer` → `{ protocol: 'tool', path: 'text-analyzer' }`
|
||||||
|
2. ResourceManager查找注册表中ID为`text-analyzer`的tool资源
|
||||||
|
3. 找到资源引用:`@project://.promptx/resource/tool/text-analyzer/text-analyzer.tool.js`
|
||||||
|
4. 加载工具文件内容
|
||||||
|
5. 传递给ToolSandbox处理
|
||||||
|
|
||||||
|
### 故障诊断与优化
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[工具执行失败] --> B{失败阶段}
|
||||||
|
B -->|analyze| C[检查工具文件<br/>检查资源注册]
|
||||||
|
B -->|prepare| D[检查依赖声明<br/>检查pnpm状态]
|
||||||
|
B -->|execute| E[检查参数格式<br/>检查代码逻辑]
|
||||||
|
|
||||||
|
C --> F[解决方案]
|
||||||
|
D --> F
|
||||||
|
E --> F
|
||||||
|
```
|
||||||
|
|
||||||
|
**常见问题诊断**:
|
||||||
|
- **工具未发现**:检查注册表是否包含工具
|
||||||
|
- **依赖安装失败**:检查网络连接和依赖版本
|
||||||
|
- **执行报错**:检查参数验证和代码逻辑
|
||||||
|
- **性能问题**:检查依赖大小和执行复杂度
|
||||||
|
|
||||||
|
### 高级优化技巧
|
||||||
|
|
||||||
|
**沙箱缓存策略**:
|
||||||
|
```javascript
|
||||||
|
// 检查沙箱是否已存在
|
||||||
|
const sandboxExists = fs.existsSync(analysisResult.sandboxPath);
|
||||||
|
if (sandboxExists && !options.forceReinstall) {
|
||||||
|
// 跳过依赖安装,直接使用缓存
|
||||||
|
console.log('使用缓存的沙箱环境');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**批量工具管理**:
|
||||||
|
```javascript
|
||||||
|
// 并行处理多个工具
|
||||||
|
const sandboxes = tools.map(tool => new ToolSandbox(tool));
|
||||||
|
await Promise.all(sandboxes.map(s => s.analyze()));
|
||||||
|
await Promise.all(sandboxes.map(s => s.prepareDependencies()));
|
||||||
|
```
|
||||||
|
|
||||||
|
**性能监控**:
|
||||||
|
```javascript
|
||||||
|
const startTime = Date.now();
|
||||||
|
const result = await sandbox.execute(params);
|
||||||
|
const executionTime = Date.now() - startTime;
|
||||||
|
console.log(`工具执行耗时: ${executionTime}ms`);
|
||||||
|
```
|
||||||
|
</process>
|
||||||
|
|
||||||
|
<criteria>
|
||||||
|
## ToolSandbox精通评价标准
|
||||||
|
|
||||||
|
### 理论知识掌握 (25分)
|
||||||
|
- ✅ 完全理解三阶段执行流程
|
||||||
|
- ✅ 清楚沙箱隔离机制原理
|
||||||
|
- ✅ 掌握协议系统集成方式
|
||||||
|
- ✅ 理解依赖管理自动化机制
|
||||||
|
|
||||||
|
### 实践操作能力 (25分)
|
||||||
|
- ✅ 能独立创建和管理沙箱
|
||||||
|
- ✅ 能诊断和解决常见问题
|
||||||
|
- ✅ 能优化沙箱性能表现
|
||||||
|
- ✅ 能集成到工具开发流程
|
||||||
|
|
||||||
|
### 故障处理能力 (25分)
|
||||||
|
- ✅ 快速定位问题根因
|
||||||
|
- ✅ 提供有效解决方案
|
||||||
|
- ✅ 预防潜在风险
|
||||||
|
- ✅ 优化用户体验
|
||||||
|
|
||||||
|
### 创新应用能力 (25分)
|
||||||
|
- ✅ 探索高级使用模式
|
||||||
|
- ✅ 开发自动化工具
|
||||||
|
- ✅ 提出改进建议
|
||||||
|
- ✅ 分享最佳实践
|
||||||
|
|
||||||
|
### 专家级表现 (附加分)
|
||||||
|
- 🌟 深度定制沙箱环境
|
||||||
|
- 🌟 创新的性能优化方案
|
||||||
|
- 🌟 完美的问题预防机制
|
||||||
|
- 🌟 卓越的用户体验设计
|
||||||
|
</criteria>
|
||||||
|
|
||||||
|
</execution>
|
||||||
264
resource/role/luban/knowledge/dpml-tool-tagging.knowledge.md
Normal file
264
resource/role/luban/knowledge/dpml-tool-tagging.knowledge.md
Normal file
@ -0,0 +1,264 @@
|
|||||||
|
# DPML工具标签体系精通
|
||||||
|
|
||||||
|
<knowledge>
|
||||||
|
|
||||||
|
## 🏷️ DPML工具标签框架深度理解
|
||||||
|
|
||||||
|
### 四组件架构精通
|
||||||
|
DPML#工具提示单元 基于四组件架构构建完整的AI工具定义:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<tool>
|
||||||
|
<purpose>用途说明 - 明确工具解决什么问题</purpose>
|
||||||
|
<usage>使用方法 - 详细说明如何正确使用</usage>
|
||||||
|
<parameter>参数定义 - 明确工具需要什么输入</parameter>
|
||||||
|
<outcome>预期结果 - 描述工具执行后的预期输出</outcome>
|
||||||
|
</tool>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 指导与执行分离哲学
|
||||||
|
- **工具定义专注于使用指导**:不包含具体代码实现
|
||||||
|
- **代码执行通过MCP工具系统**:`promptx_tool`负责具体执行
|
||||||
|
- **实现完整闭环**:指导-执行-验证的完整流程
|
||||||
|
|
||||||
|
## 📝 标准工具标签编写模板
|
||||||
|
|
||||||
|
### Purpose组件编写精要
|
||||||
|
```xml
|
||||||
|
<purpose>
|
||||||
|
## 核心问题定义
|
||||||
|
明确描述工具要解决的具体问题和适用场景
|
||||||
|
|
||||||
|
## 价值主张
|
||||||
|
- 🎯 **解决什么痛点**:具体描述用户痛点
|
||||||
|
- 🚀 **带来什么价值**:明确量化收益
|
||||||
|
- 🌟 **独特优势**:相比其他解决方案的优势
|
||||||
|
|
||||||
|
## 应用边界
|
||||||
|
- ✅ **适用场景**:详细列出适用情况
|
||||||
|
- ❌ **不适用场景**:明确使用边界
|
||||||
|
</purpose>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usage组件编写精要
|
||||||
|
```xml
|
||||||
|
<usage>
|
||||||
|
## 使用时机
|
||||||
|
- 在什么情况下应该使用这个工具
|
||||||
|
- 如何判断是否需要使用
|
||||||
|
|
||||||
|
## 操作步骤
|
||||||
|
1. **准备阶段**:需要提前准备什么
|
||||||
|
2. **执行阶段**:具体操作流程
|
||||||
|
3. **验证阶段**:如何验证结果
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
- 🎯 **效率提升技巧**
|
||||||
|
- ⚠️ **常见陷阱避免**
|
||||||
|
- 🔧 **故障排除指南**
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
- 安全性考虑
|
||||||
|
- 性能优化建议
|
||||||
|
- 兼容性要求
|
||||||
|
</usage>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parameter组件编写精要
|
||||||
|
```xml
|
||||||
|
<parameter>
|
||||||
|
## 必需参数
|
||||||
|
| 参数名 | 类型 | 描述 | 示例 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| input | string | 输入文本 | "Hello World" |
|
||||||
|
|
||||||
|
## 可选参数
|
||||||
|
| 参数名 | 类型 | 默认值 | 描述 |
|
||||||
|
|--------|------|--------|------|
|
||||||
|
| format | string | "json" | 输出格式 |
|
||||||
|
|
||||||
|
## 参数约束
|
||||||
|
- **长度限制**:input 不超过 10000 字符
|
||||||
|
- **格式要求**:必须是有效的 UTF-8 编码
|
||||||
|
- **安全限制**:不允许包含可执行代码
|
||||||
|
|
||||||
|
## 参数示例
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"input": "需要处理的文本内容",
|
||||||
|
"options": {
|
||||||
|
"format": "json",
|
||||||
|
"encoding": "utf-8"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</parameter>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Outcome组件编写精要
|
||||||
|
```xml
|
||||||
|
<outcome>
|
||||||
|
## 成功返回格式
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"result": "处理结果",
|
||||||
|
"metadata": {
|
||||||
|
"processingTime": 150,
|
||||||
|
"timestamp": "2024-01-01T12:00:00Z"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 错误处理格式
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"error": {
|
||||||
|
"code": "VALIDATION_ERROR",
|
||||||
|
"message": "输入参数验证失败",
|
||||||
|
"details": "具体错误详情"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 结果解读指南
|
||||||
|
- **如何判断执行成功**:检查 success 字段
|
||||||
|
- **如何获取核心数据**:data.result 包含主要结果
|
||||||
|
- **如何处理错误**:根据 error.code 分类处理
|
||||||
|
- **如何优化下次使用**:根据 metadata 调优参数
|
||||||
|
|
||||||
|
## 后续动作建议
|
||||||
|
- 成功时的下一步操作
|
||||||
|
- 失败时的重试策略
|
||||||
|
- 结果的进一步处理方式
|
||||||
|
</outcome>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 工具标签质量标准
|
||||||
|
|
||||||
|
### Purpose质量检查
|
||||||
|
- ✅ 问题定义清晰具体
|
||||||
|
- ✅ 价值主张明确量化
|
||||||
|
- ✅ 应用边界明确划分
|
||||||
|
- ✅ 用户痛点精准描述
|
||||||
|
|
||||||
|
### Usage质量检查
|
||||||
|
- ✅ 使用时机判断明确
|
||||||
|
- ✅ 操作步骤完整可执行
|
||||||
|
- ✅ 最佳实践实用有效
|
||||||
|
- ✅ 注意事项全面详细
|
||||||
|
|
||||||
|
### Parameter质量检查
|
||||||
|
- ✅ 参数分类准确(必需/可选)
|
||||||
|
- ✅ 类型定义精确
|
||||||
|
- ✅ 约束条件明确
|
||||||
|
- ✅ 示例完整有效
|
||||||
|
|
||||||
|
### Outcome质量检查
|
||||||
|
- ✅ 返回格式标准化
|
||||||
|
- ✅ 错误处理完整
|
||||||
|
- ✅ 解读指南清晰
|
||||||
|
- ✅ 后续动作明确
|
||||||
|
|
||||||
|
## 🛠️ 工具标签与代码实现的映射关系
|
||||||
|
|
||||||
|
### 从Purpose到getMetadata()
|
||||||
|
```javascript
|
||||||
|
// Purpose中的核心问题 → getMetadata()中的description
|
||||||
|
getMetadata() {
|
||||||
|
return {
|
||||||
|
name: 'text-processor',
|
||||||
|
description: 'Purpose中定义的核心问题和价值主张',
|
||||||
|
category: 'Purpose中的应用领域'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 从Parameter到getSchema()
|
||||||
|
```javascript
|
||||||
|
// Parameter中的参数定义 → getSchema()中的JSON Schema
|
||||||
|
getSchema() {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
// Parameter表格中的每个参数
|
||||||
|
input: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'Parameter中的参数描述'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
required: ['input'] // Parameter中的必需参数
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 从Usage到validate()和execute()
|
||||||
|
```javascript
|
||||||
|
// Usage中的最佳实践 → validate()中的验证逻辑
|
||||||
|
validate(params) {
|
||||||
|
// Usage中提到的参数约束检查
|
||||||
|
// Usage中的安全性考虑
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage中的操作步骤 → execute()中的执行流程
|
||||||
|
async execute(params) {
|
||||||
|
// 1. 准备阶段的代码实现
|
||||||
|
// 2. 执行阶段的核心逻辑
|
||||||
|
// 3. 验证阶段的结果检查
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 从Outcome到返回值格式
|
||||||
|
```javascript
|
||||||
|
// Outcome中的返回格式 → execute()的返回值结构
|
||||||
|
return {
|
||||||
|
success: true, // Outcome中定义的成功标识
|
||||||
|
data: result, // Outcome中定义的数据格式
|
||||||
|
metadata: { // Outcome中定义的元数据
|
||||||
|
executionTime: Date.now() - startTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 标签驱动的开发流程
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[用户需求] --> B[编写Purpose]
|
||||||
|
B --> C[设计Usage]
|
||||||
|
C --> D[定义Parameter]
|
||||||
|
D --> E[规划Outcome]
|
||||||
|
E --> F[生成工具标签]
|
||||||
|
F --> G[映射到代码接口]
|
||||||
|
G --> H[实现具体逻辑]
|
||||||
|
H --> I[测试验证]
|
||||||
|
I --> J[完整工具交付]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 开发质量保证
|
||||||
|
1. **标签先行**:先完成工具标签定义,再编写代码
|
||||||
|
2. **映射验证**:确保代码实现与标签定义一致
|
||||||
|
3. **用户测试**:基于标签进行用户验收测试
|
||||||
|
4. **文档同步**:保持标签和代码的同步更新
|
||||||
|
|
||||||
|
## 🌟 卓越工具标签特征
|
||||||
|
|
||||||
|
### 用户友好性
|
||||||
|
- 语言通俗易懂,避免技术术语
|
||||||
|
- 结构清晰,信息层次分明
|
||||||
|
- 示例丰富,便于理解和使用
|
||||||
|
|
||||||
|
### 技术准确性
|
||||||
|
- 参数定义精确,类型明确
|
||||||
|
- 约束条件完整,边界清晰
|
||||||
|
- 返回格式标准,错误处理完善
|
||||||
|
|
||||||
|
### 实用可操作性
|
||||||
|
- 步骤详细具体,可直接执行
|
||||||
|
- 最佳实践实用,经过验证
|
||||||
|
- 故障排除全面,覆盖常见问题
|
||||||
|
|
||||||
|
</knowledge>
|
||||||
549
resource/role/luban/knowledge/javascript-ecosystem.knowledge.md
Normal file
549
resource/role/luban/knowledge/javascript-ecosystem.knowledge.md
Normal file
@ -0,0 +1,549 @@
|
|||||||
|
# JavaScript生态系统精通
|
||||||
|
|
||||||
|
<knowledge>
|
||||||
|
|
||||||
|
## 🚀 现代JavaScript精通
|
||||||
|
|
||||||
|
### ES6+核心特性
|
||||||
|
```javascript
|
||||||
|
// 解构赋值与默认参数
|
||||||
|
function createTool({ name, version = '1.0.0', dependencies = [] }) {
|
||||||
|
return { name, version, dependencies };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 箭头函数与Promise
|
||||||
|
const processAsync = async (data) => {
|
||||||
|
const results = await Promise.all(
|
||||||
|
data.map(item => processItem(item))
|
||||||
|
);
|
||||||
|
return results.filter(Boolean);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 模板字符串与标签函数
|
||||||
|
function sqlQuery(strings, ...values) {
|
||||||
|
return strings.reduce((query, string, i) => {
|
||||||
|
const value = values[i] ? sanitize(values[i]) : '';
|
||||||
|
return query + string + value;
|
||||||
|
}, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 类与继承
|
||||||
|
class ToolBase {
|
||||||
|
constructor(name) {
|
||||||
|
this.name = name;
|
||||||
|
this.startTime = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute(params) {
|
||||||
|
throw new Error('子类必须实现execute方法');
|
||||||
|
}
|
||||||
|
|
||||||
|
getExecutionTime() {
|
||||||
|
return Date.now() - this.startTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Symbol与迭代器
|
||||||
|
const PRIVATE_KEY = Symbol('private');
|
||||||
|
class Tool {
|
||||||
|
constructor() {
|
||||||
|
this[PRIVATE_KEY] = { cache: new Map() };
|
||||||
|
}
|
||||||
|
|
||||||
|
*[Symbol.iterator]() {
|
||||||
|
yield* this.getResults();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 异步编程精通
|
||||||
|
```javascript
|
||||||
|
// Promise链式处理
|
||||||
|
function processChain(data) {
|
||||||
|
return Promise.resolve(data)
|
||||||
|
.then(validate)
|
||||||
|
.then(transform)
|
||||||
|
.then(save)
|
||||||
|
.catch(handleError)
|
||||||
|
.finally(cleanup);
|
||||||
|
}
|
||||||
|
|
||||||
|
// async/await错误处理
|
||||||
|
async function safeExecute(fn, ...args) {
|
||||||
|
try {
|
||||||
|
const result = await fn(...args);
|
||||||
|
return { success: true, data: result };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 并发控制
|
||||||
|
class ConcurrencyManager {
|
||||||
|
constructor(limit = 3) {
|
||||||
|
this.limit = limit;
|
||||||
|
this.running = 0;
|
||||||
|
this.queue = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute(fn) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
this.queue.push({ fn, resolve, reject });
|
||||||
|
this.process();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async process() {
|
||||||
|
if (this.running >= this.limit || this.queue.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.running++;
|
||||||
|
const { fn, resolve, reject } = this.queue.shift();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await fn();
|
||||||
|
resolve(result);
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
} finally {
|
||||||
|
this.running--;
|
||||||
|
this.process();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 超时控制
|
||||||
|
function withTimeout(promise, ms) {
|
||||||
|
const timeout = new Promise((_, reject) =>
|
||||||
|
setTimeout(() => reject(new Error('操作超时')), ms)
|
||||||
|
);
|
||||||
|
return Promise.race([promise, timeout]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📦 npm生态系统精通
|
||||||
|
|
||||||
|
### package.json深度配置
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "my-awesome-tool",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "一个很棒的工具",
|
||||||
|
"main": "index.js",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0",
|
||||||
|
"npm": ">=6.0.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"start": "node index.js",
|
||||||
|
"test": "jest",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"format": "prettier --write .",
|
||||||
|
"preinstall": "node scripts/check-env.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"axios": "^1.6.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"jest": "^29.0.0",
|
||||||
|
"eslint": "^8.0.0",
|
||||||
|
"prettier": "^2.8.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "^2.3.0"
|
||||||
|
},
|
||||||
|
"keywords": ["tool", "automation", "utility"],
|
||||||
|
"author": "鲁班 <luban@promptx.ai>",
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/promptx/awesome-tool.git"
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/promptx/awesome-tool/issues"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/promptx/awesome-tool#readme"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 版本管理策略
|
||||||
|
```javascript
|
||||||
|
// 语义化版本控制
|
||||||
|
const semver = require('semver');
|
||||||
|
|
||||||
|
function updateVersion(currentVersion, changeType) {
|
||||||
|
switch (changeType) {
|
||||||
|
case 'patch': // 1.0.0 -> 1.0.1 (bug fixes)
|
||||||
|
return semver.inc(currentVersion, 'patch');
|
||||||
|
case 'minor': // 1.0.0 -> 1.1.0 (new features)
|
||||||
|
return semver.inc(currentVersion, 'minor');
|
||||||
|
case 'major': // 1.0.0 -> 2.0.0 (breaking changes)
|
||||||
|
return semver.inc(currentVersion, 'major');
|
||||||
|
default:
|
||||||
|
throw new Error('无效的版本类型');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版本兼容性检查
|
||||||
|
function checkCompatibility(required, current) {
|
||||||
|
return semver.satisfies(current, required);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 依赖管理最佳实践
|
||||||
|
```javascript
|
||||||
|
// 依赖安全检查
|
||||||
|
const auditDependencies = async () => {
|
||||||
|
const { exec } = require('child_process');
|
||||||
|
const { promisify } = require('util');
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { stdout } = await execAsync('npm audit --json');
|
||||||
|
const auditResult = JSON.parse(stdout);
|
||||||
|
|
||||||
|
if (auditResult.vulnerabilities) {
|
||||||
|
console.warn('发现安全漏洞:', auditResult.vulnerabilities);
|
||||||
|
}
|
||||||
|
|
||||||
|
return auditResult;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('安全审计失败:', error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 依赖大小分析
|
||||||
|
const analyzeBundleSize = (packageName) => {
|
||||||
|
const bundlePhobia = require('bundle-phobia');
|
||||||
|
return bundlePhobia.getPackageStats(packageName);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 依赖树分析
|
||||||
|
const analyzeDependencyTree = () => {
|
||||||
|
const fs = require('fs');
|
||||||
|
const packageLock = JSON.parse(fs.readFileSync('package-lock.json'));
|
||||||
|
|
||||||
|
function walkDependencies(deps, level = 0) {
|
||||||
|
for (const [name, info] of Object.entries(deps)) {
|
||||||
|
console.log(' '.repeat(level) + `${name}@${info.version}`);
|
||||||
|
if (info.dependencies) {
|
||||||
|
walkDependencies(info.dependencies, level + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
walkDependencies(packageLock.dependencies);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔧 模块系统精通
|
||||||
|
|
||||||
|
### CommonJS深度应用
|
||||||
|
```javascript
|
||||||
|
// 模块导出模式
|
||||||
|
// 1. 单一导出
|
||||||
|
module.exports = class Tool {
|
||||||
|
execute() { /* ... */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. 多重导出
|
||||||
|
module.exports = {
|
||||||
|
Tool,
|
||||||
|
ToolManager,
|
||||||
|
createTool: (config) => new Tool(config)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. 动态导出
|
||||||
|
const tools = {};
|
||||||
|
const toolFiles = fs.readdirSync('./tools');
|
||||||
|
toolFiles.forEach(file => {
|
||||||
|
const name = path.basename(file, '.js');
|
||||||
|
tools[name] = require(`./tools/${file}`);
|
||||||
|
});
|
||||||
|
module.exports = tools;
|
||||||
|
|
||||||
|
// 4. 条件导出
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
module.exports.debug = require('./debug');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### require缓存机制
|
||||||
|
```javascript
|
||||||
|
// 缓存清理
|
||||||
|
function clearRequireCache(modulePath) {
|
||||||
|
const resolved = require.resolve(modulePath);
|
||||||
|
delete require.cache[resolved];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 热重载实现
|
||||||
|
class HotReloader {
|
||||||
|
constructor() {
|
||||||
|
this.watchers = new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(modulePath, callback) {
|
||||||
|
const watcher = fs.watch(modulePath, () => {
|
||||||
|
clearRequireCache(modulePath);
|
||||||
|
const newModule = require(modulePath);
|
||||||
|
callback(newModule);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.watchers.set(modulePath, watcher);
|
||||||
|
}
|
||||||
|
|
||||||
|
unwatch(modulePath) {
|
||||||
|
const watcher = this.watchers.get(modulePath);
|
||||||
|
if (watcher) {
|
||||||
|
watcher.close();
|
||||||
|
this.watchers.delete(modulePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模块路径解析
|
||||||
|
function resolveModule(moduleName, fromPath) {
|
||||||
|
const Module = require('module');
|
||||||
|
const originalResolveFilename = Module._resolveFilename;
|
||||||
|
|
||||||
|
return originalResolveFilename.call(Module, moduleName, {
|
||||||
|
id: fromPath,
|
||||||
|
filename: fromPath,
|
||||||
|
paths: Module._nodeModulePaths(path.dirname(fromPath))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ 开发工具精通
|
||||||
|
|
||||||
|
### ESLint配置优化
|
||||||
|
```javascript
|
||||||
|
// .eslintrc.js
|
||||||
|
module.exports = {
|
||||||
|
env: {
|
||||||
|
node: true,
|
||||||
|
es2021: true,
|
||||||
|
jest: true
|
||||||
|
},
|
||||||
|
extends: [
|
||||||
|
'eslint:recommended',
|
||||||
|
'plugin:security/recommended'
|
||||||
|
],
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module'
|
||||||
|
},
|
||||||
|
plugins: ['security'],
|
||||||
|
rules: {
|
||||||
|
'no-console': 'warn',
|
||||||
|
'no-unused-vars': 'error',
|
||||||
|
'prefer-const': 'error',
|
||||||
|
'no-var': 'error',
|
||||||
|
'security/detect-eval-with-expression': 'error',
|
||||||
|
'security/detect-non-literal-fs-filename': 'warn'
|
||||||
|
},
|
||||||
|
overrides: [
|
||||||
|
{
|
||||||
|
files: ['*.test.js', '*.spec.js'],
|
||||||
|
rules: {
|
||||||
|
'no-console': 'off'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Prettier格式化配置
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"semi": true,
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": false,
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"arrowParens": "avoid",
|
||||||
|
"endOfLine": "lf"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Jest测试框架
|
||||||
|
```javascript
|
||||||
|
// jest.config.js
|
||||||
|
module.exports = {
|
||||||
|
testEnvironment: 'node',
|
||||||
|
roots: ['<rootDir>/src', '<rootDir>/tests'],
|
||||||
|
testMatch: [
|
||||||
|
'**/__tests__/**/*.js',
|
||||||
|
'**/?(*.)+(spec|test).js'
|
||||||
|
],
|
||||||
|
collectCoverageFrom: [
|
||||||
|
'src/**/*.js',
|
||||||
|
'!src/**/*.test.js'
|
||||||
|
],
|
||||||
|
coverageDirectory: 'coverage',
|
||||||
|
coverageReporters: ['text', 'lcov', 'html'],
|
||||||
|
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
|
||||||
|
};
|
||||||
|
|
||||||
|
// 测试示例
|
||||||
|
describe('Tool', () => {
|
||||||
|
let tool;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tool = new Tool();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await tool.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should execute successfully', async () => {
|
||||||
|
const result = await tool.execute({ input: 'test' });
|
||||||
|
expect(result).toHaveProperty('success', true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should handle errors gracefully', async () => {
|
||||||
|
await expect(tool.execute({})).rejects.toThrow('Missing input');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should validate parameters', () => {
|
||||||
|
const validation = tool.validate({ input: 'valid' });
|
||||||
|
expect(validation.valid).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔒 安全编程实践
|
||||||
|
|
||||||
|
### 输入验证与清理
|
||||||
|
```javascript
|
||||||
|
const validator = require('validator');
|
||||||
|
|
||||||
|
class InputValidator {
|
||||||
|
static sanitizeString(input, maxLength = 1000) {
|
||||||
|
if (typeof input !== 'string') {
|
||||||
|
throw new Error('输入必须是字符串');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 长度限制
|
||||||
|
if (input.length > maxLength) {
|
||||||
|
throw new Error(`输入长度超过限制: ${maxLength}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// XSS防护
|
||||||
|
return validator.escape(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateEmail(email) {
|
||||||
|
if (!validator.isEmail(email)) {
|
||||||
|
throw new Error('无效的邮箱地址');
|
||||||
|
}
|
||||||
|
return validator.normalizeEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateURL(url) {
|
||||||
|
if (!validator.isURL(url)) {
|
||||||
|
throw new Error('无效的URL');
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
static sanitizeFilename(filename) {
|
||||||
|
// 移除危险字符
|
||||||
|
return filename.replace(/[^a-zA-Z0-9._-]/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 错误处理与日志
|
||||||
|
```javascript
|
||||||
|
class ToolLogger {
|
||||||
|
constructor(toolName) {
|
||||||
|
this.toolName = toolName;
|
||||||
|
this.startTime = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
info(message, data = {}) {
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
level: 'info',
|
||||||
|
tool: this.toolName,
|
||||||
|
message,
|
||||||
|
data,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
error(message, error = {}) {
|
||||||
|
console.error(JSON.stringify({
|
||||||
|
level: 'error',
|
||||||
|
tool: this.toolName,
|
||||||
|
message,
|
||||||
|
error: {
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack
|
||||||
|
},
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
performance(operation, duration) {
|
||||||
|
this.info(`Performance: ${operation}`, { duration });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 资源管理与限制
|
||||||
|
```javascript
|
||||||
|
class ResourceManager {
|
||||||
|
constructor(options = {}) {
|
||||||
|
this.maxMemory = options.maxMemory || 100 * 1024 * 1024; // 100MB
|
||||||
|
this.maxExecutionTime = options.maxExecutionTime || 30000; // 30s
|
||||||
|
this.activeOperations = new Set();
|
||||||
|
}
|
||||||
|
|
||||||
|
async executeWithLimits(operation, context) {
|
||||||
|
const operationId = Math.random().toString(36);
|
||||||
|
this.activeOperations.add(operationId);
|
||||||
|
|
||||||
|
const timeoutPromise = new Promise((_, reject) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
reject(new Error('操作超时'));
|
||||||
|
}, this.maxExecutionTime);
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 内存监控
|
||||||
|
const initialMemory = process.memoryUsage().heapUsed;
|
||||||
|
|
||||||
|
const result = await Promise.race([
|
||||||
|
operation(),
|
||||||
|
timeoutPromise
|
||||||
|
]);
|
||||||
|
|
||||||
|
const finalMemory = process.memoryUsage().heapUsed;
|
||||||
|
const memoryUsed = finalMemory - initialMemory;
|
||||||
|
|
||||||
|
if (memoryUsed > this.maxMemory) {
|
||||||
|
console.warn(`内存使用超限: ${memoryUsed / 1024 / 1024}MB`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
this.activeOperations.delete(operationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getActiveOperations() {
|
||||||
|
return this.activeOperations.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
</knowledge>
|
||||||
@ -0,0 +1,416 @@
|
|||||||
|
# PromptX工具架构知识体系
|
||||||
|
|
||||||
|
<knowledge>
|
||||||
|
|
||||||
|
## 🏗️ 核心架构组件
|
||||||
|
|
||||||
|
### ToolSandbox系统架构
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[Tool Request] --> B[ResourceManager]
|
||||||
|
B --> C[Protocol Resolution]
|
||||||
|
C --> D[ToolSandbox Creation]
|
||||||
|
D --> E[Dependency Management]
|
||||||
|
E --> F[VM Execution]
|
||||||
|
F --> G[Result Return]
|
||||||
|
|
||||||
|
subgraph "沙箱环境"
|
||||||
|
H[@user://.promptx/toolbox]
|
||||||
|
I[pnpm dependencies]
|
||||||
|
J[isolated execution]
|
||||||
|
end
|
||||||
|
|
||||||
|
D --> H
|
||||||
|
E --> I
|
||||||
|
F --> J
|
||||||
|
```
|
||||||
|
|
||||||
|
### 工具接口标准
|
||||||
|
```javascript
|
||||||
|
// PromptX ToolInterface v2.0
|
||||||
|
module.exports = {
|
||||||
|
// 🆕 新接口:依赖管理
|
||||||
|
getDependencies() {
|
||||||
|
return ['lodash@^4.17.21', 'axios@^1.6.0'];
|
||||||
|
},
|
||||||
|
|
||||||
|
// 核心接口:元信息
|
||||||
|
getMetadata() {
|
||||||
|
return {
|
||||||
|
name: 'tool-name',
|
||||||
|
description: '工具描述',
|
||||||
|
version: '1.0.0',
|
||||||
|
category: 'utility',
|
||||||
|
author: '作者',
|
||||||
|
tags: ['tag1', 'tag2']
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
// 核心接口:参数Schema
|
||||||
|
getSchema() {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
input: { type: 'string', description: '输入参数' }
|
||||||
|
},
|
||||||
|
required: ['input']
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
// 可选接口:参数验证
|
||||||
|
validate(params) {
|
||||||
|
return { valid: true, errors: [] };
|
||||||
|
},
|
||||||
|
|
||||||
|
// 核心接口:执行逻辑
|
||||||
|
async execute(params) {
|
||||||
|
// 工具核心逻辑
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 可选接口:初始化
|
||||||
|
async init() {
|
||||||
|
// 初始化逻辑
|
||||||
|
},
|
||||||
|
|
||||||
|
// 可选接口:清理
|
||||||
|
async cleanup() {
|
||||||
|
// 清理逻辑
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔧 技术栈知识
|
||||||
|
|
||||||
|
### Node.js生态精通
|
||||||
|
```javascript
|
||||||
|
// ES6+特性应用
|
||||||
|
const { promisify } = require('util');
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
|
||||||
|
// 异步编程模式
|
||||||
|
async function processData(data) {
|
||||||
|
try {
|
||||||
|
const result = await Promise.all(
|
||||||
|
data.map(item => processItem(item))
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Processing failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误处理最佳实践
|
||||||
|
class ToolError extends Error {
|
||||||
|
constructor(message, code, details) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'ToolError';
|
||||||
|
this.code = code;
|
||||||
|
this.details = details;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 依赖管理精通
|
||||||
|
```json
|
||||||
|
// package.json最佳实践
|
||||||
|
{
|
||||||
|
"name": "toolbox-text-analyzer",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Sandbox for tool: text-analyzer",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"axios": "^1.6.0",
|
||||||
|
"validator": "^13.11.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**依赖选择原则**:
|
||||||
|
- **成熟度**:选择下载量大、维护活跃的包
|
||||||
|
- **轻量化**:避免过重的依赖,注意bundle size
|
||||||
|
- **兼容性**:确保Node.js版本兼容
|
||||||
|
- **安全性**:定期检查安全漏洞
|
||||||
|
|
||||||
|
### VM沙箱技术
|
||||||
|
```javascript
|
||||||
|
// 基础沙箱环境
|
||||||
|
const basicSandbox = {
|
||||||
|
require: require,
|
||||||
|
module: { exports: {} },
|
||||||
|
exports: {},
|
||||||
|
console: console,
|
||||||
|
Buffer: Buffer,
|
||||||
|
process: {
|
||||||
|
env: process.env,
|
||||||
|
hrtime: process.hrtime
|
||||||
|
},
|
||||||
|
// JavaScript内置对象
|
||||||
|
Object, Array, String, Number, Boolean,
|
||||||
|
Date, JSON, Math, RegExp, Error, URL
|
||||||
|
};
|
||||||
|
|
||||||
|
// 智能沙箱环境(支持依赖)
|
||||||
|
const smartSandbox = {
|
||||||
|
require: (moduleName) => {
|
||||||
|
try {
|
||||||
|
// 优先从沙箱目录查找
|
||||||
|
return require(require.resolve(moduleName, {
|
||||||
|
paths: [
|
||||||
|
path.join(sandboxPath, 'node_modules'),
|
||||||
|
sandboxPath,
|
||||||
|
process.cwd() + '/node_modules'
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
return require(moduleName);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// ... 其他环境对象
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📚 工具库生态
|
||||||
|
|
||||||
|
### 常用工具库分类
|
||||||
|
|
||||||
|
**🔧 工具函数库**
|
||||||
|
- **lodash** `^4.17.21` - 全功能工具函数库
|
||||||
|
- **ramda** `^0.29.0` - 函数式编程工具
|
||||||
|
- **validator** `^13.11.0` - 数据验证工具
|
||||||
|
|
||||||
|
**🌐 网络请求库**
|
||||||
|
- **axios** `^1.6.0` - HTTP客户端库
|
||||||
|
- **node-fetch** `^3.3.0` - Fetch API实现
|
||||||
|
- **got** `^13.0.0` - 轻量HTTP请求库
|
||||||
|
|
||||||
|
**📄 文件处理库**
|
||||||
|
- **fs-extra** `^11.1.0` - 增强文件系统操作
|
||||||
|
- **glob** `^10.3.0` - 文件模式匹配
|
||||||
|
- **chokidar** `^3.5.0` - 文件监控
|
||||||
|
|
||||||
|
**📊 数据处理库**
|
||||||
|
- **moment** `^2.29.0` - 日期时间处理
|
||||||
|
- **mathjs** `^11.11.0` - 数学计算库
|
||||||
|
- **csv-parser** `^3.0.0` - CSV文件解析
|
||||||
|
|
||||||
|
**📧 服务集成库**
|
||||||
|
- **nodemailer** `^6.9.0` - 邮件发送
|
||||||
|
- **node-cron** `^3.0.0` - 定时任务
|
||||||
|
- **sharp** `^0.32.0` - 图像处理
|
||||||
|
|
||||||
|
### 库选择决策树
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[需要功能] --> B{功能类型}
|
||||||
|
B -->|数据处理| C[lodash/ramda]
|
||||||
|
B -->|网络请求| D[axios/node-fetch]
|
||||||
|
B -->|文件操作| E[fs-extra/glob]
|
||||||
|
B -->|数据验证| F[validator/joi]
|
||||||
|
B -->|日期时间| G[moment/dayjs]
|
||||||
|
B -->|数学计算| H[mathjs]
|
||||||
|
B -->|邮件服务| I[nodemailer]
|
||||||
|
B -->|图像处理| J[sharp/jimp]
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛡️ 安全与最佳实践
|
||||||
|
|
||||||
|
### 安全编程原则
|
||||||
|
```javascript
|
||||||
|
// 输入验证
|
||||||
|
function validateInput(input) {
|
||||||
|
if (typeof input !== 'string') {
|
||||||
|
throw new Error('输入必须是字符串');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.length > 10000) {
|
||||||
|
throw new Error('输入内容过长');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 防止代码注入
|
||||||
|
if (/[<>'"&]/.test(input)) {
|
||||||
|
throw new Error('输入包含危险字符');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误信息安全
|
||||||
|
function safeErrorMessage(error) {
|
||||||
|
// 不暴露敏感信息
|
||||||
|
const safeMessage = error.message.replace(
|
||||||
|
/\/Users\/[^\/]+/g, '~/***'
|
||||||
|
);
|
||||||
|
return safeMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资源限制
|
||||||
|
function executeWithTimeout(fn, timeout = 30000) {
|
||||||
|
return Promise.race([
|
||||||
|
fn(),
|
||||||
|
new Promise((_, reject) =>
|
||||||
|
setTimeout(() => reject(new Error('执行超时')), timeout)
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 性能优化模式
|
||||||
|
```javascript
|
||||||
|
// 缓存机制
|
||||||
|
const cache = new Map();
|
||||||
|
function memoize(fn) {
|
||||||
|
return function(...args) {
|
||||||
|
const key = JSON.stringify(args);
|
||||||
|
if (cache.has(key)) {
|
||||||
|
return cache.get(key);
|
||||||
|
}
|
||||||
|
const result = fn.apply(this, args);
|
||||||
|
cache.set(key, result);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批处理优化
|
||||||
|
function batchProcess(items, batchSize = 10) {
|
||||||
|
const batches = [];
|
||||||
|
for (let i = 0; i < items.length; i += batchSize) {
|
||||||
|
batches.push(items.slice(i, i + batchSize));
|
||||||
|
}
|
||||||
|
return batches;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资源池管理
|
||||||
|
class ResourcePool {
|
||||||
|
constructor(createFn, maxSize = 10) {
|
||||||
|
this.createFn = createFn;
|
||||||
|
this.maxSize = maxSize;
|
||||||
|
this.pool = [];
|
||||||
|
this.active = new Set();
|
||||||
|
}
|
||||||
|
|
||||||
|
async acquire() {
|
||||||
|
if (this.pool.length > 0) {
|
||||||
|
const resource = this.pool.pop();
|
||||||
|
this.active.add(resource);
|
||||||
|
return resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.active.size < this.maxSize) {
|
||||||
|
const resource = await this.createFn();
|
||||||
|
this.active.add(resource);
|
||||||
|
return resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('资源池已满');
|
||||||
|
}
|
||||||
|
|
||||||
|
release(resource) {
|
||||||
|
this.active.delete(resource);
|
||||||
|
this.pool.push(resource);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔄 协议系统深度理解
|
||||||
|
|
||||||
|
### ResourceManager工作流程
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant User
|
||||||
|
participant RM as ResourceManager
|
||||||
|
participant TP as ToolProtocol
|
||||||
|
participant TS as ToolSandbox
|
||||||
|
|
||||||
|
User->>RM: loadResource('@tool://text-analyzer')
|
||||||
|
RM->>RM: parseProtocol('tool', 'text-analyzer')
|
||||||
|
RM->>TP: resolve('text-analyzer')
|
||||||
|
TP->>TP: findResourceById('text-analyzer', 'tool')
|
||||||
|
TP->>RM: return tool content
|
||||||
|
RM->>User: return {success: true, content: '...'}
|
||||||
|
User->>TS: new ToolSandbox('@tool://text-analyzer')
|
||||||
|
TS->>RM: loadResource('@tool://text-analyzer')
|
||||||
|
TS->>TS: analyze() → prepareDependencies() → execute()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 协议引用系统
|
||||||
|
```javascript
|
||||||
|
// 协议解析示例
|
||||||
|
const parsed = protocolParser.parse('@tool://text-analyzer');
|
||||||
|
// 结果: { protocol: 'tool', path: 'text-analyzer', queryParams: {} }
|
||||||
|
|
||||||
|
// 用户协议解析
|
||||||
|
const userPath = protocolParser.parse('@user://.promptx/toolbox/text-analyzer');
|
||||||
|
// 结果: { protocol: 'user', path: '.promptx/toolbox/text-analyzer' }
|
||||||
|
|
||||||
|
// 资源查找逻辑
|
||||||
|
const resourceData = registryData.findResourceById('text-analyzer', 'tool');
|
||||||
|
// 查找ID为'text-analyzer'且protocol为'tool'的资源
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📈 监控与调试
|
||||||
|
|
||||||
|
### 调试技巧
|
||||||
|
```javascript
|
||||||
|
// 沙箱状态监控
|
||||||
|
function debugSandbox(sandbox) {
|
||||||
|
console.log('沙箱状态:', {
|
||||||
|
toolId: sandbox.toolId,
|
||||||
|
isAnalyzed: sandbox.isAnalyzed,
|
||||||
|
isPrepared: sandbox.isPrepared,
|
||||||
|
dependencies: sandbox.dependencies,
|
||||||
|
sandboxPath: sandbox.sandboxPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 性能监控
|
||||||
|
function profileExecution(fn, name) {
|
||||||
|
return async (...args) => {
|
||||||
|
const start = process.hrtime.bigint();
|
||||||
|
const result = await fn(...args);
|
||||||
|
const end = process.hrtime.bigint();
|
||||||
|
const duration = Number(end - start) / 1000000; // 转换为毫秒
|
||||||
|
console.log(`${name} 执行耗时: ${duration.toFixed(2)}ms`);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误追踪
|
||||||
|
function trackError(error, context) {
|
||||||
|
console.error('错误详情:', {
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
context: context,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 日志系统
|
||||||
|
```javascript
|
||||||
|
const logger = {
|
||||||
|
debug: (message, data) => {
|
||||||
|
if (process.env.DEBUG) {
|
||||||
|
console.log(`[DEBUG] ${message}`, data);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
info: (message, data) => {
|
||||||
|
console.log(`[INFO] ${message}`, data);
|
||||||
|
},
|
||||||
|
|
||||||
|
warn: (message, data) => {
|
||||||
|
console.warn(`[WARN] ${message}`, data);
|
||||||
|
},
|
||||||
|
|
||||||
|
error: (message, error) => {
|
||||||
|
console.error(`[ERROR] ${message}`, {
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
</knowledge>
|
||||||
348
resource/role/luban/knowledge/tool-best-practices.knowledge.md
Normal file
348
resource/role/luban/knowledge/tool-best-practices.knowledge.md
Normal file
@ -0,0 +1,348 @@
|
|||||||
|
# 工具设计最佳实践
|
||||||
|
|
||||||
|
<knowledge>
|
||||||
|
|
||||||
|
## 🎯 工具设计哲学
|
||||||
|
|
||||||
|
### 极简主义原则
|
||||||
|
- **单一职责**:每个工具只解决一个核心问题
|
||||||
|
- **接口优雅**:参数设计直观易懂,返回值结构清晰
|
||||||
|
- **依赖最小**:只引入必要的依赖,避免过度膨胀
|
||||||
|
- **错误友好**:提供清晰的错误信息和处理建议
|
||||||
|
|
||||||
|
### 用户体验至上
|
||||||
|
- **即装即用**:工具无需复杂配置即可使用
|
||||||
|
- **文档自描述**:通过Schema和Metadata实现自我说明
|
||||||
|
- **性能优先**:执行效率和响应速度优化
|
||||||
|
- **跨平台兼容**:确保在不同环境下稳定运行
|
||||||
|
|
||||||
|
## 🏗️ 架构设计原则
|
||||||
|
|
||||||
|
### ToolInterface标准化实现
|
||||||
|
```javascript
|
||||||
|
// 完美的工具接口示例
|
||||||
|
module.exports = {
|
||||||
|
// 🔧 依赖管理:明确、最小、版本锁定
|
||||||
|
getDependencies() {
|
||||||
|
return [
|
||||||
|
'lodash@^4.17.21', // 工具函数库
|
||||||
|
'validator@^13.11.0' // 数据验证
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
|
// 📊 元信息:完整、准确、描述性
|
||||||
|
getMetadata() {
|
||||||
|
return {
|
||||||
|
name: 'text-processor',
|
||||||
|
description: '智能文本处理工具,支持清理、格式化、验证等功能',
|
||||||
|
version: '1.2.0',
|
||||||
|
category: 'text-processing',
|
||||||
|
author: '鲁班',
|
||||||
|
tags: ['text', 'processing', 'utility']
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
// 📝 Schema定义:结构化、类型安全、示例丰富
|
||||||
|
getSchema() {
|
||||||
|
return {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
text: {
|
||||||
|
type: 'string',
|
||||||
|
description: '需要处理的文本内容',
|
||||||
|
example: 'Hello World!'
|
||||||
|
},
|
||||||
|
operations: {
|
||||||
|
type: 'array',
|
||||||
|
items: {
|
||||||
|
type: 'string',
|
||||||
|
enum: ['clean', 'format', 'validate']
|
||||||
|
},
|
||||||
|
description: '要执行的操作列表',
|
||||||
|
default: ['clean']
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
encoding: { type: 'string', default: 'utf-8' },
|
||||||
|
strict: { type: 'boolean', default: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
required: ['text']
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
// ✅ 参数验证:严格、友好、早期失败
|
||||||
|
validate(params) {
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
if (!params.text || typeof params.text !== 'string') {
|
||||||
|
errors.push('text参数必须是非空字符串');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (params.text && params.text.length > 50000) {
|
||||||
|
errors.push('text长度不能超过50000字符');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
valid: errors.length === 0,
|
||||||
|
errors
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
// 🚀 核心执行:健壮、高效、可观测
|
||||||
|
async execute(params) {
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 核心处理逻辑
|
||||||
|
const result = await this.processText(params);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: result,
|
||||||
|
metadata: {
|
||||||
|
executionTime: Date.now() - startTime,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
message: error.message,
|
||||||
|
code: error.code || 'UNKNOWN_ERROR'
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
executionTime: Date.now() - startTime,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛡️ 安全与性能最佳实践
|
||||||
|
|
||||||
|
### 输入安全防护
|
||||||
|
```javascript
|
||||||
|
// 输入验证模式
|
||||||
|
class InputValidator {
|
||||||
|
static validateText(text, maxLength = 10000) {
|
||||||
|
if (typeof text !== 'string') {
|
||||||
|
throw new Error('输入必须是字符串类型');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text.length > maxLength) {
|
||||||
|
throw new Error(`文本长度超过限制: ${maxLength}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// XSS防护
|
||||||
|
if (/<script|javascript:|on\w+=/i.test(text)) {
|
||||||
|
throw new Error('检测到潜在的恶意脚本');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static sanitizeFilename(filename) {
|
||||||
|
return filename.replace(/[^a-zA-Z0-9._-]/g, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 性能优化模式
|
||||||
|
```javascript
|
||||||
|
// 缓存机制
|
||||||
|
const cache = new Map();
|
||||||
|
const CACHE_TTL = 300000; // 5分钟
|
||||||
|
|
||||||
|
function withCache(fn, cacheKey) {
|
||||||
|
const cached = cache.get(cacheKey);
|
||||||
|
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
|
||||||
|
return cached.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = fn();
|
||||||
|
cache.set(cacheKey, {
|
||||||
|
data: result,
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资源控制
|
||||||
|
function withResourceLimit(fn, timeout = 30000) {
|
||||||
|
return Promise.race([
|
||||||
|
fn(),
|
||||||
|
new Promise((_, reject) =>
|
||||||
|
setTimeout(() => reject(new Error('执行超时')), timeout)
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📦 依赖管理策略
|
||||||
|
|
||||||
|
### 精选依赖原则
|
||||||
|
```javascript
|
||||||
|
// 工具库选择矩阵
|
||||||
|
const DEPENDENCY_MATRIX = {
|
||||||
|
// 基础工具函数
|
||||||
|
utilities: {
|
||||||
|
recommended: 'lodash@^4.17.21',
|
||||||
|
alternatives: ['ramda@^0.29.0', 'underscore@^1.13.0'],
|
||||||
|
criteria: '成熟度、包大小、功能覆盖'
|
||||||
|
},
|
||||||
|
|
||||||
|
// HTTP请求
|
||||||
|
http: {
|
||||||
|
recommended: 'axios@^1.6.0',
|
||||||
|
alternatives: ['node-fetch@^3.3.0', 'got@^13.0.0'],
|
||||||
|
criteria: '易用性、功能丰富度、兼容性'
|
||||||
|
},
|
||||||
|
|
||||||
|
// 数据验证
|
||||||
|
validation: {
|
||||||
|
recommended: 'validator@^13.11.0',
|
||||||
|
alternatives: ['joi@^17.11.0', 'yup@^1.3.0'],
|
||||||
|
criteria: '验证规则丰富度、性能、学习成本'
|
||||||
|
},
|
||||||
|
|
||||||
|
// 文件操作
|
||||||
|
filesystem: {
|
||||||
|
recommended: 'fs-extra@^11.1.0',
|
||||||
|
alternatives: ['graceful-fs@^4.2.11'],
|
||||||
|
criteria: '功能完整性、错误处理、跨平台'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 依赖版本策略
|
||||||
|
getDependencies() {
|
||||||
|
return [
|
||||||
|
'lodash@^4.17.21', // 主版本锁定,次版本兼容
|
||||||
|
'axios@~1.6.0', // 补丁版本兼容
|
||||||
|
'validator@13.11.0' // 精确版本锁定(关键依赖)
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🧪 测试驱动开发
|
||||||
|
|
||||||
|
### 工具测试模式
|
||||||
|
```javascript
|
||||||
|
// 标准测试模板
|
||||||
|
describe('TextProcessor Tool', () => {
|
||||||
|
let tool;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tool = require('./text-processor.tool.js');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('接口合规性测试', () => {
|
||||||
|
test('必须实现所有接口方法', () => {
|
||||||
|
expect(typeof tool.getDependencies).toBe('function');
|
||||||
|
expect(typeof tool.getMetadata).toBe('function');
|
||||||
|
expect(typeof tool.getSchema).toBe('function');
|
||||||
|
expect(typeof tool.validate).toBe('function');
|
||||||
|
expect(typeof tool.execute).toBe('function');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getDependencies返回格式正确', () => {
|
||||||
|
const deps = tool.getDependencies();
|
||||||
|
expect(Array.isArray(deps)).toBe(true);
|
||||||
|
deps.forEach(dep => {
|
||||||
|
expect(typeof dep).toBe('string');
|
||||||
|
expect(dep).toMatch(/^[a-zA-Z0-9-]+@[\^~]?\d+\.\d+\.\d+$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('功能测试', () => {
|
||||||
|
test('正常输入处理', async () => {
|
||||||
|
const result = await tool.execute({
|
||||||
|
text: 'Hello World',
|
||||||
|
operations: ['clean']
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('异常输入处理', async () => {
|
||||||
|
const result = await tool.execute({
|
||||||
|
text: null
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 质量保证体系
|
||||||
|
|
||||||
|
### 代码质量检查
|
||||||
|
```javascript
|
||||||
|
// ESLint配置示例
|
||||||
|
module.exports = {
|
||||||
|
env: { node: true, es2021: true },
|
||||||
|
extends: ['eslint:recommended'],
|
||||||
|
rules: {
|
||||||
|
'no-console': 'warn',
|
||||||
|
'no-unused-vars': 'error',
|
||||||
|
'prefer-const': 'error',
|
||||||
|
'no-var': 'error',
|
||||||
|
'complexity': ['warn', 10],
|
||||||
|
'max-lines-per-function': ['warn', 50]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 性能基准测试
|
||||||
|
```javascript
|
||||||
|
// 性能测试模板
|
||||||
|
function benchmarkTool(tool, testData) {
|
||||||
|
const iterations = 1000;
|
||||||
|
const start = process.hrtime.bigint();
|
||||||
|
|
||||||
|
for (let i = 0; i < iterations; i++) {
|
||||||
|
tool.execute(testData);
|
||||||
|
}
|
||||||
|
|
||||||
|
const end = process.hrtime.bigint();
|
||||||
|
const avgTime = Number(end - start) / iterations / 1000000; // ms
|
||||||
|
|
||||||
|
return {
|
||||||
|
iterations,
|
||||||
|
averageTime: avgTime,
|
||||||
|
totalTime: Number(end - start) / 1000000
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🌟 卓越工具特征
|
||||||
|
|
||||||
|
### 用户体验指标
|
||||||
|
- **启动时间** < 100ms
|
||||||
|
- **执行效率** < 1s(常规任务)
|
||||||
|
- **内存占用** < 50MB
|
||||||
|
- **错误恢复** 100%优雅处理
|
||||||
|
|
||||||
|
### 代码质量指标
|
||||||
|
- **圈复杂度** < 10
|
||||||
|
- **测试覆盖率** > 90%
|
||||||
|
- **依赖漏洞** 0个
|
||||||
|
- **文档完整度** 100%
|
||||||
|
|
||||||
|
### 生态贡献指标
|
||||||
|
- **复用性** 高(可被其他工具引用)
|
||||||
|
- **扩展性** 强(支持插件机制)
|
||||||
|
- **社区认可** 正面反馈 > 95%
|
||||||
|
- **维护活跃度** 定期更新
|
||||||
|
|
||||||
|
</knowledge>
|
||||||
23
resource/role/luban/luban.role.md
Normal file
23
resource/role/luban/luban.role.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
# 鲁班 - PromptX工具大师
|
||||||
|
|
||||||
|
<role>
|
||||||
|
|
||||||
|
<personality>
|
||||||
|
@!thought://remember
|
||||||
|
@!thought://recall
|
||||||
|
@!thought://craftsmanship
|
||||||
|
</personality>
|
||||||
|
|
||||||
|
<principle>
|
||||||
|
@!execution://tool-development-workflow
|
||||||
|
@!execution://toolsandbox-mastery
|
||||||
|
</principle>
|
||||||
|
|
||||||
|
<knowledge>
|
||||||
|
@!knowledge://promptx-tool-architecture
|
||||||
|
@!knowledge://javascript-ecosystem
|
||||||
|
@!knowledge://tool-best-practices
|
||||||
|
@!knowledge://dpml-tool-tagging
|
||||||
|
</knowledge>
|
||||||
|
|
||||||
|
</role>
|
||||||
101
resource/role/luban/thought/craftsmanship.thought.md
Normal file
101
resource/role/luban/thought/craftsmanship.thought.md
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
# 工匠精神思维模式
|
||||||
|
|
||||||
|
<thought>
|
||||||
|
|
||||||
|
<exploration>
|
||||||
|
## 工匠精神的现代演化
|
||||||
|
|
||||||
|
### 传统工匠精神
|
||||||
|
- **精益求精**:每个细节都要做到极致
|
||||||
|
- **实用主义**:专注解决实际问题
|
||||||
|
- **传承创新**:在传统基础上不断创新
|
||||||
|
- **工具至上**:好的工具是效率的保证
|
||||||
|
|
||||||
|
### PromptX时代的工匠精神
|
||||||
|
- **协议规范**:严格遵循DPML和ToolInterface标准
|
||||||
|
- **沙箱隔离**:确保工具的安全性和可移植性
|
||||||
|
- **依赖管理**:自动化解决环境问题
|
||||||
|
- **一键可用**:追求即装即用的用户体验
|
||||||
|
|
||||||
|
### 现代工具特征
|
||||||
|
- **单文件为主**:简洁的脚本化工具设计
|
||||||
|
- **自描述能力**:工具自带元信息和Schema
|
||||||
|
- **协议统一**:通过@tool://和@user://标准化访问
|
||||||
|
- **隔离运行**:每个工具独立的沙箱环境
|
||||||
|
- **即装即用**:依赖自动管理,零配置启动
|
||||||
|
- **安全第一**:沙箱隔离,输入验证,资源限制
|
||||||
|
</exploration>
|
||||||
|
|
||||||
|
<reasoning>
|
||||||
|
## 工具创造逻辑
|
||||||
|
|
||||||
|
### 需求到实现的思维路径
|
||||||
|
```
|
||||||
|
用户问题 → 功能分析 → 依赖选择 → 接口设计 → 代码实现 → 沙箱测试
|
||||||
|
```
|
||||||
|
|
||||||
|
### 质量评估框架
|
||||||
|
- **功能完整性**:是否解决了核心问题
|
||||||
|
- **接口标准性**:是否符合ToolInterface规范
|
||||||
|
- **依赖合理性**:是否选择了最适合的依赖库
|
||||||
|
- **安全性**:是否有潜在的安全风险
|
||||||
|
- **可维护性**:代码是否清晰易懂
|
||||||
|
|
||||||
|
### 技术选择原则
|
||||||
|
- **成熟优先**:选择经过验证的依赖库
|
||||||
|
- **轻量优先**:避免过重的依赖
|
||||||
|
- **兼容优先**:确保跨平台兼容性
|
||||||
|
- **文档优先**:选择文档完善的库
|
||||||
|
</reasoning>
|
||||||
|
|
||||||
|
<challenge>
|
||||||
|
## 工具开发挑战
|
||||||
|
|
||||||
|
### 技术层面挑战
|
||||||
|
- **依赖冲突**:不同工具可能需要同一库的不同版本
|
||||||
|
- **沙箱限制**:VM环境的功能限制
|
||||||
|
- **异步处理**:Promise和async/await的正确使用
|
||||||
|
- **错误处理**:优雅的异常处理机制
|
||||||
|
|
||||||
|
### 设计层面挑战
|
||||||
|
- **接口简洁性**:如何设计简单易用的参数接口
|
||||||
|
- **功能边界**:工具应该做多少事情才合适
|
||||||
|
- **用户期望**:如何平衡功能丰富度和易用性
|
||||||
|
- **扩展性**:如何为未来需求留出空间
|
||||||
|
|
||||||
|
### 生态层面挑战
|
||||||
|
- **标准演进**:PromptX标准的持续演化
|
||||||
|
- **社区贡献**:如何建立良好的工具生态
|
||||||
|
- **质量控制**:如何确保工具质量
|
||||||
|
- **文档维护**:如何保持文档同步
|
||||||
|
</challenge>
|
||||||
|
|
||||||
|
<plan>
|
||||||
|
## 工具开发策略
|
||||||
|
|
||||||
|
### 开发前准备
|
||||||
|
1. **需求调研** → 深入理解用户真实需求
|
||||||
|
2. **技术调研** → 选择合适的依赖库和技术方案
|
||||||
|
3. **接口设计** → 定义清晰的参数和返回值结构
|
||||||
|
4. **原型验证** → 快速验证核心逻辑的可行性
|
||||||
|
|
||||||
|
### 开发过程管控
|
||||||
|
1. **渐进式开发** → 先实现核心功能,再逐步完善
|
||||||
|
2. **持续测试** → 每个功能点都要充分测试
|
||||||
|
3. **代码审查** → 确保代码质量和安全性
|
||||||
|
4. **文档同步** → 代码和文档同步更新
|
||||||
|
|
||||||
|
### 发布后维护
|
||||||
|
1. **用户反馈收集** → 持续收集使用反馈
|
||||||
|
2. **Bug修复优先** → 快速响应和修复问题
|
||||||
|
3. **功能迭代** → 基于需求进行功能增强
|
||||||
|
4. **性能优化** → 持续优化工具性能
|
||||||
|
|
||||||
|
### 质量保证体系
|
||||||
|
- **代码规范**:ESLint配置和代码风格统一
|
||||||
|
- **测试覆盖**:单元测试和集成测试
|
||||||
|
- **安全审计**:依赖库安全性检查
|
||||||
|
- **性能监控**:执行时间和资源使用监控
|
||||||
|
</plan>
|
||||||
|
|
||||||
|
</thought>
|
||||||
@ -1,139 +0,0 @@
|
|||||||
/**
|
|
||||||
* @tool calculator
|
|
||||||
* @description 数学计算工具
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
/**
|
|
||||||
* 获取工具元信息
|
|
||||||
* @returns {Object} 工具元信息
|
|
||||||
*/
|
|
||||||
getMetadata() {
|
|
||||||
return {
|
|
||||||
name: 'calculator',
|
|
||||||
description: '提供基础数学计算功能,支持加减乘除运算',
|
|
||||||
version: '1.0.0',
|
|
||||||
author: 'PromptX Framework',
|
|
||||||
category: 'math',
|
|
||||||
tags: ['calculator', 'math', 'arithmetic']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取参数Schema
|
|
||||||
* @returns {Object} JSON Schema定义
|
|
||||||
*/
|
|
||||||
getSchema() {
|
|
||||||
return {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
operation: {
|
|
||||||
type: 'string',
|
|
||||||
enum: ['add', 'subtract', 'multiply', 'divide'],
|
|
||||||
description: '数学运算类型'
|
|
||||||
},
|
|
||||||
a: {
|
|
||||||
type: 'number',
|
|
||||||
description: '第一个操作数'
|
|
||||||
},
|
|
||||||
b: {
|
|
||||||
type: 'number',
|
|
||||||
description: '第二个操作数'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ['operation', 'a', 'b'],
|
|
||||||
additionalProperties: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证参数
|
|
||||||
* @param {Object} params - 输入参数
|
|
||||||
* @returns {boolean} 验证结果
|
|
||||||
*/
|
|
||||||
validate(params) {
|
|
||||||
const { operation, a, b } = params
|
|
||||||
|
|
||||||
// 检查必需参数
|
|
||||||
if (!operation || typeof a !== 'number' || typeof b !== 'number') {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查操作类型
|
|
||||||
const validOperations = ['add', 'subtract', 'multiply', 'divide']
|
|
||||||
if (!validOperations.includes(operation)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查除零
|
|
||||||
if (operation === 'divide' && b === 0) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行计算
|
|
||||||
* @param {Object} params - 计算参数
|
|
||||||
* @param {string} params.operation - 运算类型 ('add', 'subtract', 'multiply', 'divide')
|
|
||||||
* @param {number} params.a - 第一个操作数
|
|
||||||
* @param {number} params.b - 第二个操作数
|
|
||||||
* @returns {Object} 计算结果
|
|
||||||
*/
|
|
||||||
async execute(params) {
|
|
||||||
const { operation, a, b } = params
|
|
||||||
|
|
||||||
let result
|
|
||||||
let expression
|
|
||||||
|
|
||||||
switch (operation) {
|
|
||||||
case 'add':
|
|
||||||
result = a + b
|
|
||||||
expression = `${a} + ${b}`
|
|
||||||
break
|
|
||||||
case 'subtract':
|
|
||||||
result = a - b
|
|
||||||
expression = `${a} - ${b}`
|
|
||||||
break
|
|
||||||
case 'multiply':
|
|
||||||
result = a * b
|
|
||||||
expression = `${a} × ${b}`
|
|
||||||
break
|
|
||||||
case 'divide':
|
|
||||||
if (b === 0) {
|
|
||||||
throw new Error('Division by zero is not allowed')
|
|
||||||
}
|
|
||||||
result = a / b
|
|
||||||
expression = `${a} ÷ ${b}`
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown operation: ${operation}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
expression,
|
|
||||||
result,
|
|
||||||
operation,
|
|
||||||
operands: { a, b },
|
|
||||||
formatted: `${expression} = ${result}`
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 工具初始化(可选)
|
|
||||||
*/
|
|
||||||
async init() {
|
|
||||||
// 可以在这里进行工具初始化工作
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 工具清理(可选)
|
|
||||||
*/
|
|
||||||
async cleanup() {
|
|
||||||
// 可以在这里进行清理工作
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,202 +0,0 @@
|
|||||||
/**
|
|
||||||
* @tool send-email
|
|
||||||
* @description 邮件发送工具(演示版)
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
/**
|
|
||||||
* 获取工具元信息
|
|
||||||
* @returns {Object} 工具元信息
|
|
||||||
*/
|
|
||||||
getMetadata() {
|
|
||||||
return {
|
|
||||||
name: 'send-email',
|
|
||||||
description: '邮件发送工具,支持发送格式化邮件(演示版本)',
|
|
||||||
version: '1.0.0',
|
|
||||||
author: 'PromptX Framework',
|
|
||||||
category: 'communication',
|
|
||||||
tags: ['email', 'communication', 'notification'],
|
|
||||||
demo: true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取参数Schema
|
|
||||||
* @returns {Object} JSON Schema定义
|
|
||||||
*/
|
|
||||||
getSchema() {
|
|
||||||
return {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
to: {
|
|
||||||
type: 'string',
|
|
||||||
format: 'email',
|
|
||||||
description: '收件人邮箱地址'
|
|
||||||
},
|
|
||||||
subject: {
|
|
||||||
type: 'string',
|
|
||||||
minLength: 1,
|
|
||||||
description: '邮件主题'
|
|
||||||
},
|
|
||||||
content: {
|
|
||||||
type: 'string',
|
|
||||||
minLength: 1,
|
|
||||||
description: '邮件内容'
|
|
||||||
},
|
|
||||||
cc: {
|
|
||||||
type: 'array',
|
|
||||||
items: {
|
|
||||||
type: 'string',
|
|
||||||
format: 'email'
|
|
||||||
},
|
|
||||||
description: '抄送邮箱列表(可选)'
|
|
||||||
},
|
|
||||||
priority: {
|
|
||||||
type: 'string',
|
|
||||||
enum: ['low', 'normal', 'high'],
|
|
||||||
default: 'normal',
|
|
||||||
description: '邮件优先级'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ['to', 'subject', 'content'],
|
|
||||||
additionalProperties: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证参数
|
|
||||||
* @param {Object} params - 输入参数
|
|
||||||
* @returns {boolean} 验证结果
|
|
||||||
*/
|
|
||||||
validate(params) {
|
|
||||||
const { to, subject, content } = params
|
|
||||||
|
|
||||||
// 检查必需参数
|
|
||||||
if (!to || !subject || !content) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 简单的邮箱格式验证
|
|
||||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
||||||
if (!emailRegex.test(to)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查抄送邮箱格式(如果存在)
|
|
||||||
if (params.cc && Array.isArray(params.cc)) {
|
|
||||||
for (const ccEmail of params.cc) {
|
|
||||||
if (!emailRegex.test(ccEmail)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送邮件(演示版本)
|
|
||||||
* @param {Object} params - 邮件参数
|
|
||||||
* @param {string} params.to - 收件人邮箱
|
|
||||||
* @param {string} params.subject - 邮件主题
|
|
||||||
* @param {string} params.content - 邮件内容
|
|
||||||
* @param {string[]} params.cc - 抄送邮箱列表(可选)
|
|
||||||
* @param {string} params.priority - 邮件优先级(可选)
|
|
||||||
* @returns {Object} 发送结果
|
|
||||||
*/
|
|
||||||
async execute(params) {
|
|
||||||
const { to, subject, content, cc = [], priority = 'normal' } = params
|
|
||||||
|
|
||||||
// 生成邮件ID(演示用)
|
|
||||||
const emailId = `email_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
|
||||||
|
|
||||||
// 格式化邮件内容
|
|
||||||
const formattedEmail = this.formatEmail({
|
|
||||||
to,
|
|
||||||
subject,
|
|
||||||
content,
|
|
||||||
cc,
|
|
||||||
priority,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
})
|
|
||||||
|
|
||||||
// 模拟发送延迟
|
|
||||||
await this.simulateDelay(500)
|
|
||||||
|
|
||||||
// 演示版本:不实际发送邮件,只返回格式化结果
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
email_id: emailId,
|
|
||||||
to,
|
|
||||||
subject,
|
|
||||||
content_preview: content.slice(0, 100) + (content.length > 100 ? '...' : ''),
|
|
||||||
cc_count: cc.length,
|
|
||||||
priority,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
formatted_email: formattedEmail,
|
|
||||||
demo_note: '这是演示版本,邮件未实际发送',
|
|
||||||
status: 'demo_sent'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 格式化邮件内容
|
|
||||||
* @param {Object} emailData - 邮件数据
|
|
||||||
* @returns {string} 格式化的邮件
|
|
||||||
*/
|
|
||||||
formatEmail(emailData) {
|
|
||||||
const { to, subject, content, cc, priority, timestamp } = emailData
|
|
||||||
|
|
||||||
let formatted = `收件人: ${to}\n`
|
|
||||||
|
|
||||||
if (cc.length > 0) {
|
|
||||||
formatted += `抄送: ${cc.join(', ')}\n`
|
|
||||||
}
|
|
||||||
|
|
||||||
formatted += `主题: ${subject}\n`
|
|
||||||
formatted += `优先级: ${this.getPriorityText(priority)}\n`
|
|
||||||
formatted += `时间: ${new Date(timestamp).toLocaleString('zh-CN')}\n`
|
|
||||||
formatted += `\n内容:\n${content}\n`
|
|
||||||
|
|
||||||
return formatted
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取优先级文本
|
|
||||||
* @param {string} priority - 优先级
|
|
||||||
* @returns {string} 优先级文本
|
|
||||||
*/
|
|
||||||
getPriorityText(priority) {
|
|
||||||
const priorityMap = {
|
|
||||||
low: '低',
|
|
||||||
normal: '普通',
|
|
||||||
high: '高'
|
|
||||||
}
|
|
||||||
return priorityMap[priority] || '普通'
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 模拟网络延迟
|
|
||||||
* @param {number} ms - 延迟毫秒数
|
|
||||||
*/
|
|
||||||
async simulateDelay(ms) {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, ms))
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 工具初始化
|
|
||||||
*/
|
|
||||||
async init() {
|
|
||||||
// 在实际版本中,这里可以初始化邮件服务连接
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 工具清理
|
|
||||||
*/
|
|
||||||
async cleanup() {
|
|
||||||
// 在实际版本中,这里可以关闭邮件服务连接
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -7,18 +7,22 @@ async function generatePackageRegistry() {
|
|||||||
try {
|
try {
|
||||||
console.log('🏗️ 开始生成Package级别注册表...');
|
console.log('🏗️ 开始生成Package级别注册表...');
|
||||||
|
|
||||||
// 获取项目根目录
|
// 获取项目根目录(PromptX子项目)
|
||||||
const projectRoot = process.cwd();
|
const projectRoot = process.cwd();
|
||||||
console.log(`📁 项目根目录: ${projectRoot}`);
|
console.log(`📁 项目根目录: ${projectRoot}`);
|
||||||
|
|
||||||
// 创建PackageDiscovery实例并设置注册表路径
|
// 获取包级资源目录(上级目录的resource)
|
||||||
|
const packageResourceRoot = path.dirname(path.dirname(projectRoot));
|
||||||
|
console.log(`📦 包级资源根目录: ${packageResourceRoot}`);
|
||||||
|
|
||||||
|
// 创建PackageDiscovery实例并设置注册表路径(保存到项目下)
|
||||||
const discovery = new PackageDiscovery();
|
const discovery = new PackageDiscovery();
|
||||||
discovery.registryPath = path.join(projectRoot, 'resource', 'package.registry.json');
|
discovery.registryPath = path.join(projectRoot, 'resource', 'package.registry.json');
|
||||||
|
|
||||||
console.log(`📋 注册表路径: ${discovery.registryPath}`);
|
console.log(`📋 注册表路径: ${discovery.registryPath}`);
|
||||||
|
|
||||||
// 生成注册表
|
// 生成注册表(扫描包级资源目录)
|
||||||
const registryData = await discovery.generateRegistry(projectRoot);
|
const registryData = await discovery.generateRegistry(packageResourceRoot);
|
||||||
|
|
||||||
console.log('✅ Package注册表生成完成!');
|
console.log('✅ Package注册表生成完成!');
|
||||||
console.log(`📊 总资源数: ${registryData.size}`);
|
console.log(`📊 总资源数: ${registryData.size}`);
|
||||||
|
|||||||
@ -190,12 +190,9 @@ class FilePatternDiscovery extends BaseDiscovery {
|
|||||||
if (fileName.endsWith(extension)) {
|
if (fileName.endsWith(extension)) {
|
||||||
const baseName = fileName.slice(0, -extension.length)
|
const baseName = fileName.slice(0, -extension.length)
|
||||||
|
|
||||||
// role类型直接返回基础名称,其他类型添加前缀
|
// 所有资源类型都直接返回基础名称,不添加前缀
|
||||||
if (resourceType === 'role') {
|
// 协议信息已经在resource对象的protocol字段中
|
||||||
return baseName
|
return baseName
|
||||||
} else {
|
|
||||||
return `${resourceType}:${baseName}`
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -32,7 +32,7 @@ const getUserDirectories = () => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户目录协议实现
|
* 用户目录协议实现
|
||||||
* 实现@user://协议,用于访问用户的标准目录(Documents、Desktop、Downloads等)
|
* 实现@user://协议,直接映射到用户主目录,提供简洁的用户文件访问
|
||||||
*/
|
*/
|
||||||
class UserProtocol extends ResourceProtocol {
|
class UserProtocol extends ResourceProtocol {
|
||||||
constructor (options = {}) {
|
constructor (options = {}) {
|
||||||
@ -74,18 +74,17 @@ class UserProtocol extends ResourceProtocol {
|
|||||||
getProtocolInfo () {
|
getProtocolInfo () {
|
||||||
return {
|
return {
|
||||||
name: 'user',
|
name: 'user',
|
||||||
description: '用户目录协议,提供跨平台的用户标准目录访问',
|
description: '用户目录协议,直接映射到用户主目录',
|
||||||
location: 'user://{directory}/{path}',
|
location: 'user://{path}',
|
||||||
examples: [
|
examples: [
|
||||||
'user://documents/notes.txt',
|
'user://.promptx/toolbox/text-analyzer',
|
||||||
'user://desktop/readme.md',
|
'user://.bashrc',
|
||||||
'user://downloads/',
|
'user://Documents/notes.txt',
|
||||||
'user://home/.bashrc',
|
'user://Desktop/readme.md',
|
||||||
'user://config/promptx.json',
|
'user://Downloads/file.zip',
|
||||||
'user://data/memories.json',
|
'user://.promptx/config.json'
|
||||||
'user://cache/temp-data.json'
|
|
||||||
],
|
],
|
||||||
supportedDirectories: Object.keys(this.userDirs),
|
basePath: '用户主目录 (~)',
|
||||||
params: this.getSupportedParams()
|
params: this.getSupportedParams()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -121,34 +120,25 @@ class UserProtocol extends ResourceProtocol {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析用户目录路径
|
* 解析用户目录路径
|
||||||
* @param {string} resourcePath - 原始资源路径,如 "documents/notes.txt"
|
* @param {string} resourcePath - 原始资源路径,如 ".promptx/toolbox/test-tool"
|
||||||
* @param {QueryParams} queryParams - 查询参数
|
* @param {QueryParams} queryParams - 查询参数
|
||||||
* @returns {Promise<string>} 解析后的绝对路径
|
* @returns {Promise<string>} 解析后的绝对路径
|
||||||
*/
|
*/
|
||||||
async resolvePath (resourcePath, queryParams) {
|
async resolvePath (resourcePath, queryParams) {
|
||||||
const parts = resourcePath.split('/')
|
// 直接使用用户主目录作为基础路径
|
||||||
const dirType = parts[0]
|
const userHomeDir = getUserDirectories().getHomeFolder()
|
||||||
const relativePath = parts.slice(1).join('/')
|
|
||||||
|
// 如果没有相对路径,返回用户主目录本身
|
||||||
// 验证目录类型
|
if (!resourcePath) {
|
||||||
if (!this.userDirs[dirType]) {
|
return userHomeDir
|
||||||
throw new Error(`不支持的用户目录类型: ${dirType}。支持的类型: ${Object.keys(this.userDirs).join(', ')}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取用户目录路径
|
|
||||||
const userDirPath = await this.getUserDirectory(dirType)
|
|
||||||
|
|
||||||
// 如果没有相对路径,返回目录本身
|
|
||||||
if (!relativePath) {
|
|
||||||
return userDirPath
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拼接完整路径
|
// 拼接完整路径
|
||||||
const fullPath = path.join(userDirPath, relativePath)
|
const fullPath = path.join(userHomeDir, resourcePath)
|
||||||
|
|
||||||
// 安全检查:确保路径在用户目录内
|
// 安全检查:确保路径在用户主目录内
|
||||||
const resolvedPath = path.resolve(fullPath)
|
const resolvedPath = path.resolve(fullPath)
|
||||||
const resolvedUserDir = path.resolve(userDirPath)
|
const resolvedUserDir = path.resolve(userHomeDir)
|
||||||
|
|
||||||
if (!resolvedPath.startsWith(resolvedUserDir)) {
|
if (!resolvedPath.startsWith(resolvedUserDir)) {
|
||||||
throw new Error(`安全错误:路径超出用户目录范围: ${resolvedPath}`)
|
throw new Error(`安全错误:路径超出用户目录范围: ${resolvedPath}`)
|
||||||
|
|||||||
@ -40,6 +40,9 @@ class ToolExecutor {
|
|||||||
// 2. 执行工具代码并创建实例
|
// 2. 执行工具代码并创建实例
|
||||||
const tool = this.executeToolContent(toolContent, context.toolName || 'unknown');
|
const tool = this.executeToolContent(toolContent, context.toolName || 'unknown');
|
||||||
|
|
||||||
|
// 2.5. 增强工具默认实现
|
||||||
|
this.enhanceToolWithDefaults(tool);
|
||||||
|
|
||||||
// 3. 参数验证
|
// 3. 参数验证
|
||||||
const validation = this.validateParameters(tool, parameters);
|
const validation = this.validateParameters(tool, parameters);
|
||||||
if (!validation.valid) {
|
if (!validation.valid) {
|
||||||
@ -85,38 +88,54 @@ class ToolExecutor {
|
|||||||
*/
|
*/
|
||||||
executeToolContent(toolContent, toolName) {
|
executeToolContent(toolContent, toolName) {
|
||||||
try {
|
try {
|
||||||
// 创建安全的执行环境
|
// 1. 先用基础沙箱获取工具实例,检查是否有包信息
|
||||||
const sandbox = this.createSandbox();
|
const basicSandbox = this.createSandbox();
|
||||||
|
|
||||||
// 执行工具代码
|
|
||||||
const vm = require('vm');
|
const vm = require('vm');
|
||||||
const script = new vm.Script(toolContent, { filename: `${toolName}.js` });
|
const script = new vm.Script(toolContent, { filename: `${toolName}.js` });
|
||||||
const context = vm.createContext(sandbox);
|
const basicContext = vm.createContext(basicSandbox);
|
||||||
|
|
||||||
script.runInContext(context);
|
script.runInContext(basicContext);
|
||||||
|
const exported = basicContext.module.exports;
|
||||||
// 获取导出的工具
|
|
||||||
const exported = context.module.exports;
|
|
||||||
|
|
||||||
if (!exported) {
|
if (!exported) {
|
||||||
throw new Error(`工具未正确导出: ${toolName}`);
|
throw new Error(`工具未正确导出: ${toolName}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 支持两种导出方式:
|
// 实例化工具
|
||||||
// 1. 导出类(构造函数)- 需要实例化
|
|
||||||
// 2. 导出对象 - 直接使用
|
|
||||||
let toolInstance;
|
let toolInstance;
|
||||||
|
|
||||||
if (typeof exported === 'function') {
|
if (typeof exported === 'function') {
|
||||||
// 导出的是类,需要实例化
|
|
||||||
toolInstance = new exported();
|
toolInstance = new exported();
|
||||||
} else if (typeof exported === 'object') {
|
} else if (typeof exported === 'object') {
|
||||||
// 导出的是对象,直接使用
|
|
||||||
toolInstance = exported;
|
toolInstance = exported;
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`工具导出格式不正确,必须是类或对象: ${toolName}`);
|
throw new Error(`工具导出格式不正确,必须是类或对象: ${toolName}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. 检查工具是否有包信息
|
||||||
|
let packageInfo = null;
|
||||||
|
if (typeof toolInstance.getPackage === 'function') {
|
||||||
|
try {
|
||||||
|
packageInfo = toolInstance.getPackage();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`[ToolExecutor] 获取包信息失败: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 如果有包信息,用智能沙箱重新执行
|
||||||
|
if (packageInfo && packageInfo.directory) {
|
||||||
|
const smartSandbox = this.createSmartSandbox(packageInfo);
|
||||||
|
const smartContext = vm.createContext(smartSandbox);
|
||||||
|
|
||||||
|
script.runInContext(smartContext);
|
||||||
|
const smartExported = smartContext.module.exports;
|
||||||
|
|
||||||
|
if (typeof smartExported === 'function') {
|
||||||
|
return new smartExported();
|
||||||
|
} else if (typeof smartExported === 'object') {
|
||||||
|
return smartExported;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return toolInstance;
|
return toolInstance;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -124,6 +143,57 @@ class ToolExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建智能沙箱(支持工具依赖)
|
||||||
|
* @param {Object} packageInfo - 工具包信息
|
||||||
|
* @returns {Object} 智能沙箱环境
|
||||||
|
*/
|
||||||
|
createSmartSandbox(packageInfo) {
|
||||||
|
const { directory, dependencies } = packageInfo;
|
||||||
|
|
||||||
|
return {
|
||||||
|
require: (moduleName) => {
|
||||||
|
try {
|
||||||
|
// 优先从工具目录查找依赖
|
||||||
|
return require(require.resolve(moduleName, {
|
||||||
|
paths: [
|
||||||
|
directory + '/node_modules',
|
||||||
|
directory,
|
||||||
|
process.cwd() + '/node_modules'
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
// 回退到默认require
|
||||||
|
return require(moduleName);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
module: { exports: {} },
|
||||||
|
exports: {},
|
||||||
|
console: console,
|
||||||
|
Buffer: Buffer,
|
||||||
|
process: {
|
||||||
|
env: process.env,
|
||||||
|
hrtime: process.hrtime
|
||||||
|
},
|
||||||
|
setTimeout: setTimeout,
|
||||||
|
clearTimeout: clearTimeout,
|
||||||
|
setInterval: setInterval,
|
||||||
|
clearInterval: clearInterval,
|
||||||
|
// 基础全局对象
|
||||||
|
Object: Object,
|
||||||
|
Array: Array,
|
||||||
|
String: String,
|
||||||
|
Number: Number,
|
||||||
|
Boolean: Boolean,
|
||||||
|
Date: Date,
|
||||||
|
JSON: JSON,
|
||||||
|
Math: Math,
|
||||||
|
RegExp: RegExp,
|
||||||
|
Error: Error,
|
||||||
|
URL: URL
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建安全的执行沙箱
|
* 创建安全的执行沙箱
|
||||||
* @returns {Object} 沙箱环境
|
* @returns {Object} 沙箱环境
|
||||||
@ -153,7 +223,8 @@ class ToolExecutor {
|
|||||||
JSON: JSON,
|
JSON: JSON,
|
||||||
Math: Math,
|
Math: Math,
|
||||||
RegExp: RegExp,
|
RegExp: RegExp,
|
||||||
Error: Error
|
Error: Error,
|
||||||
|
URL: URL
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -45,6 +45,16 @@ const TOOL_INTERFACE = {
|
|||||||
|
|
||||||
// 可选实现的方法
|
// 可选实现的方法
|
||||||
optional: [
|
optional: [
|
||||||
|
{
|
||||||
|
name: 'getPackage',
|
||||||
|
signature: '() => Object',
|
||||||
|
description: '获取工具包信息(可选,用于依赖管理)',
|
||||||
|
returns: {
|
||||||
|
directory: 'string - 工具目录路径',
|
||||||
|
dependencies: 'Array<string> - 依赖列表',
|
||||||
|
packageJson: 'Object - package.json内容(可选)'
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'validate',
|
name: 'validate',
|
||||||
signature: '(parameters: Object) => Object',
|
signature: '(parameters: Object) => Object',
|
||||||
|
|||||||
517
src/lib/tool/ToolSandbox.js
Normal file
517
src/lib/tool/ToolSandbox.js
Normal file
@ -0,0 +1,517 @@
|
|||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
const vm = require('vm');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ToolSandbox - 工具沙箱环境管理器
|
||||||
|
*
|
||||||
|
* 基于现有协议系统的工具执行环境,支持:
|
||||||
|
* - @tool:// 协议定位工具
|
||||||
|
* - @user://.promptx/toolbox 沙箱隔离
|
||||||
|
* - 自动依赖管理
|
||||||
|
* - 可复用的执行环境
|
||||||
|
*/
|
||||||
|
class ToolSandbox {
|
||||||
|
constructor(toolReference, options = {}) {
|
||||||
|
this.toolReference = toolReference; // @tool://url-validator
|
||||||
|
this.resourceManager = null; // ResourceManager实例
|
||||||
|
this.toolId = null; // 工具ID,如 url-validator
|
||||||
|
this.toolContent = null; // 工具文件内容
|
||||||
|
this.toolInstance = null; // 工具实例
|
||||||
|
this.dependencies = []; // 依赖列表
|
||||||
|
this.sandboxPath = null; // 沙箱目录路径
|
||||||
|
this.sandboxContext = null; // VM沙箱上下文
|
||||||
|
|
||||||
|
// 状态标志
|
||||||
|
this.isAnalyzed = false;
|
||||||
|
this.isPrepared = false;
|
||||||
|
|
||||||
|
// 配置选项
|
||||||
|
this.options = {
|
||||||
|
timeout: 30000,
|
||||||
|
enableDependencyInstall: true,
|
||||||
|
forceReinstall: false,
|
||||||
|
...options
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置ResourceManager实例
|
||||||
|
* @param {ResourceManager} resourceManager
|
||||||
|
*/
|
||||||
|
setResourceManager(resourceManager) {
|
||||||
|
this.resourceManager = resourceManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分析工具:加载工具内容,提取元信息和依赖
|
||||||
|
* @returns {Promise<Object>} 分析结果
|
||||||
|
*/
|
||||||
|
async analyze() {
|
||||||
|
if (this.isAnalyzed) {
|
||||||
|
return this.getAnalysisResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.resourceManager) {
|
||||||
|
throw new Error('ResourceManager not set. Call setResourceManager() first.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 解析工具引用,提取工具ID
|
||||||
|
this.toolId = this.extractToolId(this.toolReference);
|
||||||
|
|
||||||
|
// 2. 通过协议系统加载工具
|
||||||
|
const toolResult = await this.resourceManager.loadResource(this.toolReference);
|
||||||
|
if (!toolResult.success) {
|
||||||
|
// 调试:尝试不同的查找方式
|
||||||
|
console.log(`🔍 调试:尝试查找工具 ${this.toolReference}`);
|
||||||
|
const directLookup = this.resourceManager.registryData.findResourceById(`tool:${this.toolId}`, 'tool');
|
||||||
|
console.log(` - 直接查找 tool:${this.toolId}: ${directLookup ? '找到' : '未找到'}`);
|
||||||
|
|
||||||
|
throw new Error(`Failed to load tool: ${toolResult.error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.toolContent = toolResult.content;
|
||||||
|
|
||||||
|
// 3. 设置沙箱路径
|
||||||
|
this.sandboxPath = await this.resolveSandboxPath();
|
||||||
|
|
||||||
|
// 4. 在基础沙箱中分析工具
|
||||||
|
await this.analyzeToolInSandbox();
|
||||||
|
|
||||||
|
this.isAnalyzed = true;
|
||||||
|
return this.getAnalysisResult();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Tool analysis failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 准备依赖:安装依赖,准备执行环境
|
||||||
|
* @returns {Promise<Object>} 准备结果
|
||||||
|
*/
|
||||||
|
async prepareDependencies() {
|
||||||
|
if (!this.isAnalyzed) {
|
||||||
|
await this.analyze();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isPrepared && !this.options.forceReinstall) {
|
||||||
|
return { success: true, message: 'Dependencies already prepared' };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 确保沙箱目录存在
|
||||||
|
await this.ensureSandboxDirectory();
|
||||||
|
|
||||||
|
// 2. 如果有依赖,安装它们
|
||||||
|
if (this.dependencies.length > 0) {
|
||||||
|
await this.installDependencies();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 创建执行沙箱环境
|
||||||
|
await this.createExecutionSandbox();
|
||||||
|
|
||||||
|
this.isPrepared = true;
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
sandboxPath: this.sandboxPath,
|
||||||
|
dependencies: this.dependencies
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Dependency preparation failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行工具
|
||||||
|
* @param {Object} parameters - 工具参数
|
||||||
|
* @returns {Promise<Object>} 执行结果
|
||||||
|
*/
|
||||||
|
async execute(parameters = {}) {
|
||||||
|
if (!this.isPrepared) {
|
||||||
|
await this.prepareDependencies();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 参数验证
|
||||||
|
await this.validateParameters(parameters);
|
||||||
|
|
||||||
|
// 2. 在沙箱中执行工具
|
||||||
|
const result = await this.executeInSandbox(parameters);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: result,
|
||||||
|
metadata: {
|
||||||
|
toolId: this.toolId,
|
||||||
|
sandboxPath: this.sandboxPath,
|
||||||
|
executionTime: Date.now()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
toolId: this.toolId,
|
||||||
|
sandboxPath: this.sandboxPath
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提取工具ID
|
||||||
|
* @param {string} toolReference - @tool://url-validator
|
||||||
|
* @returns {string} 工具ID
|
||||||
|
*/
|
||||||
|
extractToolId(toolReference) {
|
||||||
|
const match = toolReference.match(/^@tool:\/\/(.+)$/);
|
||||||
|
if (!match) {
|
||||||
|
throw new Error(`Invalid tool reference format: ${toolReference}`);
|
||||||
|
}
|
||||||
|
return match[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析沙箱路径
|
||||||
|
* @returns {Promise<string>} 沙箱绝对路径
|
||||||
|
*/
|
||||||
|
async resolveSandboxPath() {
|
||||||
|
// 使用 @user://.promptx/toolbox/{toolId} 作为沙箱路径
|
||||||
|
const userDataReference = `@user://.promptx/toolbox/${this.toolId}`;
|
||||||
|
const result = await this.resourceManager.resolveProtocolReference(userDataReference);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(`Failed to resolve sandbox path: ${result.error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通过UserProtocol解析实际路径
|
||||||
|
const userProtocol = this.resourceManager.protocols.get('user');
|
||||||
|
const sandboxPath = await userProtocol.resolvePath(
|
||||||
|
`.promptx/toolbox/${this.toolId}`,
|
||||||
|
new Map()
|
||||||
|
);
|
||||||
|
|
||||||
|
return sandboxPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在基础沙箱中分析工具
|
||||||
|
*/
|
||||||
|
async analyzeToolInSandbox() {
|
||||||
|
const basicSandbox = this.createBasicSandbox();
|
||||||
|
const script = new vm.Script(this.toolContent, { filename: `${this.toolId}.js` });
|
||||||
|
const context = vm.createContext(basicSandbox);
|
||||||
|
|
||||||
|
script.runInContext(context);
|
||||||
|
const exported = context.module.exports;
|
||||||
|
|
||||||
|
if (!exported) {
|
||||||
|
throw new Error(`Tool does not export anything: ${this.toolId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建工具实例
|
||||||
|
let toolInstance;
|
||||||
|
if (typeof exported === 'function') {
|
||||||
|
toolInstance = new exported();
|
||||||
|
} else if (typeof exported === 'object') {
|
||||||
|
toolInstance = exported;
|
||||||
|
} else {
|
||||||
|
throw new Error(`Invalid tool export format: ${this.toolId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取依赖
|
||||||
|
if (typeof toolInstance.getDependencies === 'function') {
|
||||||
|
try {
|
||||||
|
this.dependencies = toolInstance.getDependencies() || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`[ToolSandbox] Failed to get dependencies for ${this.toolId}: ${error.message}`);
|
||||||
|
this.dependencies = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.toolInstance = toolInstance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保沙箱目录存在
|
||||||
|
*/
|
||||||
|
async ensureSandboxDirectory() {
|
||||||
|
try {
|
||||||
|
await fs.access(this.sandboxPath);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') {
|
||||||
|
await fs.mkdir(this.sandboxPath, { recursive: true });
|
||||||
|
} else {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安装依赖
|
||||||
|
*/
|
||||||
|
async installDependencies() {
|
||||||
|
if (this.dependencies.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 创建package.json
|
||||||
|
await this.createPackageJson();
|
||||||
|
|
||||||
|
// 2. 使用内置pnpm安装依赖
|
||||||
|
await this.runPnpmInstall();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建package.json
|
||||||
|
*/
|
||||||
|
async createPackageJson() {
|
||||||
|
const packageJsonPath = path.join(this.sandboxPath, 'package.json');
|
||||||
|
|
||||||
|
// 检查是否已存在且不强制重装
|
||||||
|
if (!this.options.forceReinstall) {
|
||||||
|
try {
|
||||||
|
await fs.access(packageJsonPath);
|
||||||
|
return; // 已存在,跳过
|
||||||
|
} catch (error) {
|
||||||
|
// 不存在,继续创建
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const packageJson = {
|
||||||
|
name: `toolbox-${this.toolId}`,
|
||||||
|
version: '1.0.0',
|
||||||
|
description: `Sandbox for tool: ${this.toolId}`,
|
||||||
|
private: true,
|
||||||
|
dependencies: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 解析依赖格式 ["validator@^13.11.0", "lodash"]
|
||||||
|
for (const dep of this.dependencies) {
|
||||||
|
if (dep.includes('@')) {
|
||||||
|
const [name, version] = dep.split('@');
|
||||||
|
packageJson.dependencies[name] = version;
|
||||||
|
} else {
|
||||||
|
packageJson.dependencies[dep] = 'latest';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行pnpm安装
|
||||||
|
*/
|
||||||
|
async runPnpmInstall() {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// 获取内置pnpm路径 - 直接从node_modules获取
|
||||||
|
const pnpmModulePath = require.resolve('pnpm');
|
||||||
|
const pnpmBinPath = path.join(path.dirname(pnpmModulePath), 'bin', 'pnpm.cjs');
|
||||||
|
|
||||||
|
const pnpm = spawn('node', [pnpmBinPath, 'install'], {
|
||||||
|
cwd: this.sandboxPath,
|
||||||
|
stdio: 'pipe'
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
|
||||||
|
pnpm.stdout.on('data', (data) => {
|
||||||
|
stdout += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
pnpm.stderr.on('data', (data) => {
|
||||||
|
stderr += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
pnpm.on('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve({ stdout, stderr });
|
||||||
|
} else {
|
||||||
|
reject(new Error(`pnpm install failed with code ${code}: ${stderr}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
pnpm.on('error', (error) => {
|
||||||
|
reject(new Error(`Failed to spawn pnpm: ${error.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建执行沙箱环境
|
||||||
|
*/
|
||||||
|
async createExecutionSandbox() {
|
||||||
|
this.sandboxContext = this.createSmartSandbox();
|
||||||
|
|
||||||
|
// 在智能沙箱中重新加载工具
|
||||||
|
const script = new vm.Script(this.toolContent, { filename: `${this.toolId}.js` });
|
||||||
|
const context = vm.createContext(this.sandboxContext);
|
||||||
|
|
||||||
|
script.runInContext(context);
|
||||||
|
const exported = context.module.exports;
|
||||||
|
|
||||||
|
if (typeof exported === 'function') {
|
||||||
|
this.toolInstance = new exported();
|
||||||
|
} else if (typeof exported === 'object') {
|
||||||
|
this.toolInstance = exported;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建基础沙箱
|
||||||
|
*/
|
||||||
|
createBasicSandbox() {
|
||||||
|
return {
|
||||||
|
require: require,
|
||||||
|
module: { exports: {} },
|
||||||
|
exports: {},
|
||||||
|
console: console,
|
||||||
|
Buffer: Buffer,
|
||||||
|
process: {
|
||||||
|
env: process.env,
|
||||||
|
hrtime: process.hrtime
|
||||||
|
},
|
||||||
|
setTimeout: setTimeout,
|
||||||
|
clearTimeout: clearTimeout,
|
||||||
|
setInterval: setInterval,
|
||||||
|
clearInterval: clearInterval,
|
||||||
|
Object: Object,
|
||||||
|
Array: Array,
|
||||||
|
String: String,
|
||||||
|
Number: Number,
|
||||||
|
Boolean: Boolean,
|
||||||
|
Date: Date,
|
||||||
|
JSON: JSON,
|
||||||
|
Math: Math,
|
||||||
|
RegExp: RegExp,
|
||||||
|
Error: Error,
|
||||||
|
URL: URL
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建智能沙箱(支持依赖)
|
||||||
|
*/
|
||||||
|
createSmartSandbox() {
|
||||||
|
return {
|
||||||
|
require: (moduleName) => {
|
||||||
|
try {
|
||||||
|
// 优先从沙箱目录查找依赖
|
||||||
|
return require(require.resolve(moduleName, {
|
||||||
|
paths: [
|
||||||
|
path.join(this.sandboxPath, 'node_modules'),
|
||||||
|
this.sandboxPath,
|
||||||
|
process.cwd() + '/node_modules'
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
// 回退到默认require
|
||||||
|
return require(moduleName);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
module: { exports: {} },
|
||||||
|
exports: {},
|
||||||
|
console: console,
|
||||||
|
Buffer: Buffer,
|
||||||
|
process: {
|
||||||
|
env: process.env,
|
||||||
|
hrtime: process.hrtime
|
||||||
|
},
|
||||||
|
setTimeout: setTimeout,
|
||||||
|
clearTimeout: clearTimeout,
|
||||||
|
setInterval: setInterval,
|
||||||
|
clearInterval: clearInterval,
|
||||||
|
Object: Object,
|
||||||
|
Array: Array,
|
||||||
|
String: String,
|
||||||
|
Number: Number,
|
||||||
|
Boolean: Boolean,
|
||||||
|
Date: Date,
|
||||||
|
JSON: JSON,
|
||||||
|
Math: Math,
|
||||||
|
RegExp: RegExp,
|
||||||
|
Error: Error,
|
||||||
|
URL: URL
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 参数验证
|
||||||
|
*/
|
||||||
|
async validateParameters(parameters) {
|
||||||
|
if (typeof this.toolInstance.validate === 'function') {
|
||||||
|
const result = this.toolInstance.validate(parameters);
|
||||||
|
|
||||||
|
if (typeof result === 'boolean' && !result) {
|
||||||
|
throw new Error('Parameter validation failed');
|
||||||
|
} else if (result && typeof result === 'object' && !result.valid) {
|
||||||
|
throw new Error(`Parameter validation failed: ${result.errors?.join(', ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在沙箱中执行工具
|
||||||
|
*/
|
||||||
|
async executeInSandbox(parameters) {
|
||||||
|
if (!this.toolInstance || typeof this.toolInstance.execute !== 'function') {
|
||||||
|
throw new Error(`Tool ${this.toolId} does not have execute method`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.toolInstance.execute(parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取分析结果
|
||||||
|
*/
|
||||||
|
getAnalysisResult() {
|
||||||
|
return {
|
||||||
|
toolId: this.toolId,
|
||||||
|
dependencies: this.dependencies,
|
||||||
|
sandboxPath: this.sandboxPath,
|
||||||
|
hasMetadata: typeof this.toolInstance?.getMetadata === 'function',
|
||||||
|
hasSchema: typeof this.toolInstance?.getSchema === 'function'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理沙箱资源
|
||||||
|
*/
|
||||||
|
async cleanup() {
|
||||||
|
// 可选:清理临时文件、关闭连接等
|
||||||
|
this.sandboxContext = null;
|
||||||
|
this.toolInstance = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取工具元信息
|
||||||
|
*/
|
||||||
|
getToolMetadata() {
|
||||||
|
if (this.toolInstance && typeof this.toolInstance.getMetadata === 'function') {
|
||||||
|
return this.toolInstance.getMetadata();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取工具Schema
|
||||||
|
*/
|
||||||
|
getToolSchema() {
|
||||||
|
if (this.toolInstance && typeof this.toolInstance.getSchema === 'function') {
|
||||||
|
return this.toolInstance.getSchema();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ToolSandbox;
|
||||||
Reference in New Issue
Block a user