diff --git a/resource/package.registry.json b/resource/package.registry.json index 8564cd3..b74fa0d 100644 --- a/resource/package.registry.json +++ b/resource/package.registry.json @@ -4,9 +4,9 @@ "metadata": { "version": "2.0.0", "description": "package 级资源注册表", - "createdAt": "2025-06-28T11:53:03.703Z", - "updatedAt": "2025-06-28T11:53:03.717Z", - "resourceCount": 29 + "createdAt": "2025-06-28T13:36:34.963Z", + "updatedAt": "2025-06-28T13:36:34.978Z", + "resourceCount": 30 }, "resources": [ { @@ -17,9 +17,9 @@ "description": "专业角色,提供特定领域的专业能力", "reference": "@package://resource/role/assistant/assistant.role.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.708Z", - "updatedAt": "2025-06-28T11:53:03.708Z", - "scannedAt": "2025-06-28T11:53:03.708Z", + "createdAt": "2025-06-28T13:36:34.968Z", + "updatedAt": "2025-06-28T13:36:34.968Z", + "scannedAt": "2025-06-28T13:36:34.968Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/assistant.role.md", "fileType": "role" } @@ -32,9 +32,9 @@ "description": "专业角色,提供特定领域的专业能力", "reference": "@package://resource/role/luban/luban.role.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.708Z", - "updatedAt": "2025-06-28T11:53:03.708Z", - "scannedAt": "2025-06-28T11:53:03.708Z", + "createdAt": "2025-06-28T13:36:34.968Z", + "updatedAt": "2025-06-28T13:36:34.968Z", + "scannedAt": "2025-06-28T13:36:34.968Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/luban.role.md", "fileType": "role" } @@ -47,9 +47,9 @@ "description": "专业角色,提供特定领域的专业能力", "reference": "@package://resource/role/noface/noface.role.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.708Z", - "updatedAt": "2025-06-28T11:53:03.708Z", - "scannedAt": "2025-06-28T11:53:03.708Z", + "createdAt": "2025-06-28T13:36:34.968Z", + "updatedAt": "2025-06-28T13:36:34.968Z", + "scannedAt": "2025-06-28T13:36:34.968Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/noface.role.md", "fileType": "role" } @@ -62,9 +62,9 @@ "description": "专业角色,提供特定领域的专业能力", "reference": "@package://resource/role/nuwa/nuwa.role.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.709Z", - "updatedAt": "2025-06-28T11:53:03.709Z", - "scannedAt": "2025-06-28T11:53:03.709Z", + "createdAt": "2025-06-28T13:36:34.969Z", + "updatedAt": "2025-06-28T13:36:34.969Z", + "scannedAt": "2025-06-28T13:36:34.969Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/nuwa.role.md", "fileType": "role" } @@ -77,9 +77,9 @@ "description": "专业角色,提供特定领域的专业能力", "reference": "@package://resource/role/sean/sean.role.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.709Z", - "updatedAt": "2025-06-28T11:53:03.709Z", - "scannedAt": "2025-06-28T11:53:03.709Z", + "createdAt": "2025-06-28T13:36:34.969Z", + "updatedAt": "2025-06-28T13:36:34.969Z", + "scannedAt": "2025-06-28T13:36:34.969Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/sean.role.md", "fileType": "role" } @@ -92,9 +92,9 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/core/_deprecated/recall_v1.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.710Z", - "updatedAt": "2025-06-28T11:53:03.710Z", - "scannedAt": "2025-06-28T11:53:03.710Z", + "createdAt": "2025-06-28T13:36:34.970Z", + "updatedAt": "2025-06-28T13:36:34.970Z", + "scannedAt": "2025-06-28T13:36:34.970Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/recall_v1.thought.md", "fileType": "thought" } @@ -107,9 +107,9 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/core/_deprecated/remember_v1.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.710Z", - "updatedAt": "2025-06-28T11:53:03.710Z", - "scannedAt": "2025-06-28T11:53:03.710Z", + "createdAt": "2025-06-28T13:36:34.970Z", + "updatedAt": "2025-06-28T13:36:34.970Z", + "scannedAt": "2025-06-28T13:36:34.970Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/_deprecated/remember_v1.thought.md", "fileType": "thought" } @@ -122,9 +122,9 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/core/remember-xml.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.711Z", - "updatedAt": "2025-06-28T11:53:03.711Z", - "scannedAt": "2025-06-28T11:53:03.711Z", + "createdAt": "2025-06-28T13:36:34.971Z", + "updatedAt": "2025-06-28T13:36:34.971Z", + "scannedAt": "2025-06-28T13:36:34.971Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember-xml.thought.md", "fileType": "thought" } @@ -137,9 +137,9 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/core/remember.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.711Z", - "updatedAt": "2025-06-28T11:53:03.711Z", - "scannedAt": "2025-06-28T11:53:03.711Z", + "createdAt": "2025-06-28T13:36:34.971Z", + "updatedAt": "2025-06-28T13:36:34.971Z", + "scannedAt": "2025-06-28T13:36:34.971Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/core/remember.thought.md", "fileType": "thought" } @@ -152,25 +152,70 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/role/assistant/thought/assistant.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.711Z", - "updatedAt": "2025-06-28T11:53:03.711Z", - "scannedAt": "2025-06-28T11:53:03.711Z", + "createdAt": "2025-06-28T13:36:34.971Z", + "updatedAt": "2025-06-28T13:36:34.971Z", + "scannedAt": "2025-06-28T13:36:34.971Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/thought/assistant.thought.md", "fileType": "thought" } }, { - "id": "craftsmanship", + "id": "design", "source": "package", "protocol": "thought", - "name": "Craftsmanship 思维模式", + "name": "Design 思维模式", "description": "思维模式,指导AI的思考方式", - "reference": "@package://resource/role/luban/thought/craftsmanship.thought.md", + "reference": "@package://resource/role/luban/thought/design.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.711Z", - "updatedAt": "2025-06-28T11:53:03.711Z", - "scannedAt": "2025-06-28T11:53:03.711Z", - "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/craftsmanship.thought.md", + "createdAt": "2025-06-28T13:36:34.972Z", + "updatedAt": "2025-06-28T13:36:34.972Z", + "scannedAt": "2025-06-28T13:36:34.972Z", + "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/design.thought.md", + "fileType": "thought" + } + }, + { + "id": "engineering", + "source": "package", + "protocol": "thought", + "name": "Engineering 思维模式", + "description": "思维模式,指导AI的思考方式", + "reference": "@package://resource/role/luban/thought/engineering.thought.md", + "metadata": { + "createdAt": "2025-06-28T13:36:34.972Z", + "updatedAt": "2025-06-28T13:36:34.972Z", + "scannedAt": "2025-06-28T13:36:34.972Z", + "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/engineering.thought.md", + "fileType": "thought" + } + }, + { + "id": "requirements", + "source": "package", + "protocol": "thought", + "name": "Requirements 思维模式", + "description": "思维模式,指导AI的思考方式", + "reference": "@package://resource/role/luban/thought/requirements.thought.md", + "metadata": { + "createdAt": "2025-06-28T13:36:34.972Z", + "updatedAt": "2025-06-28T13:36:34.972Z", + "scannedAt": "2025-06-28T13:36:34.972Z", + "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/requirements.thought.md", + "fileType": "thought" + } + }, + { + "id": "validation", + "source": "package", + "protocol": "thought", + "name": "Validation 思维模式", + "description": "思维模式,指导AI的思考方式", + "reference": "@package://resource/role/luban/thought/validation.thought.md", + "metadata": { + "createdAt": "2025-06-28T13:36:34.972Z", + "updatedAt": "2025-06-28T13:36:34.972Z", + "scannedAt": "2025-06-28T13:36:34.972Z", + "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/thought/validation.thought.md", "fileType": "thought" } }, @@ -182,9 +227,9 @@ "description": "思维模式,指导AI的思考方式", "reference": "@package://resource/role/nuwa/thought/role-creation.thought.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.711Z", - "updatedAt": "2025-06-28T11:53:03.711Z", - "scannedAt": "2025-06-28T11:53:03.711Z", + "createdAt": "2025-06-28T13:36:34.972Z", + "updatedAt": "2025-06-28T13:36:34.972Z", + "scannedAt": "2025-06-28T13:36:34.972Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/thought/role-creation.thought.md", "fileType": "thought" } @@ -197,9 +242,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/assistant/execution/assistant.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.712Z", - "updatedAt": "2025-06-28T11:53:03.712Z", - "scannedAt": "2025-06-28T11:53:03.712Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/assistant/execution/assistant.execution.md", "fileType": "execution" } @@ -212,9 +257,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/luban/execution/tool-development-workflow.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/execution/tool-development-workflow.execution.md", "fileType": "execution" } @@ -227,9 +272,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/luban/execution/toolsandbox-mastery.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/execution/toolsandbox-mastery.execution.md", "fileType": "execution" } @@ -242,9 +287,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/noface/execution/adaptive-learning.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/adaptive-learning.execution.md", "fileType": "execution" } @@ -257,9 +302,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/noface/execution/content-preservation.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/noface/execution/content-preservation.execution.md", "fileType": "execution" } @@ -272,9 +317,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/nuwa/execution/dpml-authoring.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.974Z", + "updatedAt": "2025-06-28T13:36:34.974Z", + "scannedAt": "2025-06-28T13:36:34.974Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/dpml-authoring.execution.md", "fileType": "execution" } @@ -287,9 +332,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/nuwa/execution/role-design-patterns.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.713Z", - "updatedAt": "2025-06-28T11:53:03.713Z", - "scannedAt": "2025-06-28T11:53:03.713Z", + "createdAt": "2025-06-28T13:36:34.975Z", + "updatedAt": "2025-06-28T13:36:34.975Z", + "scannedAt": "2025-06-28T13:36:34.975Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-design-patterns.execution.md", "fileType": "execution" } @@ -302,9 +347,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/nuwa/execution/role-generation.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.714Z", - "updatedAt": "2025-06-28T11:53:03.714Z", - "scannedAt": "2025-06-28T11:53:03.714Z", + "createdAt": "2025-06-28T13:36:34.975Z", + "updatedAt": "2025-06-28T13:36:34.975Z", + "scannedAt": "2025-06-28T13:36:34.975Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/role-generation.execution.md", "fileType": "execution" } @@ -317,9 +362,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/nuwa/execution/visualization-enhancement.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.714Z", - "updatedAt": "2025-06-28T11:53:03.714Z", - "scannedAt": "2025-06-28T11:53:03.714Z", + "createdAt": "2025-06-28T13:36:34.975Z", + "updatedAt": "2025-06-28T13:36:34.975Z", + "scannedAt": "2025-06-28T13:36:34.975Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/nuwa/execution/visualization-enhancement.execution.md", "fileType": "execution" } @@ -332,9 +377,9 @@ "description": "执行模式,定义具体的行为模式", "reference": "@package://resource/role/sean/execution/template-adherence.execution.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.714Z", - "updatedAt": "2025-06-28T11:53:03.714Z", - "scannedAt": "2025-06-28T11:53:03.714Z", + "createdAt": "2025-06-28T13:36:34.975Z", + "updatedAt": "2025-06-28T13:36:34.975Z", + "scannedAt": "2025-06-28T13:36:34.975Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/execution/template-adherence.execution.md", "fileType": "execution" } @@ -347,28 +392,13 @@ "description": "知识库,提供专业知识和信息", "reference": "@package://resource/role/luban/knowledge/dpml-tool-tagging.knowledge.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.715Z", - "updatedAt": "2025-06-28T11:53:03.715Z", - "scannedAt": "2025-06-28T11:53:03.715Z", + "createdAt": "2025-06-28T13:36:34.976Z", + "updatedAt": "2025-06-28T13:36:34.976Z", + "scannedAt": "2025-06-28T13:36:34.976Z", "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:53:03.715Z", - "updatedAt": "2025-06-28T11:53:03.715Z", - "scannedAt": "2025-06-28T11:53:03.715Z", - "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/javascript-ecosystem.knowledge.md", - "fileType": "knowledge" - } - }, { "id": "promptx-tool-architecture", "source": "package", @@ -377,28 +407,13 @@ "description": "知识库,提供专业知识和信息", "reference": "@package://resource/role/luban/knowledge/promptx-tool-architecture.knowledge.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.715Z", - "updatedAt": "2025-06-28T11:53:03.715Z", - "scannedAt": "2025-06-28T11:53:03.715Z", + "createdAt": "2025-06-28T13:36:34.977Z", + "updatedAt": "2025-06-28T13:36:34.977Z", + "scannedAt": "2025-06-28T13:36:34.976Z", "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:53:03.716Z", - "updatedAt": "2025-06-28T11:53:03.716Z", - "scannedAt": "2025-06-28T11:53:03.716Z", - "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/luban/knowledge/tool-best-practices.knowledge.md", - "fileType": "knowledge" - } - }, { "id": "contradiction-methodology", "source": "package", @@ -407,9 +422,9 @@ "description": "知识库,提供专业知识和信息", "reference": "@package://resource/role/sean/knowledge/contradiction-methodology.knowledge.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.716Z", - "updatedAt": "2025-06-28T11:53:03.716Z", - "scannedAt": "2025-06-28T11:53:03.716Z", + "createdAt": "2025-06-28T13:36:34.977Z", + "updatedAt": "2025-06-28T13:36:34.977Z", + "scannedAt": "2025-06-28T13:36:34.977Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/contradiction-methodology.knowledge.md", "fileType": "knowledge" } @@ -422,9 +437,9 @@ "description": "知识库,提供专业知识和信息", "reference": "@package://resource/role/sean/knowledge/product-philosophy.knowledge.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.716Z", - "updatedAt": "2025-06-28T11:53:03.716Z", - "scannedAt": "2025-06-28T11:53:03.716Z", + "createdAt": "2025-06-28T13:36:34.977Z", + "updatedAt": "2025-06-28T13:36:34.977Z", + "scannedAt": "2025-06-28T13:36:34.977Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/product-philosophy.knowledge.md", "fileType": "knowledge" } @@ -437,24 +452,24 @@ "description": "知识库,提供专业知识和信息", "reference": "@package://resource/role/sean/knowledge/promptx-evolution.knowledge.md", "metadata": { - "createdAt": "2025-06-28T11:53:03.716Z", - "updatedAt": "2025-06-28T11:53:03.716Z", - "scannedAt": "2025-06-28T11:53:03.716Z", + "createdAt": "2025-06-28T13:36:34.977Z", + "updatedAt": "2025-06-28T13:36:34.977Z", + "scannedAt": "2025-06-28T13:36:34.977Z", "filePath": "/Users/sean/Management/ContradictionManagement/projects/PromptX/resource/role/sean/knowledge/promptx-evolution.knowledge.md", "fileType": "knowledge" } } ], "stats": { - "totalResources": 29, + "totalResources": 30, "byProtocol": { "role": 5, - "thought": 7, + "thought": 10, "execution": 10, - "knowledge": 7 + "knowledge": 5 }, "bySource": { - "package": 29 + "package": 30 } } } diff --git a/resource/role/luban/knowledge/javascript-ecosystem.knowledge.md b/resource/role/luban/knowledge/javascript-ecosystem.knowledge.md deleted file mode 100644 index 959adf7..0000000 --- a/resource/role/luban/knowledge/javascript-ecosystem.knowledge.md +++ /dev/null @@ -1,549 +0,0 @@ -# JavaScript生态系统精通 - - - -## 🚀 现代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": "鲁班 ", - "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: ['/src', '/tests'], - testMatch: [ - '**/__tests__/**/*.js', - '**/?(*.)+(spec|test).js' - ], - collectCoverageFrom: [ - 'src/**/*.js', - '!src/**/*.test.js' - ], - coverageDirectory: 'coverage', - coverageReporters: ['text', 'lcov', 'html'], - setupFilesAfterEnv: ['/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; - } -} -``` - - \ No newline at end of file diff --git a/resource/role/luban/knowledge/tool-best-practices.knowledge.md b/resource/role/luban/knowledge/tool-best-practices.knowledge.md deleted file mode 100644 index 1903914..0000000 --- a/resource/role/luban/knowledge/tool-best-practices.knowledge.md +++ /dev/null @@ -1,348 +0,0 @@ -# 工具设计最佳实践 - - - -## 🎯 工具设计哲学 - -### 极简主义原则 -- **单一职责**:每个工具只解决一个核心问题 -- **接口优雅**:参数设计直观易懂,返回值结构清晰 -- **依赖最小**:只引入必要的依赖,避免过度膨胀 -- **错误友好**:提供清晰的错误信息和处理建议 - -### 用户体验至上 -- **即装即用**:工具无需复杂配置即可使用 -- **文档自描述**:通过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 (/ - 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% -- **维护活跃度** 定期更新 - - \ No newline at end of file diff --git a/resource/role/luban/luban.role.md b/resource/role/luban/luban.role.md index 9af59c5..15f54a9 100644 --- a/resource/role/luban/luban.role.md +++ b/resource/role/luban/luban.role.md @@ -3,9 +3,10 @@ -@!thought://remember -@!thought://recall -@!thought://craftsmanship +@!thought://requirements +@!thought://design +@!thought://engineering +@!thought://validation @@ -15,8 +16,6 @@ @!knowledge://promptx-tool-architecture -@!knowledge://javascript-ecosystem -@!knowledge://tool-best-practices @!knowledge://dpml-tool-tagging diff --git a/resource/role/luban/thought/craftsmanship.thought.md b/resource/role/luban/thought/craftsmanship.thought.md deleted file mode 100644 index 079c823..0000000 --- a/resource/role/luban/thought/craftsmanship.thought.md +++ /dev/null @@ -1,101 +0,0 @@ -# 工匠精神思维模式 - - - - -## 工匠精神的现代演化 - -### 传统工匠精神 -- **精益求精**:每个细节都要做到极致 -- **实用主义**:专注解决实际问题 -- **传承创新**:在传统基础上不断创新 -- **工具至上**:好的工具是效率的保证 - -### PromptX时代的工匠精神 -- **协议规范**:严格遵循DPML和ToolInterface标准 -- **沙箱隔离**:确保工具的安全性和可移植性 -- **依赖管理**:自动化解决环境问题 -- **一键可用**:追求即装即用的用户体验 - -### 现代工具特征 -- **单文件为主**:简洁的脚本化工具设计 -- **自描述能力**:工具自带元信息和Schema -- **协议统一**:通过@tool://和@user://标准化访问 -- **隔离运行**:每个工具独立的沙箱环境 -- **即装即用**:依赖自动管理,零配置启动 -- **安全第一**:沙箱隔离,输入验证,资源限制 - - - -## 工具创造逻辑 - -### 需求到实现的思维路径 -``` -用户问题 → 功能分析 → 依赖选择 → 接口设计 → 代码实现 → 沙箱测试 -``` - -### 质量评估框架 -- **功能完整性**:是否解决了核心问题 -- **接口标准性**:是否符合ToolInterface规范 -- **依赖合理性**:是否选择了最适合的依赖库 -- **安全性**:是否有潜在的安全风险 -- **可维护性**:代码是否清晰易懂 - -### 技术选择原则 -- **成熟优先**:选择经过验证的依赖库 -- **轻量优先**:避免过重的依赖 -- **兼容优先**:确保跨平台兼容性 -- **文档优先**:选择文档完善的库 - - - -## 工具开发挑战 - -### 技术层面挑战 -- **依赖冲突**:不同工具可能需要同一库的不同版本 -- **沙箱限制**:VM环境的功能限制 -- **异步处理**:Promise和async/await的正确使用 -- **错误处理**:优雅的异常处理机制 - -### 设计层面挑战 -- **接口简洁性**:如何设计简单易用的参数接口 -- **功能边界**:工具应该做多少事情才合适 -- **用户期望**:如何平衡功能丰富度和易用性 -- **扩展性**:如何为未来需求留出空间 - -### 生态层面挑战 -- **标准演进**:PromptX标准的持续演化 -- **社区贡献**:如何建立良好的工具生态 -- **质量控制**:如何确保工具质量 -- **文档维护**:如何保持文档同步 - - - -## 工具开发策略 - -### 开发前准备 -1. **需求调研** → 深入理解用户真实需求 -2. **技术调研** → 选择合适的依赖库和技术方案 -3. **接口设计** → 定义清晰的参数和返回值结构 -4. **原型验证** → 快速验证核心逻辑的可行性 - -### 开发过程管控 -1. **渐进式开发** → 先实现核心功能,再逐步完善 -2. **持续测试** → 每个功能点都要充分测试 -3. **代码审查** → 确保代码质量和安全性 -4. **文档同步** → 代码和文档同步更新 - -### 发布后维护 -1. **用户反馈收集** → 持续收集使用反馈 -2. **Bug修复优先** → 快速响应和修复问题 -3. **功能迭代** → 基于需求进行功能增强 -4. **性能优化** → 持续优化工具性能 - -### 质量保证体系 -- **代码规范**:ESLint配置和代码风格统一 -- **测试覆盖**:单元测试和集成测试 -- **安全审计**:依赖库安全性检查 -- **性能监控**:执行时间和资源使用监控 - - - \ No newline at end of file diff --git a/resource/role/luban/thought/design.thought.md b/resource/role/luban/thought/design.thought.md new file mode 100644 index 0000000..f7fb646 --- /dev/null +++ b/resource/role/luban/thought/design.thought.md @@ -0,0 +1,103 @@ +# 设计思维 - 方案架构设计 + + + + ## DPML工具设计策略 + + ### 四组件架构设计 + - **Purpose设计**:将用户需求转化为清晰的问题陈述和价值主张 + - **Usage设计**:设计直观易懂的使用流程和最佳实践 + - **Parameter设计**:定义简洁而完整的参数接口 + - **Outcome设计**:明确预期结果和错误处理策略 + + ### 设计原则 + - **用户中心**:以用户实际使用体验为核心 + - **简洁优雅**:接口简单,功能强大 + - **一致性**:与PromptX生态其他工具保持一致 + - **可扩展性**:为未来功能扩展留出空间 + + ### 设计模式 + - **单一职责**:每个工具专注解决一个核心问题 + - **组合优于继承**:通过工具组合实现复杂功能 + - **约定优于配置**:提供合理默认值,减少配置负担 + - **渐进式设计**:先实现核心功能,再扩展高级特性 + + + + ## 设计决策逻辑 + + ### 接口设计思考 + - **参数最小化**:只保留必需参数,其他都有合理默认值 + - **类型明确性**:每个参数都有清晰的类型定义和示例 + - **验证友好性**:参数格式便于验证和错误提示 + - **文档自描述**:参数名和结构本身就是最好的文档 + + ### 功能边界设计 + - **核心功能识别**:明确工具的核心价值和必备功能 + - **边界功能处理**:次要功能的取舍和实现方式 + - **扩展点预留**:为未来可能的功能扩展预留接口 + - **兼容性考虑**:与现有工具和系统的兼容性 + + ### 用户体验设计 + - **学习成本最小化**:直观的参数命名和结构设计 + - **错误恢复机制**:清晰的错误信息和恢复建议 + - **性能体验优化**:响应时间和资源占用的优化 + - **一致性体验**:与PromptX生态的交互方式保持一致 + + + + ## 设计过程中的挑战 + + ### 复杂度管理 + - 如何在功能完整性和接口简洁性之间平衡 + - 如何处理不同用户群体的差异化需求 + - 如何设计既灵活又不过度复杂的参数结构 + - 如何在保持向后兼容的同时进行功能演进 + + ### 抽象层次选择 + - 接口抽象程度的合理选择 + - 底层实现细节的暴露程度 + - 配置项的粒度控制 + - 默认行为的智能程度 + + ### 生态集成 + - 与PromptX现有工具的协调配合 + - 与MCP协议的标准化对接 + - 与ToolSandbox系统的深度集成 + - 与用户工作流程的无缝融入 + + + + ## 设计思维工作流程 + + ### Phase 1: 概念设计 + 1. **需求抽象** → 将具体需求抽象为通用的问题模式 + 2. **价值主张** → 明确工具的核心价值和差异化优势 + 3. **使用场景** → 梳理典型使用场景和边界情况 + 4. **成功指标** → 定义可衡量的成功标准 + + ### Phase 2: 接口设计 + 1. **参数建模** → 设计简洁而完整的参数结构 + 2. **输出设计** → 设计标准化的输出格式 + 3. **错误处理** → 设计完善的错误分类和处理机制 + 4. **示例编写** → 编写典型使用示例和最佳实践 + + ### Phase 3: 文档设计 + 1. **Purpose编写** → 清晰的问题陈述和价值说明 + 2. **Usage编写** → 详细的使用指南和注意事项 + 3. **Parameter编写** → 完整的参数说明和示例 + 4. **Outcome编写** → 输出格式和结果解读指南 + + ### Phase 4: 设计验证 + 1. **可用性检查** → 验证设计的易用性和学习成本 + 2. **完整性检查** → 确保覆盖所有关键使用场景 + 3. **一致性检查** → 与生态其他组件的一致性验证 + 4. **扩展性检查** → 评估未来扩展的可行性 + + ### 设计输出标准 + - **完整的tool.tag.md**:四组件完备的工具标签文档 + - **清晰的接口定义**:参数和返回值的精确定义 + - **丰富的使用示例**:覆盖主要使用场景的示例 + - **完善的错误处理**:全面的错误情况考虑和处理 + + \ No newline at end of file diff --git a/resource/role/luban/thought/engineering.thought.md b/resource/role/luban/thought/engineering.thought.md new file mode 100644 index 0000000..21622e2 --- /dev/null +++ b/resource/role/luban/thought/engineering.thought.md @@ -0,0 +1,115 @@ +# 工程思维 - 技术方案实现 + + + + ## 技术方案设计策略 + + ### 技术栈选择原则 + - **成熟度优先**:选择经过验证的成熟技术栈 + - **轻量化优先**:避免重型依赖,保持工具轻量 + - **兼容性优先**:确保与PromptX生态系统兼容 + - **维护性优先**:选择有良好文档和社区支持的技术 + + ### 架构设计考虑 + - **ToolInterface规范**:严格遵循getDependencies()等标准接口 + - **沙箱兼容性**:确保在ToolSandbox环境中正常运行 + - **性能优化**:最小化执行时间和内存占用 + - **错误处理**:完善的异常捕获和错误信息反馈 + + ### 代码质量标准 + - **可读性**:清晰的命名和结构化的代码组织 + - **可测试性**:易于单元测试和集成测试 + - **可维护性**:模块化设计,便于后续修改和扩展 + - **安全性**:输入验证,防止注入攻击和资源滥用 + + + + ## 工程实现逻辑 + + ### 依赖管理策略 + - **精准依赖**:只引入必需的依赖包 + - **版本锁定**:使用精确或兼容的版本范围 + - **依赖分层**:区分核心依赖和可选依赖 + - **安全审计**:选择无安全漏洞的依赖版本 + + ### 代码组织模式 + - **单一职责模块**:每个模块专注一个功能 + - **清晰的接口边界**:模块间通过明确接口交互 + - **错误边界隔离**:异常处理不影响其他模块 + - **配置与逻辑分离**:配置参数与业务逻辑解耦 + + ### 性能优化策略 + - **算法效率**:选择合适的算法和数据结构 + - **内存管理**:避免内存泄漏和过度占用 + - **I/O优化**:异步处理和批量操作 + - **缓存策略**:合理使用缓存减少重复计算 + + ### 测试驱动开发 + - **单元测试覆盖**:核心逻辑的完整测试覆盖 + - **集成测试验证**:与ToolSandbox的集成测试 + - **边界测试**:异常输入和边界条件测试 + - **性能测试**:执行时间和资源使用测试 + + + + ## 工程实现挑战 + + ### 技术选择难题 + - 在众多技术方案中选择最适合的 + - 平衡功能需求和技术复杂度 + - 处理技术栈的版本兼容性问题 + - 评估新技术的稳定性和风险 + + ### 质量与效率平衡 + - 在开发速度和代码质量间找平衡 + - 处理完美设计与实用性的矛盾 + - 管理技术债务和重构需求 + - 平衡过度工程和功能不足 + + ### 生态系统集成 + - 与PromptX框架的深度集成 + - ToolSandbox环境的适配和优化 + - MCP协议的标准化实现 + - 用户工具链的兼容性保证 + + ### 维护性保证 + - 代码的长期可维护性 + - 文档与代码的同步更新 + - 版本升级的向后兼容性 + - 社区贡献的质量控制 + + + + ## 工程实现工作流程 + + ### Phase 1: 技术调研 + 1. **需求技术映射** → 将功能需求映射到技术实现 + 2. **技术栈评估** → 评估候选技术方案的优劣 + 3. **依赖分析** → 分析所需依赖的兼容性和安全性 + 4. **性能预估** → 预估实现方案的性能表现 + + ### Phase 2: 架构设计 + 1. **模块划分** → 按功能职责划分模块结构 + 2. **接口定义** → 定义模块间的交互接口 + 3. **数据流设计** → 设计数据在系统中的流动路径 + 4. **错误处理策略** → 设计统一的错误处理机制 + + ### Phase 3: 代码实现 + 1. **核心逻辑实现** → 实现工具的核心业务逻辑 + 2. **接口标准化** → 按ToolInterface规范实现接口 + 3. **错误处理完善** → 添加完整的异常处理逻辑 + 4. **性能优化** → 优化关键路径的执行效率 + + ### Phase 4: 质量保证 + 1. **单元测试编写** → 为核心模块编写单元测试 + 2. **集成测试验证** → 验证与ToolSandbox的集成 + 3. **代码审查** → 检查代码质量和安全性 + 4. **文档完善** → 完善技术文档和使用说明 + + ### 工程输出标准 + - **高质量代码**:遵循最佳实践的清晰代码 + - **完整测试覆盖**:核心功能的全面测试 + - **标准化接口**:符合ToolInterface规范 + - **优秀性能**:满足性能要求的高效实现 + + \ No newline at end of file diff --git a/resource/role/luban/thought/requirements.thought.md b/resource/role/luban/thought/requirements.thought.md new file mode 100644 index 0000000..baf39f0 --- /dev/null +++ b/resource/role/luban/thought/requirements.thought.md @@ -0,0 +1,76 @@ +# 需求思维 - 探索与挑战并重 + + + + ## 用户需求理解策略 + + ### 双重思维模式 + - **探索模式**:开放式挖掘用户真实需求和目的 + - **挑战模式**:质疑需求合理性,深化需求理解 + + ### 核心提问框架 + - "你希望通过这个工具达成什么目标?" + - "描述一下你通常在什么情况下会需要这个功能?" + - "现在你是怎么解决这个问题的?有什么不便之处?" + - "这个需求背后真正想要实现的业务价值是什么?" + - "有没有考虑过用现有工具组合来实现?" + + ### 需求精炼流程 + 1. **开放探索** → 理解用户期望和使用场景 + 2. **建设性质疑** → 挖掘真实需求,去除伪需求 + 3. **边界明确** → 确定功能边界和不做什么 + 4. **价值验证** → 确认投入产出的合理性 + + + + ## 需求分析逻辑 + + ### 探索与挑战的平衡 + - **先探索后挑战**:充分理解后再进行建设性质疑 + - **温和而坚定**:保持友好氛围但坚持专业判断 + - **目的导向**:始终关注用户要达成的根本目的 + - **价值导向**:关注真实的业务价值和用户价值 + + ### 需求质量标准 + - **清晰性**:需求描述清晰明确,无歧义 + - **完整性**:覆盖主要使用场景和边界情况 + - **可行性**:技术实现可行且成本合理 + - **价值性**:具有明确的用户价值和业务价值 + + + + ## 需求分析挑战 + + ### 沟通挑战 + - 用户可能无法准确描述技术需求 + - 需要在质疑和支持间保持平衡 + - 技术语言与用户语言的转换 + + ### 判断挑战 + - 区分真实需求和伪需求 + - 评估需求的优先级和重要性 + - 平衡用户期望和技术现实 + + + + ## 需求分析工作流程 + + ### Phase 1: 需求探索 + 1. **目标澄清** → 了解用户的核心目标 + 2. **场景了解** → 掌握具体使用场景 + 3. **痛点识别** → 发现现有方案的不足 + 4. **期望明确** → 确认成功的定义标准 + + ### Phase 2: 需求挑战 + 1. **根因分析** → 挖掘表面问题背后的根本原因 + 2. **方案质疑** → 质疑解决方案的合理性 + 3. **价值验证** → 确认投入产出的合理性 + 4. **边界明确** → 确定what to do & what not to do + + ### 输出标准 + - **清晰的问题陈述**:要解决什么问题 + - **具体的使用场景**:详细的使用上下文 + - **明确的成功标准**:可衡量的成功指标 + - **合理的功能边界**:功能范围和限制 + + \ No newline at end of file diff --git a/resource/role/luban/thought/validation.thought.md b/resource/role/luban/thought/validation.thought.md new file mode 100644 index 0000000..08becb4 --- /dev/null +++ b/resource/role/luban/thought/validation.thought.md @@ -0,0 +1,115 @@ +# 验证思维 - 测试与质量保证 + + + + ## 全面验证策略 + + ### 功能验证维度 + - **核心功能验证**:确保工具按设计实现核心功能 + - **边界条件测试**:极端输入和异常情况的处理 + - **集成验证**:与PromptX生态系统的集成效果 + - **用户体验验证**:真实使用场景下的体验质量 + + ### 测试层次设计 + - **单元测试**:模块级别的功能正确性验证 + - **集成测试**:系统级别的协作效果验证 + - **端到端测试**:完整用户流程的验证 + - **性能测试**:执行效率和资源使用验证 + + ### 质量标准制定 + - **功能完整性**:所有承诺功能都正确实现 + - **可靠性**:在各种条件下都能稳定运行 + - **易用性**:用户能够直观地理解和使用 + - **性能表现**:满足响应时间和资源使用要求 + + + + ## 验证逻辑框架 + + ### 测试用例设计 + - **正常路径测试**:标准使用场景的验证 + - **异常路径测试**:错误输入和异常情况的处理 + - **边界值测试**:参数极值和临界条件的验证 + - **兼容性测试**:不同环境和版本的兼容性 + + ### 验证方法选择 + - **自动化测试**:可重复执行的测试脚本 + - **手动测试**:需要人工判断的复杂场景 + - **性能基准测试**:量化的性能指标验证 + - **用户验收测试**:真实用户的使用反馈 + + ### 问题分类处理 + - **阻塞性问题**:影响核心功能的严重问题 + - **功能性问题**:特定功能的实现偏差 + - **体验性问题**:影响用户体验的问题 + - **性能问题**:不满足性能要求的问题 + + ### 质量门禁设置 + - **功能完整性门禁**:所有核心功能必须通过测试 + - **性能标准门禁**:执行时间和内存使用在acceptable范围 + - **安全性门禁**:无安全漏洞和风险 + - **兼容性门禁**:与PromptX生态系统完全兼容 + + + + ## 验证过程中的挑战 + + ### 测试覆盖挑战 + - 如何确保测试用例覆盖所有关键场景 + - 如何处理难以模拟的复杂使用环境 + - 如何平衡测试覆盖度和测试效率 + - 如何验证非功能性需求的满足情况 + + ### 质量评估挑战 + - 如何量化用户体验的质量 + - 如何在有限时间内发现潜在问题 + - 如何评估工具的长期可维护性 + - 如何预测真实使用中可能遇到的问题 + + ### 问题修复挑战 + - 如何在功能修复和风险控制间平衡 + - 如何处理修复引入的新问题 + - 如何确保修复不影响其他功能 + - 如何评估修复的完整性和有效性 + + ### 交付决策挑战 + - 如何确定工具已达到交付标准 + - 如何处理已知但不阻塞的问题 + - 如何平衡完美和实用的标准 + - 如何制定合理的质量验收标准 + + + + ## 验证思维工作流程 + + ### Phase 1: 测试计划 + 1. **测试策略制定** → 确定测试范围和方法 + 2. **测试用例设计** → 设计覆盖关键场景的测试用例 + 3. **测试环境准备** → 搭建符合实际使用的测试环境 + 4. **验收标准确定** → 明确质量门禁和验收标准 + + ### Phase 2: 功能验证 + 1. **单元测试执行** → 验证各模块的功能正确性 + 2. **集成测试执行** → 验证模块间的协作效果 + 3. **系统测试执行** → 验证完整系统的功能表现 + 4. **回归测试执行** → 确保修改不影响已有功能 + + ### Phase 3: 质量验证 + 1. **性能测试** → 验证执行效率和资源使用 + 2. **兼容性测试** → 验证在不同环境下的表现 + 3. **安全测试** → 验证输入验证和安全防护 + 4. **可用性测试** → 验证用户使用的便利性 + + ### Phase 4: 用户验收 + 1. **真实场景测试** → 在真实使用场景中验证 + 2. **用户反馈收集** → 收集用户的使用体验反馈 + 3. **问题优先级评估** → 评估发现问题的严重性 + 4. **交付决策** → 基于验证结果决定是否交付 + + ### 验证输出标准 + - **完整的测试报告**:详细的测试执行结果 + - **问题清单和解决方案**:发现问题的分类和处理 + - **质量评估报告**:各维度质量指标的评估 + - **交付建议**:基于验证结果的交付建议 + + \ No newline at end of file diff --git a/src/lib/core/pouch/commands/ActionCommand.js b/src/lib/core/pouch/commands/ActionCommand.js index deec926..57286e3 100644 --- a/src/lib/core/pouch/commands/ActionCommand.js +++ b/src/lib/core/pouch/commands/ActionCommand.js @@ -15,8 +15,6 @@ const logger = require('../../../utils/logger') class ActionCommand extends BasePouchCommand { constructor () { super() - // 获取WelcomeCommand的角色注册表 - this.welcomeCommand = null // 使用全局单例 ResourceManager this.resourceManager = getGlobalResourceManager() this.dpmlParser = new DPMLContentParser() @@ -98,18 +96,32 @@ class ActionCommand extends BasePouchCommand { } /** - * 获取角色信息(从WelcomeCommand) + * 获取角色信息(直接从ResourceManager) */ async getRoleInfo (roleId) { logger.debug(`[ActionCommand] getRoleInfo调用,角色ID: ${roleId}`) - // 总是创建新的WelcomeCommand实例,确保获取最新的角色信息 - logger.debug(`[ActionCommand] 创建新的WelcomeCommand实例以获取最新角色信息`) - const WelcomeCommand = require('./WelcomeCommand') - this.welcomeCommand = new WelcomeCommand() - - const result = await this.welcomeCommand.getRoleInfo(roleId) - logger.debug(`[ActionCommand] WelcomeCommand.getRoleInfo返回:`, result) + // 直接使用ResourceManager获取角色信息,移除对WelcomeCommand的依赖 + logger.debug(`[ActionCommand] 直接从ResourceManager获取角色信息`) + + const roles = this.resourceManager.registryData.getResourcesByProtocol('role') + logger.debug(`[ActionCommand] 找到${roles.length}个角色`) + + const role = roles.find(r => r.id === roleId) + logger.debug(`[ActionCommand] 查找角色${roleId}结果:`, role ? '找到' : '未找到') + + if (!role) { + return null + } + + const result = { + id: role.id, + name: role.name, + description: role.description, + file: role.reference + } + + logger.debug(`[ActionCommand] 返回角色信息:`, result) return result } diff --git a/src/lib/core/pouch/commands/InitCommand.js b/src/lib/core/pouch/commands/InitCommand.js index 1739315..df2ced7 100644 --- a/src/lib/core/pouch/commands/InitCommand.js +++ b/src/lib/core/pouch/commands/InitCommand.js @@ -86,8 +86,9 @@ class InitCommand extends BasePouchCommand { startDir: projectPath, platform: process.platform, avoidUserHome: true, - // init命令特有:优先当前目录,不查找现有.promptx + // init命令特有:AI提供的路径优先级最高,然后是当前目录 strategies: [ + 'aiProvidedProjectPath', // 最高优先级:AI提供的项目路径 'currentWorkingDirectoryIfHasMarkers', 'currentWorkingDirectory' ] diff --git a/src/lib/core/pouch/commands/ToolCommand.js b/src/lib/core/pouch/commands/ToolCommand.js index b35199a..3406e8e 100644 --- a/src/lib/core/pouch/commands/ToolCommand.js +++ b/src/lib/core/pouch/commands/ToolCommand.js @@ -1,6 +1,6 @@ const BasePouchCommand = require('../BasePouchCommand') const { getGlobalResourceManager } = require('../../resource') -const ToolExecutor = require('../../../tool/ToolExecutor') +const ToolSandbox = require('../../../tool/ToolSandbox') const logger = require('../../../utils/logger') /** @@ -10,7 +10,6 @@ const logger = require('../../../utils/logger') class ToolCommand extends BasePouchCommand { constructor() { super() - this.toolExecutor = new ToolExecutor() this.resourceManager = null } @@ -94,7 +93,7 @@ ${JSON.stringify(result.result, null, 2)} } /** - * 内部工具执行方法 + * 内部工具执行方法 - 使用ToolSandbox三阶段执行流程 * @param {Object} args - 命令参数 * @param {string} args.tool_resource - 工具资源引用,格式:@tool://tool-name * @param {Object} args.parameters - 传递给工具的参数 @@ -103,6 +102,7 @@ ${JSON.stringify(result.result, null, 2)} */ async executeToolInternal(args) { const startTime = Date.now() + let sandbox = null try { // 1. 参数验证 @@ -112,32 +112,39 @@ ${JSON.stringify(result.result, null, 2)} logger.debug(`[PromptXTool] 开始执行工具: ${tool_resource}`) - // 2. 通过ResourceManager解析工具资源 + // 2. 创建ToolSandbox实例 + sandbox = new ToolSandbox(tool_resource) + + // 3. 设置ResourceManager const resourceManager = await this.getResourceManager() - const toolInfo = await resourceManager.loadResource(tool_resource) + sandbox.setResourceManager(resourceManager) - // 3. 准备工具执行上下文 - const executionContext = { - ...context, - tool_resource, - timestamp: new Date().toISOString(), - execution_id: this.generateExecutionId() - } + // 4. ToolSandbox三阶段执行流程 + logger.debug(`[PromptXTool] Phase 1: 分析工具`) + const analysisResult = await sandbox.analyze() - // 4. 使用ToolExecutor执行工具 - const result = await this.toolExecutor.execute( - toolInfo.content, - parameters, - executionContext - ) + logger.debug(`[PromptXTool] Phase 2: 准备依赖`, { dependencies: analysisResult.dependencies }) + await sandbox.prepareDependencies() - // 5. 格式化成功结果 + logger.debug(`[PromptXTool] Phase 3: 执行工具`) + const result = await sandbox.execute(parameters) + + // 5. 格式化成功结果 return this.formatSuccessResult(result, tool_resource, startTime) } catch (error) { // 6. 格式化错误结果 logger.error(`[PromptXTool] 工具执行失败: ${error.message}`, error) return this.formatErrorResult(error, args.tool_resource, startTime) + } finally { + // 7. 清理沙箱资源 + if (sandbox) { + try { + await sandbox.cleanup() + } catch (cleanupError) { + logger.warn(`[PromptXTool] 沙箱清理失败: ${cleanupError.message}`) + } + } } } @@ -164,7 +171,7 @@ ${JSON.stringify(result.result, null, 2)} } /** - * 格式化成功结果 + * 格式化成功结果 - 适配ToolSandbox返回格式 * @param {*} result - 工具执行结果 * @param {string} toolResource - 工具资源引用 * @param {number} startTime - 开始时间 @@ -176,8 +183,9 @@ ${JSON.stringify(result.result, null, 2)} return { success: true, tool_resource: toolResource, - result: result, + result: result, // ToolSandbox直接返回工具结果 metadata: { + executor: 'ToolSandbox', execution_time_ms: duration, timestamp: new Date().toISOString(), version: '1.0.0' @@ -186,7 +194,7 @@ ${JSON.stringify(result.result, null, 2)} } /** - * 格式化错误结果 + * 格式化错误结果 - 适配ToolSandbox错误格式 * @param {Error} error - 错误对象 * @param {string} toolResource - 工具资源引用(可能为空) * @param {number} startTime - 开始时间 @@ -194,44 +202,66 @@ ${JSON.stringify(result.result, null, 2)} */ formatErrorResult(error, toolResource, startTime) { const duration = Date.now() - startTime + const executionId = this.generateExecutionId() return { success: false, tool_resource: toolResource || 'unknown', error: { - type: error.constructor.name, + code: this.getErrorCode(error), message: error.message, - code: this.getErrorCode(error) + details: { + executionId: executionId, + executionTime: `${duration}ms`, + stack: error.stack + } }, metadata: { - execution_time_ms: duration, - timestamp: new Date().toISOString(), - version: '1.0.0' + executor: 'ToolSandbox', + timestamp: new Date().toISOString() } } } /** - * 根据错误类型获取错误代码 + * 根据错误类型获取错误代码 - 增强支持ToolSandbox错误 * @param {Error} error - 错误对象 * @returns {string} 错误代码 */ getErrorCode(error) { - if (error.message.includes('not found')) { + const message = error.message.toLowerCase() + + // ToolSandbox特有错误 + if (message.includes('analyze') || message.includes('analysis')) { + return 'ANALYSIS_ERROR' + } + if (message.includes('dependencies') || message.includes('pnpm')) { + return 'DEPENDENCY_ERROR' + } + if (message.includes('sandbox') || message.includes('execution')) { + return 'EXECUTION_ERROR' + } + if (message.includes('validation') || message.includes('validate')) { + return 'VALIDATION_ERROR' + } + + // 通用错误 + if (message.includes('not found')) { return 'TOOL_NOT_FOUND' } - if (error.message.includes('Invalid tool_resource format')) { + if (message.includes('invalid tool_resource format')) { return 'INVALID_TOOL_RESOURCE' } - if (error.message.includes('Missing')) { + if (message.includes('missing')) { return 'MISSING_PARAMETER' } - if (error.message.includes('syntax')) { + if (message.includes('syntax')) { return 'TOOL_SYNTAX_ERROR' } - if (error.message.includes('timeout')) { + if (message.includes('timeout')) { return 'EXECUTION_TIMEOUT' } + return 'UNKNOWN_ERROR' } @@ -244,24 +274,28 @@ ${JSON.stringify(result.result, null, 2)} } /** - * 获取工具命令的元信息 + * 获取工具命令的元信息 - ToolSandbox版本 * @returns {Object} 命令元信息 */ getMetadata() { return { name: 'promptx_tool', - description: '执行通过@tool协议声明的工具', - version: '1.0.0', + description: '使用ToolSandbox执行通过@tool协议声明的工具', + version: '2.0.0', author: 'PromptX Framework', + executor: 'ToolSandbox', supports: { protocols: ['@tool://'], formats: ['.tool.js'], features: [ - 'JavaScript工具执行', + 'ToolSandbox沙箱执行', + '自动依赖管理', + '三阶段执行流程', + 'pnpm依赖安装', '参数验证', '错误处理', '执行监控', - '上下文传递' + '资源清理' ] } } diff --git a/src/lib/tool/ToolExecutor.js b/src/lib/tool/ToolExecutor.js deleted file mode 100644 index 97df039..0000000 --- a/src/lib/tool/ToolExecutor.js +++ /dev/null @@ -1,388 +0,0 @@ -const ToolValidator = require('./ToolValidator'); -const { TOOL_ERROR_CODES } = require('./ToolInterface'); - -/** - * ToolExecutor 工具执行器 - * 负责工具的加载、验证、执行和结果处理 - */ -class ToolExecutor { - constructor(options = {}) { - this.options = { - timeout: 30000, // 默认30秒超时 - maxConcurrency: 10, // 最大并发数 - enableCache: true, // 启用工具缓存 - ...options - }; - - this.toolCache = new Map(); // 工具实例缓存 - this.runningTasks = new Set(); // 正在执行的任务 - } - - /** - * 执行工具(从代码内容) - * @param {string} toolContent - 工具JavaScript代码内容 - * @param {Object} parameters - 工具参数 - * @param {Object} context - 执行上下文 - * @returns {Promise} 执行结果 - */ - async execute(toolContent, parameters = {}, context = {}) { - const executionId = this.generateExecutionId(); - const startTime = Date.now(); - - try { - // 1. 并发控制 - if (this.runningTasks.size >= this.options.maxConcurrency) { - throw new Error(`超出最大并发限制: ${this.options.maxConcurrency}`); - } - - this.runningTasks.add(executionId); - - // 2. 执行工具代码并创建实例 - const tool = this.executeToolContent(toolContent, context.toolName || 'unknown'); - - // 2.5. 增强工具默认实现 - this.enhanceToolWithDefaults(tool); - - // 3. 参数验证 - const validation = this.validateParameters(tool, parameters); - if (!validation.valid) { - return this.formatError(TOOL_ERROR_CODES.VALIDATION_ERROR, '参数验证失败', { - errors: validation.errors, - parameters: parameters - }); - } - - // 4. 执行工具(带超时控制) - const result = await this.executeWithTimeout(tool, parameters); - const executionTime = Date.now() - startTime; - - // 5. 格式化成功结果 - return this.formatSuccess(result, { - executionId, - executionTime: `${executionTime}ms`, - tool: tool.getMetadata ? tool.getMetadata() : { name: context.toolName || 'unknown' } - }); - - } catch (error) { - const executionTime = Date.now() - startTime; - return this.formatError( - this.getErrorCode(error), - error.message, - { - executionId, - executionTime: `${executionTime}ms`, - stack: error.stack - } - ); - } finally { - this.runningTasks.delete(executionId); - } - } - - - /** - * 执行工具内容并返回实例 - * @param {string} toolContent - 工具代码内容 - * @param {string} toolName - 工具名称 - * @returns {Object} 工具实例 - */ - executeToolContent(toolContent, toolName) { - try { - // 1. 先用基础沙箱获取工具实例,检查是否有包信息 - const basicSandbox = this.createSandbox(); - const vm = require('vm'); - const script = new vm.Script(toolContent, { filename: `${toolName}.js` }); - const basicContext = vm.createContext(basicSandbox); - - script.runInContext(basicContext); - const exported = basicContext.module.exports; - - if (!exported) { - throw new Error(`工具未正确导出: ${toolName}`); - } - - // 实例化工具 - let toolInstance; - if (typeof exported === 'function') { - toolInstance = new exported(); - } else if (typeof exported === 'object') { - toolInstance = exported; - } else { - 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; - - } catch (error) { - throw new Error(`工具代码执行失败 ${toolName}: ${error.message}`); - } - } - - /** - * 创建智能沙箱(支持工具依赖) - * @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} 沙箱环境 - */ - createSandbox() { - 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 - }; - } - - - /** - * 带超时的工具执行 - * @param {BaseTool} tool - 工具实例 - * @param {Object} parameters - 参数 - * @returns {Promise<*>} 执行结果 - */ - async executeWithTimeout(tool, parameters) { - return new Promise((resolve, reject) => { - const timeoutId = setTimeout(() => { - reject(new Error(`工具执行超时: ${this.options.timeout}ms`)); - }, this.options.timeout); - - tool.execute(parameters) - .then(result => { - clearTimeout(timeoutId); - resolve(result); - }) - .catch(error => { - clearTimeout(timeoutId); - reject(error); - }); - }); - } - - /** - * 生成执行ID - * @returns {string} 唯一执行ID - */ - generateExecutionId() { - return `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; - } - - /** - * 参数验证 - * @param {Object} tool - 工具实例 - * @param {Object} parameters - 参数 - * @returns {Object} 验证结果 - */ - validateParameters(tool, parameters) { - // 如果工具有自定义validate方法,使用它 - if (typeof tool.validate === 'function') { - const result = tool.validate(parameters); - - // 支持两种返回格式: - // 1. boolean - 转换为标准格式 - // 2. {valid: boolean, errors?: array} - 标准格式 - if (typeof result === 'boolean') { - return { valid: result, errors: result ? [] : ['Validation failed'] }; - } else if (result && typeof result === 'object') { - return result; - } else { - return { valid: false, errors: ['Invalid validation result'] }; - } - } - - // 否则使用默认验证 - return ToolValidator.defaultValidate(tool, parameters); - } - - /** - * 为工具增强默认实现 - * @param {Object} tool - 工具实例 - */ - enhanceToolWithDefaults(tool) { - // 如果没有validate方法,提供默认实现 - if (!tool.validate) { - tool.validate = (parameters) => ToolValidator.defaultValidate(tool, parameters); - } - - // 如果没有cleanup方法,提供空实现 - if (!tool.cleanup) { - tool.cleanup = () => {}; - } - - // 如果没有init方法,提供空实现 - if (!tool.init) { - tool.init = () => {}; - } - } - - /** - * 获取错误代码 - * @param {Error} error - 错误对象 - * @returns {string} 错误代码 - */ - getErrorCode(error) { - if (error.message.includes('超时')) return TOOL_ERROR_CODES.TIMEOUT_ERROR; - if (error.message.includes('不存在')) return 'TOOL_NOT_FOUND'; - if (error.message.includes('验证失败')) return TOOL_ERROR_CODES.VALIDATION_ERROR; - if (error.message.includes('并发限制')) return 'CONCURRENCY_ERROR'; - if (error.message.includes('接口不符合规范')) return 'INTERFACE_ERROR'; - return TOOL_ERROR_CODES.EXECUTION_ERROR; - } - - /** - * 格式化成功结果 - * @param {*} data - 结果数据 - * @param {Object} metadata - 元信息 - * @returns {Object} 标准化结果 - */ - formatSuccess(data, metadata = {}) { - return { - success: true, - data: data, - metadata: { - executor: 'ToolExecutor', - timestamp: new Date().toISOString(), - ...metadata - } - }; - } - - /** - * 格式化错误结果 - * @param {string} code - 错误代码 - * @param {string} message - 错误消息 - * @param {Object} details - 错误详情 - * @returns {Object} 标准化错误 - */ - formatError(code, message, details = {}) { - return { - success: false, - error: { - code: code, - message: message, - details: details - }, - metadata: { - executor: 'ToolExecutor', - timestamp: new Date().toISOString() - } - }; - } - - /** - * 获取执行统计信息 - * @returns {Object} 统计信息 - */ - getStats() { - return { - runningTasks: this.runningTasks.size, - cachedTools: this.toolCache.size, - maxConcurrency: this.options.maxConcurrency, - timeout: this.options.timeout - }; - } - - /** - * 清理资源 - */ - cleanup() { - this.toolCache.clear(); - this.runningTasks.clear(); - } -} - -module.exports = ToolExecutor; \ No newline at end of file diff --git a/src/lib/tool/index.js b/src/lib/tool/index.js index 176c603..7126fff 100644 --- a/src/lib/tool/index.js +++ b/src/lib/tool/index.js @@ -1,43 +1,45 @@ /** * PromptX Tool Framework - * 统一的工具框架入口文件 + * 统一的工具框架入口文件 - ToolSandbox版本 */ -const ToolExecutor = require('./ToolExecutor'); +const ToolSandbox = require('./ToolSandbox'); const ToolValidator = require('./ToolValidator'); const ToolUtils = require('./ToolUtils'); const { TOOL_INTERFACE, TOOL_ERROR_CODES, TOOL_RESULT_FORMAT, EXAMPLE_TOOL } = require('./ToolInterface'); // 创建全局工具实例 -let globalExecutor = null; +let globalSandbox = null; /** - * 获取全局工具执行器 - * @param {Object} options - 配置选项 - * @returns {ToolExecutor} 工具执行器实例 + * 获取全局工具沙箱 + * @param {string} toolResource - 工具资源引用 + * @returns {ToolSandbox} 工具沙箱实例 */ -function getGlobalToolExecutor(options = {}) { - if (!globalExecutor) { - globalExecutor = new ToolExecutor(options); - } - return globalExecutor; +function getGlobalToolSandbox(toolResource) { + // ToolSandbox是工具特定的,不使用单例 + return new ToolSandbox(toolResource); } /** - * 初始化工具框架 + * 初始化工具框架 - ToolSandbox版本 * @param {Object} options - 配置选项 * @returns {Object} 初始化结果 */ function initialize(options = {}) { try { - const executor = getGlobalToolExecutor(options.executor); - return { success: true, - message: '工具框架初始化成功', - executor: { - maxConcurrency: executor.options.maxConcurrency, - timeout: executor.options.timeout + message: 'ToolSandbox工具框架初始化成功', + framework: { + executor: 'ToolSandbox', + version: '2.0.0', + features: [ + '自动依赖管理', + '沙箱隔离执行', + '三阶段执行流程', + 'pnpm集成' + ] } }; } catch (error) { @@ -50,46 +52,61 @@ function initialize(options = {}) { } /** - * 执行工具的便捷方法 - * @param {string} toolContent - 工具JavaScript代码内容 + * 执行工具的便捷方法 - ToolSandbox版本 + * @param {string} toolResource - 工具资源引用 (@tool://tool-name) * @param {Object} parameters - 工具参数 - * @param {Object} context - 执行上下文 + * @param {Object} resourceManager - ResourceManager实例 * @returns {Promise} 执行结果 */ -async function executeTool(toolContent, parameters = {}, context = {}) { - const executor = getGlobalToolExecutor(); - return await executor.execute(toolContent, parameters, context); -} - -/** - * 重置工具框架 - */ -function reset() { - if (globalExecutor) { - globalExecutor.cleanup(); - globalExecutor = null; +async function executeTool(toolResource, parameters = {}, resourceManager = null) { + if (!resourceManager) { + throw new Error('ResourceManager is required for ToolSandbox execution'); + } + + const sandbox = getGlobalToolSandbox(toolResource); + sandbox.setResourceManager(resourceManager); + + try { + await sandbox.analyze(); + await sandbox.prepareDependencies(); + return await sandbox.execute(parameters); + } finally { + await sandbox.cleanup(); } } /** - * 获取工具框架统计信息 + * 重置工具框架 - ToolSandbox版本 + */ +function reset() { + // ToolSandbox不使用全局单例,无需重置 + globalSandbox = null; +} + +/** + * 获取工具框架统计信息 - ToolSandbox版本 * @returns {Object} 统计信息 */ function getStats() { - const executorStats = globalExecutor ? globalExecutor.getStats() : {}; - return { - executor: executorStats, framework: { - initialized: !!globalExecutor, - version: '1.0.0' + name: 'PromptX ToolSandbox Framework', + version: '2.0.0', + executor: 'ToolSandbox', + features: [ + '自动依赖管理', + '沙箱隔离执行', + '三阶段执行流程', + 'pnpm集成', + '@tool://协议支持' + ] } }; } module.exports = { // 核心类 - ToolExecutor, + ToolSandbox, ToolValidator, ToolUtils, @@ -100,7 +117,7 @@ module.exports = { EXAMPLE_TOOL, // 全局实例获取器 - getGlobalToolExecutor, + getGlobalToolSandbox, // 便捷方法 initialize,