UNPKG

@iflow-mcp/promptx

Version:

AI角色创建平台和智能工具开发平台,基于MCP协议提供专业AI能力注入

1,266 lines (1,257 loc) 225 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // ../../node_modules/tsup/assets/cjs_shims.js var init_cjs_shims = __esm({ "../../node_modules/tsup/assets/cjs_shims.js"() { "use strict"; } }); // src/toolx/errors/ErrorCategories.js var require_ErrorCategories = __commonJS({ "src/toolx/errors/ErrorCategories.js"(exports2, module2) { "use strict"; init_cjs_shims(); var ERROR_CATEGORIES = { DEVELOPMENT: { name: "DEVELOPMENT", emoji: "\u{1F468}\u200D\u{1F4BB}", description: "\u5DE5\u5177\u4EE3\u7801\u9519\u8BEF", responsibility: "\u5DE5\u5177\u5F00\u53D1\u8005\u9700\u8981\u4FEE\u590D\u4EE3\u7801", severity: "error" }, VALIDATION: { name: "VALIDATION", emoji: "\u{1F4DD}", description: "\u53C2\u6570/\u73AF\u5883\u9A8C\u8BC1\u9519\u8BEF", responsibility: "\u7528\u6237\u9700\u8981\u63D0\u4F9B\u6B63\u786E\u7684\u8F93\u5165", severity: "warning", note: "\u7CFB\u7EDF\u81EA\u52A8\u68C0\u6D4B\uFF0C\u65E0\u9700\u5DE5\u5177\u5B9A\u4E49" }, BUSINESS: { name: "BUSINESS", emoji: "\u{1F4BC}", description: "\u4E1A\u52A1\u6267\u884C\u9519\u8BEF", responsibility: "\u6839\u636E\u5177\u4F53\u9519\u8BEF\u8C03\u6574\u4F7F\u7528\u65B9\u5F0F", severity: "error", note: "\u5DE5\u5177\u901A\u8FC7getBusinessErrors()\u5B9A\u4E49" }, SYSTEM: { name: "SYSTEM", emoji: "\u{1F527}", description: "\u7CFB\u7EDF\u73AF\u5883\u9519\u8BEF", responsibility: "PromptX\u56E2\u961F\u5904\u7406\u6216\u7528\u6237\u91CD\u8BD5", severity: "critical" } }; module2.exports = ERROR_CATEGORIES; } }); // src/toolx/errors/DevelopmentErrors.js var require_DevelopmentErrors = __commonJS({ "src/toolx/errors/DevelopmentErrors.js"(exports2, module2) { "use strict"; init_cjs_shims(); var DEVELOPMENT_ERRORS = { UNDECLARED_DEPENDENCY: { code: "UNDECLARED_DEPENDENCY", category: "DEVELOPMENT", description: "\u5DE5\u5177\u4F7F\u7528\u4E86\u672A\u58F0\u660E\u7684\u4F9D\u8D56\u5305", identify: (error, context) => { const message2 = error.message.toLowerCase(); if (!message2.includes("cannot find module") && !message2.includes("cannot resolve")) { return false; } const moduleMatch = error.message.match(/Cannot (?:find|resolve) module ['\"]([^'\"]+)['"]/); if (!moduleMatch) return false; const moduleName = moduleMatch[1]; if (context.dependencies) { if (typeof context.dependencies === "object") { return !Object.keys(context.dependencies).includes(moduleName); } } return true; }, getSolution: (error, context) => { const moduleMatch = error.message.match(/Cannot (?:find|resolve) module ['\"]([^'\"]+)['"]/); const moduleName = moduleMatch ? moduleMatch[1] : "unknown"; return { message: `\u5728 getDependencies() \u4E2D\u6DFB\u52A0\u4F9D\u8D56\u58F0\u660E`, code: `getDependencies() { return { '${moduleName}': 'latest' }; }`, autoRecoverable: false }; } }, TOOL_SYNTAX_ERROR: { code: "TOOL_SYNTAX_ERROR", category: "DEVELOPMENT", description: "\u5DE5\u5177\u4EE3\u7801\u5B58\u5728\u8BED\u6CD5\u9519\u8BEF", identify: (error) => { return error instanceof SyntaxError || error.message.includes("Unexpected token") || error.message.includes("Unexpected identifier"); }, getSolution: (error) => { const lineMatch = error.stack && error.stack.match(/:(\d+):(\d+)/); const line2 = lineMatch ? lineMatch[1] : "unknown"; return { message: `\u4FEE\u590D\u5DE5\u5177\u4EE3\u7801\u7684\u8BED\u6CD5\u9519\u8BEF`, detail: `\u9519\u8BEF\u4F4D\u7F6E\uFF1A\u7B2C ${line2} \u884C \u9519\u8BEF\u4FE1\u606F\uFF1A${error.message}`, autoRecoverable: false }; } }, INVALID_TOOL_EXPORT: { code: "INVALID_TOOL_EXPORT", category: "DEVELOPMENT", description: "\u5DE5\u5177\u672A\u6B63\u786E\u5BFC\u51FA\u5FC5\u9700\u7684\u63A5\u53E3", identify: (error) => { return error.message.includes("does not export") || error.message.includes("is not a function") || error.message.includes("Tool must export") || error.message.includes("missing required method"); }, getSolution: (error) => { const methodMatch = error.message.match(/method ['\"]?(\w+)['\"]?/); const method = methodMatch ? methodMatch[1] : "execute"; return { message: `\u786E\u4FDD\u5DE5\u5177\u6B63\u786E\u5BFC\u51FA\u6240\u6709\u5FC5\u9700\u7684\u65B9\u6CD5`, code: `module.exports = { getMetadata() { /* ... */ }, getSchema() { /* ... */ }, async execute(params) { /* ... */ } };`, autoRecoverable: false }; } }, INTERFACE_NOT_IMPLEMENTED: { code: "INTERFACE_NOT_IMPLEMENTED", category: "DEVELOPMENT", description: "\u5DE5\u5177\u672A\u5B9E\u73B0\u5FC5\u9700\u7684\u63A5\u53E3\u65B9\u6CD5", identify: (error) => { return error.message.includes("not implemented") || error.message.includes("must implement"); }, getSolution: (error) => { const methodMatch = error.message.match(/['\"]?(\w+)['\"]? (?:not implemented|must implement)/); const method = methodMatch ? methodMatch[1] : "unknown"; return { message: `\u5B9E\u73B0\u7F3A\u5931\u7684\u63A5\u53E3\u65B9\u6CD5: ${method}`, autoRecoverable: false }; } }, DEPENDENCY_DECLARED_BUT_MISSING: { code: "DEPENDENCY_DECLARED_BUT_MISSING", category: "DEVELOPMENT", description: "\u4F9D\u8D56\u5DF2\u58F0\u660E\u4F46\u6A21\u5757\u4E2D\u5B9E\u9645\u672A\u4F7F\u7528\u6B63\u786E", identify: (error, context) => { const message2 = error.message.toLowerCase(); if (!message2.includes("cannot find module")) return false; const moduleMatch = error.message.match(/Cannot (?:find|resolve) module ['\"]([^'\"]+)['"]/); if (!moduleMatch) return false; const moduleName = moduleMatch[1]; if (context.dependencies && typeof context.dependencies === "object") { return Object.keys(context.dependencies).includes(moduleName); } return false; }, getSolution: (error, context) => { return { message: "\u4F9D\u8D56\u5DF2\u58F0\u660E\u4F46\u5B89\u88C5\u5931\u8D25\uFF0C\u5C1D\u8BD5\u4F7F\u7528 rebuild \u6A21\u5F0F\u91CD\u65B0\u5B89\u88C5", autoRecoverable: true, retryMode: "rebuild" }; } } }; module2.exports = DEVELOPMENT_ERRORS; } }); // src/toolx/errors/ValidationErrors.js var require_ValidationErrors = __commonJS({ "src/toolx/errors/ValidationErrors.js"(exports2, module2) { "use strict"; init_cjs_shims(); var VALIDATION_ERRORS = { MISSING_REQUIRED_PARAM: { code: "MISSING_REQUIRED_PARAM", category: "VALIDATION", description: "\u7F3A\u5C11\u5FC5\u9700\u7684\u53C2\u6570", identify: (error, context) => { if (context.validationResult && !context.validationResult.valid) { return context.validationResult.errors.some((e) => e.includes("required") || e.includes("missing")); } return error.message.includes("Missing required parameter") || error.message.includes("required property"); }, getSolution: (error, context) => { var _a; const missing = ((_a = context.validationResult) == null ? void 0 : _a.missing) || []; return { message: `\u63D0\u4F9B\u5FC5\u9700\u7684\u53C2\u6570\u3002\u5982\u4E0D\u6E05\u695A\u53C2\u6570\u683C\u5F0F\uFF0C\u8BF7\u4F7F\u7528 mode: manual \u67E5\u770B\u5DE5\u5177\u7684\u5B8C\u6574\u53C2\u6570\u8BF4\u660E`, params: missing.length > 0 ? missing : "Check schema for required parameters", example: missing.length > 0 ? `{ ${missing.map((p) => `"${p}": "value"`).join(", ")} }` : null, autoRecoverable: false }; } }, INVALID_PARAM_TYPE: { code: "INVALID_PARAM_TYPE", category: "VALIDATION", description: "\u53C2\u6570\u7C7B\u578B\u9519\u8BEF", identify: (error, context) => { if (context.validationResult && !context.validationResult.valid) { return context.validationResult.errors.some((e) => e.includes("type") || e.includes("should be")); } return /expected (string|number|boolean|object|array) but got/i.test(error.message) || error.message.includes("type mismatch"); }, getSolution: (error, context) => { var _a; const typeErrors = ((_a = context.validationResult) == null ? void 0 : _a.typeErrors) || []; return { message: "\u4FEE\u6B63\u53C2\u6570\u7C7B\u578B\u3002\u5982\u4E0D\u6E05\u695A\u53C2\u6570\u683C\u5F0F\uFF0C\u8BF7\u4F7F\u7528 mode: manual \u67E5\u770B\u5DE5\u5177\u7684\u5B8C\u6574\u53C2\u6570\u8BF4\u660E", detail: typeErrors.length > 0 ? typeErrors.map((e) => `${e.param}: \u671F\u671B ${e.expected}, \u5B9E\u9645 ${e.actual}`).join("\n") : "\u68C0\u67E5\u53C2\u6570\u7C7B\u578B\u662F\u5426\u7B26\u5408 schema \u5B9A\u4E49", autoRecoverable: false }; } }, PARAM_OUT_OF_RANGE: { code: "PARAM_OUT_OF_RANGE", category: "VALIDATION", description: "\u53C2\u6570\u503C\u8D85\u51FA\u5141\u8BB8\u8303\u56F4", identify: (error, context) => { if (context.validationResult && !context.validationResult.valid) { if (context.validationResult.enumErrors && context.validationResult.enumErrors.length > 0) { return true; } return context.validationResult.errors.some((e) => e.includes("must be one of") || e.includes("enum") || e.includes(">= ") || e.includes("<= ")); } return /out of range|exceeds maximum|below minimum/i.test(error.message) || error.message.includes("enum") || error.message.includes("not in allowed values") || error.message.includes("must be one of"); }, getSolution: (error, context) => { var _a; const enumErrors = ((_a = context.validationResult) == null ? void 0 : _a.enumErrors) || []; if (enumErrors.length > 0) { const enumError = enumErrors[0]; return { message: `\u53C2\u6570 ${enumError.param} \u7684\u503C\u65E0\u6548\u3002\u5982\u4E0D\u6E05\u695A\u53C2\u6570\u683C\u5F0F\uFF0C\u8BF7\u4F7F\u7528 mode: manual \u67E5\u770B\u5DE5\u5177\u7684\u5B8C\u6574\u53C2\u6570\u8BF4\u660E`, detail: `\u5F53\u524D\u503C: "${enumError.value}" \u5141\u8BB8\u7684\u503C: ${enumError.allowed.join(", ")}`, example: `\u5C06 ${enumError.param} \u8BBE\u7F6E\u4E3A: ${enumError.allowed[0]}`, autoRecoverable: false }; } return { message: "\u53C2\u6570\u503C\u8D85\u51FA\u5141\u8BB8\u8303\u56F4\u3002\u5982\u4E0D\u6E05\u695A\u53C2\u6570\u683C\u5F0F\uFF0C\u8BF7\u4F7F\u7528 mode: manual \u67E5\u770B\u5DE5\u5177\u7684\u5B8C\u6574\u53C2\u6570\u8BF4\u660E", detail: "\u8BF7\u68C0\u67E5\u53C2\u6570\u503C\u662F\u5426\u5728\u5141\u8BB8\u7684\u8303\u56F4\u5185", autoRecoverable: false }; } }, MISSING_ENV_VAR: { code: "MISSING_ENV_VAR", category: "VALIDATION", description: "\u7F3A\u5C11\u5FC5\u9700\u7684\u73AF\u5883\u53D8\u91CF", identify: (error, context) => { if (context.missingEnvVars && context.missingEnvVars.length > 0) { return true; } return error.message.includes("Missing environment variable") || error.message.includes("env var not set") || error.message.includes("\u7F3A\u5C11\u5FC5\u9700\u7684\u914D\u7F6E"); }, getSolution: (error, context) => { var _a; const missing = context.missingEnvVars || []; const envVar = missing[0] || ((_a = error.message.match(/variable ['\"]?(\w+)['\"]?/)) == null ? void 0 : _a[1]) || "UNKNOWN"; return { message: `\u4F7F\u7528 configure \u6A21\u5F0F\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF`, command: `toolx configure --set ${envVar}=value`, detail: missing.length > 0 ? `\u7F3A\u5C11\u73AF\u5883\u53D8\u91CF: ${missing.join(", ")}` : `\u7F3A\u5C11\u73AF\u5883\u53D8\u91CF: ${envVar}`, autoRecoverable: false }; } }, INVALID_ENV_VAR_VALUE: { code: "INVALID_ENV_VAR_VALUE", category: "VALIDATION", description: "\u73AF\u5883\u53D8\u91CF\u503C\u65E0\u6548", identify: (error) => { return error.message.includes("Invalid environment variable") || error.message.includes("env var invalid"); }, getSolution: (error, context) => { return { message: "\u68C0\u67E5\u73AF\u5883\u53D8\u91CF\u503C\u662F\u5426\u6B63\u786E", detail: "\u4F7F\u7528 configure \u6A21\u5F0F\u91CD\u65B0\u8BBE\u7F6E", autoRecoverable: false }; } }, PARAMETERS_NOT_OBJECT: { code: "PARAMETERS_NOT_OBJECT", category: "VALIDATION", description: "execute/rebuild\u6A21\u5F0F\u9700\u8981parameters\u5BF9\u8C61", identify: (error, context) => { return error.message.includes("Parameters must be an object") || error.message.includes("\u9700\u8981 parameters \u5BF9\u8C61") || error.message.includes("parameters \u53C2\u6570"); }, getSolution: (error, context) => { var _a; const mode = context.mode || "execute"; const toolName = ((_a = context.tool_resource) == null ? void 0 : _a.replace("@tool://", "")) || "tool-name"; return { message: `${mode} \u6A21\u5F0F\u9700\u8981 parameters \u5BF9\u8C61`, example: `{tool_resource: '@tool://${toolName}', mode: '${mode}', parameters: {...}}`, detail: `\u{1F4A1} \u5EFA\u8BAE\uFF1A\u5148\u7528 mode: 'manual' \u67E5\u770B\u5DE5\u5177\u53C2\u6570\u8981\u6C42`, command: `\u5148\u6267\u884C: {tool_resource: '@tool://${toolName}', mode: 'manual'}`, autoRecoverable: false }; } }, SCHEMA_VALIDATION_FAILED: { code: "SCHEMA_VALIDATION_FAILED", category: "VALIDATION", description: "\u53C2\u6570\u672A\u901A\u8FC7 schema \u9A8C\u8BC1", identify: (error, context) => { return context.validationResult && !context.validationResult.valid; }, getSolution: (error, context) => { var _a; const errors = ((_a = context.validationResult) == null ? void 0 : _a.errors) || []; return { message: "\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25", errors, detail: errors.length > 0 ? errors.join("\n") : "\u8BF7\u68C0\u67E5\u53C2\u6570\u683C\u5F0F", autoRecoverable: false }; } } }; function validateAgainstSchema(params, schema) { var _a; const Ajv = require("ajv"); const ajv = new Ajv({ allErrors: true, // 收集所有错误 verbose: true, // 包含详细信息 strict: false, // 允许额外的schema关键字 coerceTypes: false // 不自动转换类型 }); if (!schema || !schema.properties) { return { valid: true, errors: [], missing: [], typeErrors: [] }; } try { const validate = ajv.compile(schema); const valid = validate(params); if (valid) { return { valid: true, errors: [], missing: [], typeErrors: [] }; } const errors = []; const missing = []; const typeErrors = []; const enumErrors = []; for (const error of validate.errors) { const field = error.instancePath ? error.instancePath.substring(1) : (_a = error.params) == null ? void 0 : _a.missingProperty; switch (error.keyword) { case "required": missing.push(error.params.missingProperty); errors.push(`Missing required parameter: ${error.params.missingProperty}`); break; case "type": typeErrors.push({ param: field, expected: error.schema, actual: typeof error.data }); errors.push(`Parameter ${field} should be ${error.schema} but got ${typeof error.data}`); break; case "enum": { enumErrors.push({ param: field, value: error.data, allowed: error.schema }); errors.push(`Parameter ${field} must be one of: ${error.schema.join(", ")}`); break; } case "minimum": errors.push(`Parameter ${field} must be >= ${error.schema}`); break; case "maximum": errors.push(`Parameter ${field} must be <= ${error.schema}`); break; case "minLength": errors.push(`Parameter ${field} length must be >= ${error.schema}`); break; case "maxLength": errors.push(`Parameter ${field} length must be <= ${error.schema}`); break; case "pattern": errors.push(`Parameter ${field} does not match required pattern`); break; default: errors.push(error.message || `Parameter ${field} validation failed`); } } return { valid: false, errors, missing, typeErrors, enumErrors, ajvErrors: validate.errors // 保留原始错误供调试 }; } catch (err) { return { valid: false, errors: [`Schema compilation error: ${err.message}`], missing: [], typeErrors: [] }; } } module2.exports = { VALIDATION_ERRORS, validateAgainstSchema }; } }); // src/toolx/errors/SystemErrors.js var require_SystemErrors = __commonJS({ "src/toolx/errors/SystemErrors.js"(exports2, module2) { "use strict"; init_cjs_shims(); var SYSTEM_ERRORS = { DEPENDENCY_INSTALL_FAILED: { code: "DEPENDENCY_INSTALL_FAILED", category: "SYSTEM", description: "\u4F9D\u8D56\u5B89\u88C5\u5931\u8D25", identify: (error) => { return error.message.includes("pnpm install failed") || error.message.includes("npm ERR") || error.message.includes("yarn error") || error.message.includes("Failed to install dependencies"); }, getSolution: (error) => { return { message: "\u4F9D\u8D56\u5B89\u88C5\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u7F51\u7EDC\u95EE\u9898", suggestions: [ "1. \u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5", "2. \u5C1D\u8BD5\u66F4\u6362 npm \u955C\u50CF\u6E90", "3. \u4F7F\u7528 rebuild \u6A21\u5F0F\u91CD\u8BD5", "4. \u6E05\u7406\u7F13\u5B58\u540E\u91CD\u8BD5" ], autoRecoverable: true, retryDelay: 5e3, retryMode: "rebuild" }; } }, SANDBOX_INIT_FAILED: { code: "SANDBOX_INIT_FAILED", category: "SYSTEM", description: "\u6C99\u7BB1\u73AF\u5883\u521D\u59CB\u5316\u5931\u8D25", identify: (error) => { return error.message.includes("Failed to create sandbox") || error.message.includes("VM context error") || error.message.includes("Sandbox initialization failed"); }, getSolution: (error) => { return { message: "\u6C99\u7BB1\u73AF\u5883\u521D\u59CB\u5316\u5931\u8D25", suggestions: [ "1. \u91CD\u542F PromptX \u670D\u52A1", "2. \u6E05\u7406 ~/.promptx/toolbox \u76EE\u5F55", "3. \u68C0\u67E5\u76EE\u5F55\u6743\u9650", "4. \u62A5\u544A\u7ED9 PromptX \u56E2\u961F" ], autoRecoverable: false }; } }, NETWORK_TIMEOUT: { code: "NETWORK_TIMEOUT", category: "SYSTEM", description: "\u7F51\u7EDC\u8BF7\u6C42\u8D85\u65F6", identify: (error) => { return error.message.includes("timeout") || error.message.includes("ETIMEDOUT") || error.message.includes("ESOCKETTIMEDOUT") || error.code === "ETIMEDOUT"; }, getSolution: (error, context) => { const currentTimeout = context.timeout || 3e4; const newTimeout = Math.min(currentTimeout * 2, 3e5); return { message: "\u7F51\u7EDC\u8BF7\u6C42\u8D85\u65F6", detail: `\u5F53\u524D\u8D85\u65F6\u65F6\u95F4: ${currentTimeout}ms`, suggestions: [ "1. \u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5", "2. \u589E\u52A0\u8D85\u65F6\u65F6\u95F4\u91CD\u8BD5", "3. \u68C0\u67E5\u76EE\u6807\u670D\u52A1\u662F\u5426\u53EF\u8BBF\u95EE" ], autoRecoverable: true, retryParams: { timeout: newTimeout } }; } }, DISK_SPACE_ERROR: { code: "DISK_SPACE_ERROR", category: "SYSTEM", description: "\u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3", identify: (error) => { return error.message.includes("ENOSPC") || error.message.includes("No space left on device") || error.message.includes("disk full"); }, getSolution: (error) => { return { message: "\u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3", suggestions: [ "1. \u6E05\u7406\u78C1\u76D8\u7A7A\u95F4", "2. \u6E05\u7406 ~/.promptx/toolbox \u76EE\u5F55", "3. \u6E05\u7406 npm/pnpm \u7F13\u5B58" ], autoRecoverable: false }; } }, PERMISSION_DENIED: { code: "PERMISSION_DENIED", category: "SYSTEM", description: "\u6743\u9650\u4E0D\u8DB3", identify: (error) => { return error.message.includes("EACCES") || error.message.includes("Permission denied") || error.message.includes("operation not permitted"); }, getSolution: (error, context) => { var _a; const path2 = ((_a = error.message.match(/['"](\/[^'"]+)['"]/)) == null ? void 0 : _a[1]) || context.sandboxPath; return { message: "\u6587\u4EF6\u6216\u76EE\u5F55\u6743\u9650\u4E0D\u8DB3", detail: `\u8DEF\u5F84: ${path2}`, suggestions: [ "1. \u68C0\u67E5\u6587\u4EF6/\u76EE\u5F55\u6743\u9650", "2. \u786E\u4FDD PromptX \u6709\u5199\u5165\u6743\u9650", "3. \u5C1D\u8BD5\u4FEE\u590D\u6743\u9650: chmod -R 755 ~/.promptx" ], autoRecoverable: false }; } }, MEMORY_ERROR: { code: "MEMORY_ERROR", category: "SYSTEM", description: "\u5185\u5B58\u4E0D\u8DB3", identify: (error) => { return error.message.includes("JavaScript heap out of memory") || error.message.includes("Cannot allocate memory") || error.message.includes("ENOMEM"); }, getSolution: (error) => { return { message: "\u5185\u5B58\u4E0D\u8DB3", suggestions: [ "1. \u5173\u95ED\u5176\u4ED6\u5E94\u7528\u91CA\u653E\u5185\u5B58", "2. \u589E\u52A0 Node.js \u5185\u5B58\u9650\u5236", "3. \u4F18\u5316\u5DE5\u5177\u51CF\u5C11\u5185\u5B58\u4F7F\u7528" ], autoRecoverable: false }; } }, PACKAGE_REGISTRY_ERROR: { code: "PACKAGE_REGISTRY_ERROR", category: "SYSTEM", description: "\u5305\u6CE8\u518C\u6E90\u8BBF\u95EE\u5931\u8D25", identify: (error) => { return error.message.includes("registry error") || error.message.includes("npm registry") || error.message.includes("E404") || error.message.includes("tarball"); }, getSolution: (error) => { return { message: "npm/pnpm \u5305\u6CE8\u518C\u6E90\u8BBF\u95EE\u5931\u8D25", suggestions: [ "1. \u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5", "2. \u5C1D\u8BD5\u4F7F\u7528\u955C\u50CF\u6E90: npm config set registry https://registry.npmmirror.com", "3. \u68C0\u67E5\u5305\u540D\u548C\u7248\u672C\u662F\u5426\u6B63\u786E", "4. \u7A0D\u540E\u91CD\u8BD5" ], autoRecoverable: true, retryDelay: 1e4 }; } }, VM_EXECUTION_ERROR: { code: "VM_EXECUTION_ERROR", category: "SYSTEM", description: "VM \u6267\u884C\u73AF\u5883\u9519\u8BEF", identify: (error) => { return error.message.includes("VM execution") || error.message.includes("sandbox context") || error.message.includes("vm.Script"); }, getSolution: (error) => { return { message: "VM \u6267\u884C\u73AF\u5883\u9519\u8BEF", detail: "PromptX \u6C99\u7BB1\u6267\u884C\u73AF\u5883\u5F02\u5E38", suggestions: [ "1. \u91CD\u542F PromptX \u670D\u52A1", "2. \u62A5\u544A\u95EE\u9898\u7ED9 PromptX \u56E2\u961F" ], autoRecoverable: false }; } }, TOOL_NOT_FOUND: { code: "TOOL_NOT_FOUND", category: "SYSTEM", description: "\u5DE5\u5177\u672A\u627E\u5230", identify: (error) => { return error.message.includes("Tool not found") || error.message.includes("Failed to load tool"); }, getSolution: (error, context) => { return { message: "\u6307\u5B9A\u7684\u5DE5\u5177\u4E0D\u5B58\u5728", toolId: context == null ? void 0 : context.toolId, suggestions: [ "1. \u68C0\u67E5\u5DE5\u5177ID\u662F\u5426\u6B63\u786E", "2. \u786E\u8BA4\u5DE5\u5177\u5DF2\u5B89\u88C5", "3. \u4F7F\u7528 discover \u547D\u4EE4\u67E5\u770B\u53EF\u7528\u5DE5\u5177", "4. \u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5\u5DE5\u5177" ], autoRecoverable: false }; } }, UNKNOWN_ERROR: { code: "UNKNOWN_ERROR", category: "SYSTEM", description: "\u672A\u77E5\u7CFB\u7EDF\u9519\u8BEF", identify: (error) => { return true; }, getSolution: (error, context) => { return { message: "\u672A\u77E5\u7CFB\u7EDF\u9519\u8BEF", detail: error.message, stack: error.stack, context, suggestions: [ "1. \u67E5\u770B\u9519\u8BEF\u8BE6\u60C5", "2. \u91CD\u8BD5\u64CD\u4F5C", "3. \u62A5\u544A\u95EE\u9898\u7ED9\u5F00\u53D1\u8005" ], autoRecoverable: false }; } } }; module2.exports = SYSTEM_ERRORS; } }); // src/toolx/errors/ToolError.js var require_ToolError = __commonJS({ "src/toolx/errors/ToolError.js"(exports2, module2) { "use strict"; init_cjs_shims(); var ERROR_CATEGORIES = require_ErrorCategories(); var DEVELOPMENT_ERRORS = require_DevelopmentErrors(); var { VALIDATION_ERRORS, validateAgainstSchema } = require_ValidationErrors(); var SYSTEM_ERRORS = require_SystemErrors(); var ToolError = class _ToolError extends Error { // 静态错误定义 static CATEGORIES = ERROR_CATEGORIES; static DEVELOPMENT_ERRORS = DEVELOPMENT_ERRORS; static VALIDATION_ERRORS = VALIDATION_ERRORS; static SYSTEM_ERRORS = SYSTEM_ERRORS; // 工具函数 static validateAgainstSchema = validateAgainstSchema; constructor(message2, code = "UNKNOWN_ERROR", details = {}) { super(message2); this.name = "ToolError"; this.code = code; this.category = details.category || "UNKNOWN"; this.categoryInfo = ERROR_CATEGORIES[this.category]; this.solution = details.solution || null; this.retryable = details.retryable || false; this.businessError = details.businessError || null; this.context = details.context || {}; this.originalError = details.originalError || null; this.details = details; if (Error.captureStackTrace) { Error.captureStackTrace(this, _ToolError); } } /** * 从各种错误源创建 ToolError(增强版) * @param {Error|Object} source - 错误源 * @param {Object} context - 上下文信息 * @returns {ToolError} */ static from(source, context = {}) { if (source instanceof _ToolError) { return source; } if (source instanceof Error) { const analysis = _ToolError.analyze(source, context); return new _ToolError( source.message, analysis.code, { category: analysis.category, solution: analysis.solution, retryable: analysis.retryable, businessError: analysis.businessError, context, originalError: source, stack: source.stack } ); } if (source && typeof source === "object") { return new _ToolError( source.formatted || source.message || "Unknown error", source.code || source.category || "UNKNOWN_ERROR", { category: source.category, solution: source.solution, ...context } ); } return new _ToolError(String(source), "UNKNOWN_ERROR", context); } /** * 分析错误并返回结构化信息(核心方法,替代ToolErrorManager.analyzeError) * @param {Error} error - 原始错误 * @param {Object} context - 错误上下文 * @returns {Object} 分析结果 */ static analyze(error, context = {}) { var _a, _b, _c, _d, _e, _f; if (context.businessErrors && Array.isArray(context.businessErrors)) { for (const bizError of context.businessErrors) { if (_ToolError.isMatch(error, bizError.match || bizError.identify, context)) { return { category: ERROR_CATEGORIES.BUSINESS.name, code: bizError.code, description: bizError.description, solution: bizError.solution, retryable: bizError.retryable || false, businessError: bizError }; } } } if (context.schema && context.params) { const paramSchema = context.schema.parameters || context.schema; const validation = validateAgainstSchema(context.params, paramSchema); if (!validation.valid) { context.validationResult = validation; if (validation.missing && validation.missing.length > 0) { const errorDef = VALIDATION_ERRORS.MISSING_REQUIRED_PARAM; return { category: ERROR_CATEGORIES.VALIDATION.name, code: errorDef.code, description: errorDef.description, solution: errorDef.getSolution(error, context) }; } if (validation.typeErrors && validation.typeErrors.length > 0) { const errorDef = VALIDATION_ERRORS.INVALID_PARAM_TYPE; return { category: ERROR_CATEGORIES.VALIDATION.name, code: errorDef.code, description: errorDef.description, solution: errorDef.getSolution(error, context) }; } if (validation.enumErrors && validation.enumErrors.length > 0) { const errorDef = VALIDATION_ERRORS.PARAM_OUT_OF_RANGE; return { category: ERROR_CATEGORIES.VALIDATION.name, code: errorDef.code, description: errorDef.description, solution: errorDef.getSolution(error, context) }; } } } if (context.environment && ((_a = context.schema) == null ? void 0 : _a.environment)) { const envSchema = context.schema.environment; const missingEnvVars = []; if (envSchema.required && Array.isArray(envSchema.required)) { for (const envName of envSchema.required) { if (!context.environment[envName]) { missingEnvVars.push(envName); } } } if (missingEnvVars.length > 0) { context.missingEnvVars = missingEnvVars; const errorDef = VALIDATION_ERRORS.MISSING_ENV_VAR; return { category: ERROR_CATEGORIES.VALIDATION.name, code: errorDef.code, description: errorDef.description, solution: errorDef.getSolution(error, context) }; } } for (const [key, errorDef] of Object.entries(VALIDATION_ERRORS)) { if (errorDef.identify && errorDef.identify(error, context)) { return { category: ERROR_CATEGORIES.VALIDATION.name, code: errorDef.code, description: errorDef.description, solution: (_b = errorDef.getSolution) == null ? void 0 : _b.call(errorDef, error, context) }; } } for (const [key, errorDef] of Object.entries(DEVELOPMENT_ERRORS)) { if (errorDef.identify && errorDef.identify(error, context)) { return { category: ERROR_CATEGORIES.DEVELOPMENT.name, code: errorDef.code, description: errorDef.description, solution: (_c = errorDef.getSolution) == null ? void 0 : _c.call(errorDef, error, context) }; } } for (const [key, errorDef] of Object.entries(SYSTEM_ERRORS)) { if (errorDef.identify && errorDef.identify(error, context)) { return { category: ERROR_CATEGORIES.SYSTEM.name, code: errorDef.code, description: errorDef.description, solution: (_d = errorDef.getSolution) == null ? void 0 : _d.call(errorDef, error, context), retryable: ((_f = (_e = errorDef.getSolution) == null ? void 0 : _e.call(errorDef, error, context)) == null ? void 0 : _f.autoRecoverable) || false }; } } return { category: ERROR_CATEGORIES.SYSTEM.name, code: "UNKNOWN_ERROR", description: "\u672A\u77E5\u9519\u8BEF", solution: null }; } /** * 通用错误匹配器 * @param {Error} error - 错误对象 * @param {string|RegExp|Function} matcher - 匹配器 * @param {Object} context - 上下文 * @returns {boolean} 是否匹配 */ static isMatch(error, matcher, context = {}) { if (!matcher) return false; if (typeof matcher === "string") { return error.message && error.message.includes(matcher); } else if (matcher instanceof RegExp) { return error.message && matcher.test(error.message); } else if (typeof matcher === "function") { return matcher(error, context); } return false; } /** * 转换为简单对象(用于序列化) * @returns {Object} */ toJSON() { return { name: this.name, message: this.message, code: this.code, category: this.category, categoryInfo: this.categoryInfo, solution: this.solution, retryable: this.retryable, businessError: this.businessError, context: this.context, details: this.details }; } /** * 格式化为 MCP 响应格式 * @returns {Object} */ toMCPFormat() { return { code: this.code, message: this.message, category: this.category, solution: this.solution, retryable: this.retryable, details: this.details }; } }; ToolError.CODES = { // 验证错误 VALIDATION_ERROR: "VALIDATION_ERROR", MISSING_PARAM: "MISSING_PARAM", INVALID_TYPE: "INVALID_TYPE", // 开发错误 MISSING_DEPENDENCY: "MISSING_DEPENDENCY", SYNTAX_ERROR: "SYNTAX_ERROR", // 系统错误 EXECUTION_ERROR: "EXECUTION_ERROR", TIMEOUT: "TIMEOUT", FILE_NOT_FOUND: "FILE_NOT_FOUND", // 通用 UNKNOWN_ERROR: "UNKNOWN_ERROR" }; module2.exports = ToolError; } }); // src/toolx/errors/index.js var require_errors = __commonJS({ "src/toolx/errors/index.js"(exports2, module2) { "use strict"; init_cjs_shims(); var ToolError = require_ToolError(); module2.exports = { // 增强的错误类(统一错误处理入口) ToolError, // 错误分类(通过ToolError访问) ERROR_CATEGORIES: ToolError.CATEGORIES, // 各类错误定义(通过ToolError访问) DEVELOPMENT_ERRORS: ToolError.DEVELOPMENT_ERRORS, VALIDATION_ERRORS: ToolError.VALIDATION_ERRORS, SYSTEM_ERRORS: ToolError.SYSTEM_ERRORS, // 工具函数(通过ToolError访问) validateAgainstSchema: ToolError.validateAgainstSchema, checkMissingEnvVars: ToolError.checkMissingEnvVars }; } }); // src/toolx/ToolDirectoryManager.js var require_ToolDirectoryManager = __commonJS({ "src/toolx/ToolDirectoryManager.js"(exports2, module2) { "use strict"; init_cjs_shims(); var path2 = require("path"); var fs2 = require("fs").promises; var logger2 = require("@promptx/logger"); var ToolDirectoryManager = class { constructor(toolId2, resourceManager) { this.toolId = toolId2; this.resourceManager = resourceManager; this.directories = { working: "@user://.promptx", // 工作目录 toolbox: `@user://.promptx/toolbox/${toolId2}`, // 工具隔离目录 dependencies: `@user://.promptx/toolbox/${toolId2}/node_modules`, // 依赖目录 cache: `@user://.promptx/cache/${toolId2}`, // 缓存目录 temp: `@user://.promptx/temp/${toolId2}` // 临时文件目录 }; this.resolvedPaths = {}; } /** * 初始化所有路径(通过协议解析) */ async initialize() { for (const [key, protocolPath] of Object.entries(this.directories)) { this.resolvedPaths[key] = await this.resolveProtocolPath(protocolPath); } logger2.debug("[ToolDirectoryManager] Initialized paths:", this.resolvedPaths); } /** * 通过协议解析路径 * @param {string} protocolPath - 协议路径,如 @user://.promptx * @returns {Promise<string>} 解析后的绝对路径 */ async resolveProtocolPath(protocolPath) { const result = await this.resourceManager.resolveProtocolReference(protocolPath); if (!result.success) { throw new Error(`Failed to resolve protocol path ${protocolPath}: ${result.error}`); } const protocol = this.resourceManager.protocols.get(result.protocol); if (!protocol) { throw new Error(`Protocol ${result.protocol} not supported`); } if (typeof protocol.resolvePath === "function") { return await protocol.resolvePath(result.path, result.queryParams || /* @__PURE__ */ new Map()); } else { throw new Error(`Protocol ${result.protocol} does not support path resolution`); } } /** * 获取工作目录路径 * @returns {string} 工作目录路径 */ getWorkingPath() { return this.resolvedPaths.working; } /** * 获取工具箱目录路径 * @returns {string} 工具箱目录路径 */ getToolboxPath() { return this.resolvedPaths.toolbox; } /** * 获取依赖目录路径 * @returns {string} node_modules 路径 */ getDependenciesPath() { return this.resolvedPaths.dependencies; } /** * 获取缓存目录路径 * @returns {string} 缓存目录路径 */ getCachePath() { return this.resolvedPaths.cache; } /** * 获取临时目录路径 * @returns {string} 临时目录路径 */ getTempPath() { return this.resolvedPaths.temp; } /** * 获取 package.json 路径 * @returns {string} package.json 路径 */ getPackageJsonPath() { return path2.join(this.resolvedPaths.toolbox, "package.json"); } /** * 确保必要的目录存在 */ async ensureDirectories() { await this.ensureDirectory(this.resolvedPaths.working); await this.ensureDirectory(this.resolvedPaths.toolbox); } /** * 确保单个目录存在 * @param {string} dirPath - 目录路径 */ async ensureDirectory(dirPath) { try { await fs2.access(dirPath); } catch (error) { if (error.code === "ENOENT") { await fs2.mkdir(dirPath, { recursive: true }); logger2.debug(`[ToolDirectoryManager] Created directory: ${dirPath}`); } else { throw error; } } } /** * 检查目录是否存在 * @param {string} dirPath - 目录路径 * @returns {Promise<boolean>} 是否存在 */ async directoryExists(dirPath) { try { await fs2.access(dirPath); return true; } catch { return false; } } /** * 检查工具箱目录是否存在 * @returns {Promise<boolean>} */ async toolboxExists() { return await this.directoryExists(this.resolvedPaths.toolbox); } /** * 清理临时文件 */ async cleanupTemp() { if (this.resolvedPaths.temp && await this.directoryExists(this.resolvedPaths.temp)) { const { rmdir } = require("fs").promises; await rmdir(this.resolvedPaths.temp, { recursive: true }); logger2.debug(`[ToolDirectoryManager] Cleaned up temp directory: ${this.resolvedPaths.temp}`); } } /** * 删除工具箱目录(用于强制重建) */ async deleteToolbox() { if (this.resolvedPaths.toolbox && await this.toolboxExists()) { const { rmdir } = require("fs").promises; await rmdir(this.resolvedPaths.toolbox, { recursive: true }); logger2.debug(`[ToolDirectoryManager] Deleted toolbox directory: ${this.resolvedPaths.toolbox}`); } } /** * 获取协议路径(用于日志或调试) * @param {string} key - 目录键名 * @returns {string} 协议路径 */ getProtocolPath(key) { return this.directories[key]; } /** * 支持自定义协议路径(未来扩展) * 比如支持 @project:// 或 @s3:// 等 */ async setCustomDirectory(key, protocolPath) { this.directories[key] = protocolPath; this.resolvedPaths[key] = await this.resolveProtocolPath(protocolPath); } }; module2.exports = ToolDirectoryManager; } }); // src/toolx/ElectronPolyfills.js var require_ElectronPolyfills = __commonJS({ "src/toolx/ElectronPolyfills.js"(exports2, module2) { "use strict"; init_cjs_shims(); var logger2 = require("@promptx/logger"); var ElectronPolyfills = class { constructor() { this.polyfills = {}; this.isElectron = this.detectElectronEnvironment(); } /** * 检测是否在Electron环境中运行 * @returns {boolean} */ detectElectronEnvironment() { const checks = [ // 检查process.versions.electron () => typeof process !== "undefined" && process.versions && !!process.versions.electron, // 检查process.type () => typeof process !== "undefined" && (process.type === "renderer" || process.type === "browser"), // 检查window.process(Electron特有) () => typeof window !== "undefined" && window.process && window.process.type, // 检查navigator.userAgent () => typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.includes("Electron") ]; return checks.some((check) => { try { return check(); } catch { return false; } }); } /** * 获取所有需要的polyfills * @returns {Object} polyfill对象集合 */ getPolyfills() { logger2.info("[ElectronPolyfills] getPolyfills called"); const polyfills = {}; this.addURLPolyfills(polyfills); this.addTextEncodingPolyfills(polyfills); this.addBase64Polyfills(polyfills); logger2.info("[ElectronPolyfills] Calling addFileAPIPolyfills"); this.addFileAPIPolyfills(polyfills); logger2.info("[ElectronPolyfills] Polyfills ready, keys:", Object.keys(polyfills)); return polyfills; } /** * 添加URL相关的polyfills */ addURLPolyfills(polyfills) { try { if (typeof URL === "undefined") { const { URL: URL2, URLSearchParams: URLSearchParams2 } = require("url"); polyfills.URL = URL2; polyfills.URLSearchParams = URLSearchParams2; logger2.debug("[ElectronPolyfills] Added URL and URLSearchParams"); } } catch (error) { logger2.warn("[ElectronPolyfills] Failed to add URL polyfills:", error.message); } } /** * 添加文本编码相关的polyfills */ addTextEncodingPolyfills(polyfills) { try { if (typeof TextEncoder === "undefined") { const { TextEncoder: TextEncoder2, TextDecoder } = require("util"); polyfills.TextEncoder = TextEncoder2; polyfills.TextDecoder = TextDecoder; logger2.debug("[ElectronPolyfills] Added TextEncoder and TextDecoder"); } } catch (error) { logger2.warn("[ElectronPolyfills] Failed to add text encoding polyfills:", error.message); } } /** * 添加Base64编码polyfills */ addBase64Polyfills(polyfills) { try { if (typeof btoa === "undefined") { polyfills.btoa = (str) => Buffer.from(str, "binary").toString("base64"); polyfills.atob = (str) => Buffer.from(str, "base64").toString("binary"); logger2.debug("[ElectronPolyfills] Added btoa and atob"); } } catch (error) { logger2.warn("[ElectronPolyfills] Failed to add base64 polyfills:", error.message); } } /** * 添加File和Blob API polyfills * 只在Electron环境中添加,提供最小化的安全实现 */ addFileAPIPolyfills(polyfills) { logger2.info("[ElectronPolyfills] addFileAPIPolyfills called"); try { class FilePolyfill { constructor(chunks, filename, options = {}) { this.name = filename; this.lastModified = options.lastModified || Date.now(); this.type = options.type || "application/octet-stream"; let buffer; if (chunks.length === 0) { buffer = Buffer.alloc(0); } else if (Buffer.isBuffer(chunks[0])) { buffer = Buffer.concat(chunks); } else if (typeof chunks[0] === "string") { buffer = Buffer.from(chunks.join("")); } else if (chunks[0] instanceof ArrayBuffer) { buffer = Buffer.from(chunks[0]); } else { buffer = Buffer.from(String(chunks[0])); } this.size = buffer.length; this._buffer = buffer; } // 提供基本的方法 async arrayBuffer() { return this._buffer.buffer.slice( this._buffer.byteOffset, this._buffer.byteOffset + this._buffer.byteLength ); } async text() { return this._buffer.toString("utf-8"); } stream() { const { Readable } = require("stream"); return Readable.from(this._buffer); } slice(start = 0, end = this.size, contentType) { const sliced = this._buffer.slice(start, end); return new FilePolyfill([slic