mta-mcp 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/bin/mta.cjs +43 -0
  2. package/dist/index.cjs +4784 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +1 -0
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +4769 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +21 -10
  9. package/build/core/agentTemplate.d.ts +0 -33
  10. package/build/core/agentTemplate.d.ts.map +0 -1
  11. package/build/core/agentTemplate.js +0 -158
  12. package/build/core/agentTemplate.js.map +0 -1
  13. package/build/core/analyzers/eslint.d.ts +0 -51
  14. package/build/core/analyzers/eslint.d.ts.map +0 -1
  15. package/build/core/analyzers/eslint.js +0 -259
  16. package/build/core/analyzers/eslint.js.map +0 -1
  17. package/build/core/analyzers/index.d.ts +0 -9
  18. package/build/core/analyzers/index.d.ts.map +0 -1
  19. package/build/core/analyzers/index.js +0 -9
  20. package/build/core/analyzers/index.js.map +0 -1
  21. package/build/core/analyzers/registry.d.ts +0 -59
  22. package/build/core/analyzers/registry.d.ts.map +0 -1
  23. package/build/core/analyzers/registry.js +0 -241
  24. package/build/core/analyzers/registry.js.map +0 -1
  25. package/build/core/analyzers/tsconfig.d.ts +0 -45
  26. package/build/core/analyzers/tsconfig.d.ts.map +0 -1
  27. package/build/core/analyzers/tsconfig.js +0 -197
  28. package/build/core/analyzers/tsconfig.js.map +0 -1
  29. package/build/core/analyzers/types.d.ts +0 -176
  30. package/build/core/analyzers/types.d.ts.map +0 -1
  31. package/build/core/analyzers/types.js +0 -39
  32. package/build/core/analyzers/types.js.map +0 -1
  33. package/build/core/analyzers/vite.d.ts +0 -46
  34. package/build/core/analyzers/vite.d.ts.map +0 -1
  35. package/build/core/analyzers/vite.js +0 -211
  36. package/build/core/analyzers/vite.js.map +0 -1
  37. package/build/core/autoInitializer.d.ts +0 -34
  38. package/build/core/autoInitializer.d.ts.map +0 -1
  39. package/build/core/autoInitializer.js +0 -145
  40. package/build/core/autoInitializer.js.map +0 -1
  41. package/build/core/codeValidator.d.ts +0 -82
  42. package/build/core/codeValidator.d.ts.map +0 -1
  43. package/build/core/codeValidator.js +0 -287
  44. package/build/core/codeValidator.js.map +0 -1
  45. package/build/core/enhancedProjectAnalyzer.d.ts +0 -102
  46. package/build/core/enhancedProjectAnalyzer.d.ts.map +0 -1
  47. package/build/core/enhancedProjectAnalyzer.js +0 -312
  48. package/build/core/enhancedProjectAnalyzer.js.map +0 -1
  49. package/build/core/errors.d.ts +0 -84
  50. package/build/core/errors.d.ts.map +0 -1
  51. package/build/core/errors.js +0 -151
  52. package/build/core/errors.js.map +0 -1
  53. package/build/core/githubClient.d.ts +0 -26
  54. package/build/core/githubClient.d.ts.map +0 -1
  55. package/build/core/githubClient.js +0 -60
  56. package/build/core/githubClient.js.map +0 -1
  57. package/build/core/i18nDetector.d.ts +0 -47
  58. package/build/core/i18nDetector.d.ts.map +0 -1
  59. package/build/core/i18nDetector.js +0 -314
  60. package/build/core/i18nDetector.js.map +0 -1
  61. package/build/core/index.d.ts +0 -11
  62. package/build/core/index.d.ts.map +0 -1
  63. package/build/core/index.js +0 -14
  64. package/build/core/index.js.map +0 -1
  65. package/build/core/logger.d.ts +0 -91
  66. package/build/core/logger.d.ts.map +0 -1
  67. package/build/core/logger.js +0 -164
  68. package/build/core/logger.js.map +0 -1
  69. package/build/core/mappings/index.d.ts +0 -5
  70. package/build/core/mappings/index.d.ts.map +0 -1
  71. package/build/core/mappings/index.js +0 -5
  72. package/build/core/mappings/index.js.map +0 -1
  73. package/build/core/mappings/scenarioMappings.d.ts +0 -51
  74. package/build/core/mappings/scenarioMappings.d.ts.map +0 -1
  75. package/build/core/mappings/scenarioMappings.js +0 -105
  76. package/build/core/mappings/scenarioMappings.js.map +0 -1
  77. package/build/core/matching/index.d.ts +0 -8
  78. package/build/core/matching/index.d.ts.map +0 -1
  79. package/build/core/matching/index.js +0 -8
  80. package/build/core/matching/index.js.map +0 -1
  81. package/build/core/matching/intentAnalyzer.d.ts +0 -78
  82. package/build/core/matching/intentAnalyzer.d.ts.map +0 -1
  83. package/build/core/matching/intentAnalyzer.js +0 -255
  84. package/build/core/matching/intentAnalyzer.js.map +0 -1
  85. package/build/core/matching/standardMatcher.d.ts +0 -101
  86. package/build/core/matching/standardMatcher.d.ts.map +0 -1
  87. package/build/core/matching/standardMatcher.js +0 -299
  88. package/build/core/matching/standardMatcher.js.map +0 -1
  89. package/build/core/matching/weights.d.ts +0 -64
  90. package/build/core/matching/weights.d.ts.map +0 -1
  91. package/build/core/matching/weights.js +0 -334
  92. package/build/core/matching/weights.js.map +0 -1
  93. package/build/core/projectContextManager.d.ts +0 -39
  94. package/build/core/projectContextManager.d.ts.map +0 -1
  95. package/build/core/projectContextManager.js +0 -147
  96. package/build/core/projectContextManager.js.map +0 -1
  97. package/build/core/scenarioDetector.d.ts +0 -2
  98. package/build/core/scenarioDetector.d.ts.map +0 -1
  99. package/build/core/scenarioDetector.js +0 -2
  100. package/build/core/scenarioDetector.js.map +0 -1
  101. package/build/core/smartAgentMatcher.d.ts +0 -51
  102. package/build/core/smartAgentMatcher.d.ts.map +0 -1
  103. package/build/core/smartAgentMatcher.js +0 -493
  104. package/build/core/smartAgentMatcher.js.map +0 -1
  105. package/build/core/standardsManager.d.ts +0 -130
  106. package/build/core/standardsManager.d.ts.map +0 -1
  107. package/build/core/standardsManager.js +0 -600
  108. package/build/core/standardsManager.js.map +0 -1
  109. package/build/core/templates/discovery.d.ts +0 -41
  110. package/build/core/templates/discovery.d.ts.map +0 -1
  111. package/build/core/templates/discovery.js +0 -262
  112. package/build/core/templates/discovery.js.map +0 -1
  113. package/build/core/templates/types.d.ts +0 -80
  114. package/build/core/templates/types.d.ts.map +0 -1
  115. package/build/core/templates/types.js +0 -10
  116. package/build/core/templates/types.js.map +0 -1
  117. package/build/core/types.d.ts +0 -57
  118. package/build/core/types.d.ts.map +0 -1
  119. package/build/core/types.js +0 -22
  120. package/build/core/types.js.map +0 -1
  121. package/build/index.d.ts +0 -3
  122. package/build/index.d.ts.map +0 -1
  123. package/build/index.js +0 -576
  124. package/build/index.js.map +0 -1
  125. package/build/tools/analyzeProject.d.ts +0 -12
  126. package/build/tools/analyzeProject.d.ts.map +0 -1
  127. package/build/tools/analyzeProject.js +0 -85
  128. package/build/tools/analyzeProject.js.map +0 -1
  129. package/build/tools/autoSetup.d.ts +0 -15
  130. package/build/tools/autoSetup.d.ts.map +0 -1
  131. package/build/tools/autoSetup.js +0 -291
  132. package/build/tools/autoSetup.js.map +0 -1
  133. package/build/tools/generateConfig.d.ts +0 -16
  134. package/build/tools/generateConfig.d.ts.map +0 -1
  135. package/build/tools/generateConfig.js +0 -379
  136. package/build/tools/generateConfig.js.map +0 -1
  137. package/build/tools/generateProjectAgent.d.ts +0 -15
  138. package/build/tools/generateProjectAgent.d.ts.map +0 -1
  139. package/build/tools/generateProjectAgent.js +0 -348
  140. package/build/tools/generateProjectAgent.js.map +0 -1
  141. package/build/tools/getCompactStandards.d.ts +0 -20
  142. package/build/tools/getCompactStandards.d.ts.map +0 -1
  143. package/build/tools/getCompactStandards.js +0 -367
  144. package/build/tools/getCompactStandards.js.map +0 -1
  145. package/build/tools/getSmartStandards.d.ts +0 -15
  146. package/build/tools/getSmartStandards.d.ts.map +0 -1
  147. package/build/tools/getSmartStandards.js +0 -201
  148. package/build/tools/getSmartStandards.js.map +0 -1
  149. package/build/tools/getStandardById.d.ts +0 -42
  150. package/build/tools/getStandardById.d.ts.map +0 -1
  151. package/build/tools/getStandardById.js +0 -289
  152. package/build/tools/getStandardById.js.map +0 -1
  153. package/build/tools/getTemplate.d.ts +0 -37
  154. package/build/tools/getTemplate.d.ts.map +0 -1
  155. package/build/tools/getTemplate.js +0 -78
  156. package/build/tools/getTemplate.js.map +0 -1
  157. package/build/tools/healthCheck.d.ts +0 -14
  158. package/build/tools/healthCheck.d.ts.map +0 -1
  159. package/build/tools/healthCheck.js +0 -237
  160. package/build/tools/healthCheck.js.map +0 -1
  161. package/build/tools/listAgents.d.ts +0 -10
  162. package/build/tools/listAgents.d.ts.map +0 -1
  163. package/build/tools/listAgents.js +0 -79
  164. package/build/tools/listAgents.js.map +0 -1
  165. package/build/tools/listTemplates.d.ts +0 -41
  166. package/build/tools/listTemplates.d.ts.map +0 -1
  167. package/build/tools/listTemplates.js +0 -81
  168. package/build/tools/listTemplates.js.map +0 -1
  169. package/build/tools/matchAgents.d.ts +0 -14
  170. package/build/tools/matchAgents.d.ts.map +0 -1
  171. package/build/tools/matchAgents.js +0 -70
  172. package/build/tools/matchAgents.js.map +0 -1
  173. package/build/tools/queryMappings.d.ts +0 -55
  174. package/build/tools/queryMappings.d.ts.map +0 -1
  175. package/build/tools/queryMappings.js +0 -119
  176. package/build/tools/queryMappings.js.map +0 -1
  177. package/build/tools/usePreset.d.ts +0 -23
  178. package/build/tools/usePreset.d.ts.map +0 -1
  179. package/build/tools/usePreset.js +0 -163
  180. package/build/tools/usePreset.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,4784 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // node_modules/tsup/assets/cjs_shims.js
27
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
+
30
+ // src/index.ts
31
+ var import_server = require("@modelcontextprotocol/sdk/server/index.js");
32
+ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
33
+ var import_types16 = require("@modelcontextprotocol/sdk/types.js");
34
+
35
+ // src/tools/analyzeProject.ts
36
+ var fs3 = __toESM(require("fs"), 1);
37
+ var path3 = __toESM(require("path"), 1);
38
+
39
+ // src/core/smartAgentMatcher.ts
40
+ var fs = __toESM(require("fs"), 1);
41
+ var path = __toESM(require("path"), 1);
42
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
43
+ var SmartAgentMatcher = class {
44
+ constructor(logger3) {
45
+ this.logger = logger3;
46
+ }
47
+ /**
48
+ * 分析项目特征
49
+ */
50
+ async analyzeProject(workspaceFolder) {
51
+ this.log(`\u{1F50D} \u5F00\u59CB\u5206\u6790\u9879\u76EE: ${workspaceFolder.name}`);
52
+ const features = {
53
+ frameworks: [],
54
+ languages: [],
55
+ tools: [],
56
+ keywords: [],
57
+ projectType: "unknown"
58
+ };
59
+ const rootPath = workspaceFolder.uri.fsPath;
60
+ const pubspecPath = path.join(rootPath, "pubspec.yaml");
61
+ if (fs.existsSync(pubspecPath)) {
62
+ const pubspecFeatures = this.analyzePubspecYaml(pubspecPath);
63
+ this.mergeFeatures(features, pubspecFeatures);
64
+ features.projectType = "flutter";
65
+ this.log(`\u2705 \u9879\u76EE\u5206\u6790\u5B8C\u6210: ${features.projectType}`);
66
+ return features;
67
+ }
68
+ const packageJsonPath = path.join(rootPath, "package.json");
69
+ if (fs.existsSync(packageJsonPath)) {
70
+ const packageFeatures = this.analyzePackageJson(packageJsonPath);
71
+ this.mergeFeatures(features, packageFeatures);
72
+ }
73
+ const structureFeatures = await this.analyzeFileStructure(rootPath);
74
+ this.mergeFeatures(features, structureFeatures);
75
+ features.projectType = this.inferProjectType(features);
76
+ this.log(`\u2705 \u9879\u76EE\u5206\u6790\u5B8C\u6210: ${features.projectType}`);
77
+ return features;
78
+ }
79
+ /**
80
+ * 分析 package.json
81
+ */
82
+ analyzePackageJson(packageJsonPath) {
83
+ var _a, _b;
84
+ const features = {
85
+ frameworks: [],
86
+ languages: [],
87
+ tools: [],
88
+ keywords: []
89
+ };
90
+ try {
91
+ const content = fs.readFileSync(packageJsonPath, "utf-8");
92
+ const packageJson = JSON.parse(content);
93
+ const allDeps = {
94
+ ...packageJson.dependencies,
95
+ ...packageJson.devDependencies
96
+ };
97
+ if (allDeps["vue"]) features.frameworks.push("Vue 3");
98
+ if (allDeps["react"]) features.frameworks.push("React");
99
+ if (allDeps["@angular/core"]) features.frameworks.push("Angular");
100
+ if (allDeps["next"]) features.frameworks.push("Next.js");
101
+ if (allDeps["nuxt"]) features.frameworks.push("Nuxt.js");
102
+ if (allDeps["svelte"]) features.frameworks.push("Svelte");
103
+ if (allDeps["solid-js"]) features.frameworks.push("Solid.js");
104
+ if (allDeps["preact"]) features.frameworks.push("Preact");
105
+ if (allDeps["remix"]) features.frameworks.push("Remix");
106
+ if (allDeps["astro"]) features.frameworks.push("Astro");
107
+ if (allDeps["express"]) features.frameworks.push("Express");
108
+ if (allDeps["koa"]) features.frameworks.push("Koa");
109
+ if (allDeps["fastify"]) features.frameworks.push("Fastify");
110
+ if (allDeps["nestjs"] || allDeps["@nestjs/core"]) features.frameworks.push("NestJS");
111
+ if (allDeps["egg"]) features.frameworks.push("Egg.js");
112
+ if (allDeps["midway"]) features.frameworks.push("Midway");
113
+ if (allDeps["hapi"]) features.frameworks.push("Hapi");
114
+ if (allDeps["meteor"]) features.frameworks.push("Meteor");
115
+ if (allDeps["blitz"]) features.frameworks.push("Blitz.js");
116
+ if (allDeps["vite"]) features.tools.push("Vite");
117
+ if (allDeps["webpack"]) features.tools.push("Webpack");
118
+ if (allDeps["rollup"]) features.tools.push("Rollup");
119
+ if (allDeps["parcel"]) features.tools.push("Parcel");
120
+ if (allDeps["esbuild"]) features.tools.push("ESBuild");
121
+ if (allDeps["turbopack"]) features.tools.push("Turbopack");
122
+ if (allDeps["element-plus"]) features.tools.push("Element Plus");
123
+ if (allDeps["ant-design-vue"]) features.tools.push("Ant Design Vue");
124
+ if (allDeps["antd"]) features.tools.push("Ant Design");
125
+ if (allDeps["@mui/material"]) features.tools.push("Material-UI");
126
+ if (allDeps["naive-ui"]) features.tools.push("Naive UI");
127
+ if (allDeps["vuetify"]) features.tools.push("Vuetify");
128
+ if (allDeps["quasar"]) features.tools.push("Quasar");
129
+ if (allDeps["primevue"]) features.tools.push("PrimeVue");
130
+ if (allDeps["chakra-ui"]) features.tools.push("Chakra UI");
131
+ if (allDeps["@headlessui/react"] || allDeps["@headlessui/vue"]) features.tools.push("Headless UI");
132
+ if (allDeps["daisyui"]) features.tools.push("DaisyUI");
133
+ if (allDeps["shadcn-ui"] || allDeps["@shadcn/ui"]) features.tools.push("Shadcn UI");
134
+ if (allDeps["tailwindcss"]) features.tools.push("Tailwind CSS");
135
+ if (allDeps["sass"] || allDeps["node-sass"]) features.tools.push("Sass");
136
+ if (allDeps["less"]) features.tools.push("Less");
137
+ if (allDeps["postcss"]) features.tools.push("PostCSS");
138
+ if (allDeps["styled-components"]) features.tools.push("Styled Components");
139
+ if (allDeps["emotion"]) features.tools.push("Emotion");
140
+ if (allDeps["unocss"]) features.tools.push("UnoCSS");
141
+ if (allDeps["@logicflow/core"]) features.tools.push("LogicFlow");
142
+ if (allDeps["echarts"]) features.tools.push("ECharts");
143
+ if (allDeps["d3"]) features.tools.push("D3.js");
144
+ if (allDeps["chart.js"]) features.tools.push("Chart.js");
145
+ if (allDeps["antv"] || allDeps["@antv/g6"]) features.tools.push("AntV");
146
+ if (allDeps["typescript"]) features.languages.push("TypeScript");
147
+ if (((_a = packageJson.dependencies) == null ? void 0 : _a["react"]) || ((_b = packageJson.devDependencies) == null ? void 0 : _b["react"])) {
148
+ features.languages.push("JavaScript");
149
+ }
150
+ if (allDeps["vue-i18n"] || allDeps["react-i18n"] || allDeps["i18next"] || allDeps["react-intl"]) {
151
+ features.keywords.push("i18n");
152
+ }
153
+ if (allDeps["pinia"] || allDeps["vuex"] || allDeps["redux"] || allDeps["@reduxjs/toolkit"] || allDeps["mobx"] || allDeps["zustand"] || allDeps["recoil"] || allDeps["jotai"]) {
154
+ features.keywords.push("state-management");
155
+ }
156
+ if (allDeps["vue-router"] || allDeps["react-router"] || allDeps["react-router-dom"] || allDeps["@tanstack/react-router"]) {
157
+ features.keywords.push("routing");
158
+ }
159
+ if (allDeps["axios"] || allDeps["@tanstack/react-query"] || allDeps["@tanstack/vue-query"] || allDeps["swr"] || allDeps["urql"]) {
160
+ features.keywords.push("data-fetching");
161
+ }
162
+ if (allDeps["formik"] || allDeps["react-hook-form"] || allDeps["vee-validate"] || allDeps["@vuelidate/core"]) {
163
+ features.keywords.push("forms");
164
+ }
165
+ if (allDeps["vitest"] || allDeps["jest"] || allDeps["@testing-library/react"] || allDeps["@testing-library/vue"] || allDeps["cypress"] || allDeps["playwright"]) {
166
+ features.keywords.push("testing");
167
+ }
168
+ if (allDeps["vant"] || allDeps["@tarojs/taro"] || allDeps["react-native"] || allDeps["uni-app"] || allDeps["@nutui/nutui"]) {
169
+ features.keywords.push("mobile");
170
+ }
171
+ if (packageJson.miniprogram || allDeps["@tarojs/taro"] || allDeps["uni-app"]) {
172
+ features.keywords.push("miniprogram");
173
+ features.keywords.push("wechat");
174
+ }
175
+ if (allDeps["prisma"] || allDeps["typeorm"] || allDeps["sequelize"] || allDeps["mongoose"]) {
176
+ features.keywords.push("database");
177
+ }
178
+ if (allDeps["graphql"] || allDeps["apollo-client"] || allDeps["@apollo/client"]) {
179
+ features.keywords.push("graphql");
180
+ }
181
+ } catch (error) {
182
+ this.log(`\u89E3\u6790 package.json \u5931\u8D25: ${error}`);
183
+ }
184
+ return features;
185
+ }
186
+ /**
187
+ * 分析 pubspec.yaml (Flutter 项目)
188
+ */
189
+ analyzePubspecYaml(pubspecPath) {
190
+ const features = {
191
+ frameworks: ["Flutter"],
192
+ languages: ["Dart"],
193
+ tools: [],
194
+ keywords: []
195
+ };
196
+ try {
197
+ const content = fs.readFileSync(pubspecPath, "utf-8");
198
+ if (content.includes("provider:")) features.keywords.push("state-management");
199
+ if (content.includes("riverpod:")) features.keywords.push("state-management");
200
+ if (content.includes("bloc:") || content.includes("flutter_bloc:")) features.keywords.push("state-management");
201
+ if (content.includes("get:") || content.includes("get_x:")) {
202
+ features.keywords.push("routing", "state-management");
203
+ }
204
+ if (content.includes("flutter_localizations:") || content.includes("intl:") || content.includes("easy_localization:")) {
205
+ features.keywords.push("i18n");
206
+ }
207
+ if (content.includes("go_router:") || content.includes("auto_route:")) features.keywords.push("routing");
208
+ if (content.includes("dio:") || content.includes("http:")) features.keywords.push("data-fetching");
209
+ if (content.includes("flutter_screenutil:")) features.tools.push("ScreenUtil");
210
+ if (content.includes("flutter_test:") || content.includes("mockito:") || content.includes("integration_test:")) {
211
+ features.keywords.push("testing");
212
+ }
213
+ } catch (error) {
214
+ this.log(`\u89E3\u6790 pubspec.yaml \u5931\u8D25: ${error}`);
215
+ }
216
+ return features;
217
+ }
218
+ /**
219
+ * 分析文件结构
220
+ */
221
+ async analyzeFileStructure(rootPath) {
222
+ const features = {
223
+ frameworks: [],
224
+ languages: [],
225
+ tools: [],
226
+ keywords: []
227
+ };
228
+ try {
229
+ const patterns = [
230
+ "**/*.vue",
231
+ "**/*.ts",
232
+ "**/*.tsx",
233
+ "**/*.jsx",
234
+ "**/*.js",
235
+ "**/*.py",
236
+ "**/*.java",
237
+ "**/*.go",
238
+ "**/*.rs",
239
+ "**/*.cpp",
240
+ "**/*.c",
241
+ "**/locales/**",
242
+ "**/i18n/**",
243
+ "**/lang/**",
244
+ "**/stores/**",
245
+ "**/store/**",
246
+ "**/redux/**",
247
+ "**/*.test.*",
248
+ "**/*.spec.*",
249
+ "**/components/**",
250
+ "**/pages/**",
251
+ "**/views/**"
252
+ ];
253
+ const files = await (0, import_fast_glob.default)(patterns, {
254
+ cwd: rootPath,
255
+ ignore: ["**/node_modules/**", "**/dist/**", "**/build/**", "**/.git/**"],
256
+ onlyFiles: true
257
+ });
258
+ if (files.some((f) => f.endsWith(".vue"))) features.frameworks.push("Vue");
259
+ if (files.some((f) => f.endsWith(".tsx"))) features.frameworks.push("React");
260
+ if (files.some((f) => f.endsWith(".svelte"))) features.frameworks.push("Svelte");
261
+ if (files.some((f) => f.endsWith(".ts") || f.endsWith(".tsx"))) features.languages.push("TypeScript");
262
+ if (files.some((f) => f.endsWith(".js") || f.endsWith(".jsx"))) features.languages.push("JavaScript");
263
+ if (files.some((f) => f.endsWith(".py"))) features.languages.push("Python");
264
+ if (files.some((f) => f.endsWith(".java"))) features.languages.push("Java");
265
+ if (files.some((f) => f.endsWith(".go"))) features.languages.push("Go");
266
+ if (files.some((f) => f.endsWith(".rs"))) features.languages.push("Rust");
267
+ if (files.some((f) => f.match(/\.(cpp|cc|cxx|c)$/))) features.languages.push("C/C++");
268
+ if (files.some((f) => f.includes("/locales/") || f.includes("/i18n/") || f.includes("/lang/"))) {
269
+ features.keywords.push("i18n");
270
+ }
271
+ if (files.some((f) => f.includes("/stores/") || f.includes("/store/") || f.includes("/redux/"))) {
272
+ features.keywords.push("state-management");
273
+ }
274
+ if (files.some((f) => f.includes(".test.") || f.includes(".spec."))) {
275
+ features.keywords.push("testing");
276
+ }
277
+ } catch (error) {
278
+ this.log(`\u626B\u63CF\u6587\u4EF6\u7ED3\u6784\u5931\u8D25: ${error}`);
279
+ }
280
+ return features;
281
+ }
282
+ /**
283
+ * 匹配 Agents
284
+ */
285
+ matchAgents(features, availableAgents) {
286
+ const scoredAgents = availableAgents.map((agent) => {
287
+ const score = this.calculateMatchScore(features, agent);
288
+ return { ...agent, score };
289
+ });
290
+ return scoredAgents.filter((a) => a.score > 0).sort((a, b) => (b.score || 0) - (a.score || 0));
291
+ }
292
+ /**
293
+ * 计算匹配分数
294
+ */
295
+ calculateMatchScore(features, agent) {
296
+ let score = 0;
297
+ const WEIGHTS = {
298
+ framework: 10,
299
+ tool: 8,
300
+ language: 5,
301
+ keyword: 3,
302
+ tag: 2
303
+ };
304
+ features.frameworks.forEach((f) => {
305
+ var _a, _b;
306
+ if ((_b = (_a = agent.applicableWhen) == null ? void 0 : _a.frameworks) == null ? void 0 : _b.some((af) => af.toLowerCase().includes(f.toLowerCase()))) {
307
+ score += WEIGHTS.framework;
308
+ }
309
+ });
310
+ features.tools.forEach((t) => {
311
+ var _a, _b;
312
+ if ((_b = (_a = agent.applicableWhen) == null ? void 0 : _a.tools) == null ? void 0 : _b.some((at) => at.toLowerCase().includes(t.toLowerCase()))) {
313
+ score += WEIGHTS.tool;
314
+ }
315
+ });
316
+ features.languages.forEach((l) => {
317
+ var _a, _b;
318
+ if ((_b = (_a = agent.applicableWhen) == null ? void 0 : _a.languages) == null ? void 0 : _b.some((al) => al.toLowerCase().includes(l.toLowerCase()))) {
319
+ score += WEIGHTS.language;
320
+ }
321
+ });
322
+ features.keywords.forEach((k) => {
323
+ var _a, _b;
324
+ if ((_b = (_a = agent.applicableWhen) == null ? void 0 : _a.keywords) == null ? void 0 : _b.some((ak) => ak.toLowerCase().includes(k.toLowerCase()))) {
325
+ score += WEIGHTS.keyword;
326
+ }
327
+ });
328
+ features.frameworks.concat(features.tools, features.languages, features.keywords).forEach((feature) => {
329
+ if (agent.tags.some((tag) => tag.toLowerCase().includes(feature.toLowerCase()))) {
330
+ score += WEIGHTS.tag;
331
+ }
332
+ });
333
+ return score;
334
+ }
335
+ /**
336
+ * 解析 Agent 元数据
337
+ */
338
+ parseAgentMetadata(filePath, content) {
339
+ const id = path.basename(filePath, ".agent.md");
340
+ let description = "";
341
+ let tags = [];
342
+ if (content.startsWith("---")) {
343
+ const endIndex = content.indexOf("---", 3);
344
+ if (endIndex > 0) {
345
+ const frontmatter = content.substring(3, endIndex);
346
+ const descMatch = frontmatter.match(/description:\s*['"](.+)['"]/);
347
+ if (descMatch) description = descMatch[1];
348
+ const tagsMatch = frontmatter.match(/tags:\s*\[(.+)\]/);
349
+ if (tagsMatch) {
350
+ tags = tagsMatch[1].split(",").map((t) => t.trim().replace(/['"]/g, ""));
351
+ }
352
+ }
353
+ }
354
+ const titleMatch = content.match(/^#\s+(.+)$/m);
355
+ const title = titleMatch ? titleMatch[1] : id;
356
+ return {
357
+ id,
358
+ path: filePath,
359
+ title,
360
+ description,
361
+ tags,
362
+ applicableWhen: {
363
+ frameworks: tags.filter(
364
+ (t) => [
365
+ "vue",
366
+ "vue3",
367
+ "react",
368
+ "angular",
369
+ "next",
370
+ "nuxt",
371
+ "svelte",
372
+ "flutter",
373
+ "express",
374
+ "nestjs",
375
+ "koa",
376
+ "fastify"
377
+ ].includes(t.toLowerCase())
378
+ ),
379
+ languages: tags.filter(
380
+ (t) => ["typescript", "javascript", "python", "java", "go", "rust", "dart", "c++"].includes(t.toLowerCase())
381
+ ),
382
+ tools: tags.filter(
383
+ (t) => [
384
+ "vite",
385
+ "webpack",
386
+ "rollup",
387
+ "logicflow",
388
+ "element-plus",
389
+ "antd",
390
+ "tailwind",
391
+ "sass",
392
+ "echarts",
393
+ "prisma",
394
+ "graphql"
395
+ ].includes(t.toLowerCase())
396
+ ),
397
+ keywords: tags.filter(
398
+ (t) => [
399
+ "i18n",
400
+ "state-management",
401
+ "routing",
402
+ "testing",
403
+ "mobile",
404
+ "miniprogram",
405
+ "database",
406
+ "forms",
407
+ "data-fetching"
408
+ ].includes(t.toLowerCase())
409
+ )
410
+ }
411
+ };
412
+ }
413
+ mergeFeatures(target, source) {
414
+ if (source.frameworks) target.frameworks.push(...source.frameworks);
415
+ if (source.languages) target.languages.push(...source.languages);
416
+ if (source.tools) target.tools.push(...source.tools);
417
+ if (source.keywords) target.keywords.push(...source.keywords);
418
+ }
419
+ inferProjectType(features) {
420
+ if (features.frameworks.some((f) => f.toLowerCase().includes("vue"))) return "vue3";
421
+ if (features.frameworks.some((f) => f.toLowerCase().includes("react"))) return "react";
422
+ if (features.frameworks.some((f) => f.toLowerCase().includes("angular"))) return "angular";
423
+ if (features.frameworks.some((f) => f.toLowerCase().includes("svelte"))) return "svelte";
424
+ if (features.frameworks.some((f) => f.toLowerCase().includes("next"))) return "nextjs";
425
+ if (features.frameworks.some((f) => f.toLowerCase().includes("nuxt"))) return "nuxtjs";
426
+ if (features.frameworks.some((f) => f.toLowerCase().includes("flutter"))) return "flutter";
427
+ if (features.frameworks.some((f) => f.toLowerCase().includes("react-native"))) return "react-native";
428
+ if (features.keywords.includes("miniprogram")) return "miniprogram";
429
+ if (features.frameworks.some((f) => f.toLowerCase().includes("nest"))) return "nestjs";
430
+ if (features.frameworks.some((f) => f.toLowerCase().includes("express"))) return "express";
431
+ if (features.frameworks.some((f) => f.toLowerCase().includes("koa"))) return "koa";
432
+ if (features.frameworks.some((f) => f.toLowerCase().includes("fastify"))) return "fastify";
433
+ if (features.languages.includes("TypeScript")) return "typescript";
434
+ if (features.languages.includes("Python")) return "python";
435
+ if (features.languages.includes("Java")) return "java";
436
+ if (features.languages.includes("Go")) return "go";
437
+ if (features.languages.includes("Rust")) return "rust";
438
+ return "general";
439
+ }
440
+ log(message) {
441
+ var _a;
442
+ (_a = this.logger) == null ? void 0 : _a.log(message);
443
+ }
444
+ };
445
+
446
+ // src/core/i18nDetector.ts
447
+ var fs2 = __toESM(require("fs"), 1);
448
+ var path2 = __toESM(require("path"), 1);
449
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
450
+ var I18nDetector = class {
451
+ /**
452
+ * 检测项目的国际化配置
453
+ */
454
+ static async detect(projectPath) {
455
+ const packageJsonPath = path2.join(projectPath, "package.json");
456
+ if (fs2.existsSync(packageJsonPath)) {
457
+ return this.detectFrontendI18n(projectPath, packageJsonPath);
458
+ }
459
+ const pubspecPath = path2.join(projectPath, "pubspec.yaml");
460
+ if (fs2.existsSync(pubspecPath)) {
461
+ return this.detectFlutterI18n(projectPath, pubspecPath);
462
+ }
463
+ return {
464
+ enabled: false,
465
+ type: "none",
466
+ configFiles: [],
467
+ messageFiles: [],
468
+ method: "",
469
+ example: "",
470
+ tips: ["\u9879\u76EE\u672A\u914D\u7F6E\u56FD\u9645\u5316\uFF0C\u5EFA\u8BAE\u6DFB\u52A0\u4E2D\u82F1\u53CC\u8BED\u652F\u6301"]
471
+ };
472
+ }
473
+ /**
474
+ * 检测前端项目的国际化配置(Vue/React)
475
+ */
476
+ static detectFrontendI18n(projectPath, packageJsonPath) {
477
+ const content = fs2.readFileSync(packageJsonPath, "utf-8");
478
+ const packageJson = JSON.parse(content);
479
+ const allDeps = {
480
+ ...packageJson.dependencies,
481
+ ...packageJson.devDependencies
482
+ };
483
+ if (allDeps["vue-i18n"]) {
484
+ return this.detectVueI18n(projectPath);
485
+ }
486
+ if (allDeps["react-i18next"] || allDeps["i18next"]) {
487
+ return this.detectReactI18n(projectPath);
488
+ }
489
+ if (allDeps["react-intl"]) {
490
+ return this.detectReactIntl(projectPath);
491
+ }
492
+ return this.detectCustomI18n(projectPath);
493
+ }
494
+ /**
495
+ * 检测 vue-i18n 配置
496
+ */
497
+ static detectVueI18n(projectPath) {
498
+ const configFiles = [];
499
+ const messageFiles = [];
500
+ const possibleConfigPaths = [
501
+ "src/i18n/index.ts",
502
+ "src/i18n/index.js",
503
+ "src/locales/index.ts",
504
+ "src/locales/index.js",
505
+ "i18n.config.ts",
506
+ "i18n.config.js"
507
+ ];
508
+ for (const configPath of possibleConfigPaths) {
509
+ const fullPath = path2.join(projectPath, configPath);
510
+ if (fs2.existsSync(fullPath)) {
511
+ configFiles.push(configPath);
512
+ }
513
+ }
514
+ const possibleMessageDirs = ["src/i18n", "src/locales", "src/lang"];
515
+ for (const dir of possibleMessageDirs) {
516
+ const fullDir = path2.join(projectPath, dir);
517
+ if (fs2.existsSync(fullDir)) {
518
+ const files = fs2.readdirSync(fullDir);
519
+ for (const file of files) {
520
+ if (/^(zh|en|ja|ko|fr|de|es).*\.(ts|js|json)$/.test(file)) {
521
+ messageFiles.push(path2.join(dir, file));
522
+ }
523
+ }
524
+ }
525
+ }
526
+ return {
527
+ enabled: true,
528
+ type: "vue-i18n",
529
+ configFiles,
530
+ messageFiles,
531
+ method: "$t()",
532
+ example: `{{ $t('common.save') }} \u6216 :label="$t('user.username')"`,
533
+ tips: [
534
+ '\u4F7F\u7528\u547D\u540D\u7A7A\u95F4\u683C\u5F0F\uFF1A$t("common.save")',
535
+ "\u6240\u6709\u6309\u94AE\u3001\u6807\u7B7E\u3001\u63D0\u793A\u6587\u5B57\u5FC5\u987B\u4F7F\u7528 $t()",
536
+ "\u8868\u5355\u9A8C\u8BC1\u89C4\u5219\u7684 message \u4E5F\u9700\u8981\u56FD\u9645\u5316",
537
+ "\u786E\u4FDD zh-CN.ts \u548C en-US.ts \u4E2D\u7684\u952E\u540D\u5B8C\u5168\u4E00\u81F4"
538
+ ]
539
+ };
540
+ }
541
+ /**
542
+ * 检测 react-i18next 配置
543
+ */
544
+ static detectReactI18n(projectPath) {
545
+ const configFiles = [];
546
+ const messageFiles = [];
547
+ const possibleConfigPaths = [
548
+ "src/i18n.ts",
549
+ "src/i18n.js",
550
+ "src/i18n/config.ts",
551
+ "src/i18n/config.js"
552
+ ];
553
+ for (const configPath of possibleConfigPaths) {
554
+ const fullPath = path2.join(projectPath, configPath);
555
+ if (fs2.existsSync(fullPath)) {
556
+ configFiles.push(configPath);
557
+ }
558
+ }
559
+ const possibleMessageDirs = ["public/locales", "src/locales", "src/i18n"];
560
+ for (const dir of possibleMessageDirs) {
561
+ const fullDir = path2.join(projectPath, dir);
562
+ if (fs2.existsSync(fullDir)) {
563
+ const pattern = path2.join(fullDir, "**/*.json");
564
+ try {
565
+ const files = import_fast_glob2.default.sync(pattern);
566
+ messageFiles.push(...files.map((f) => path2.relative(projectPath, f)));
567
+ } catch (e) {
568
+ }
569
+ }
570
+ }
571
+ return {
572
+ enabled: true,
573
+ type: "react-i18n",
574
+ configFiles,
575
+ messageFiles,
576
+ method: "t() \u6216 useTranslation()",
577
+ example: `{t('common.save')} \u6216 const { t } = useTranslation()`,
578
+ tips: [
579
+ "\u4F7F\u7528 useTranslation() hook \u83B7\u53D6 t \u51FD\u6570",
580
+ '\u547D\u540D\u7A7A\u95F4\u683C\u5F0F\uFF1At("common.save")',
581
+ "\u6240\u6709\u6587\u6848\u5FC5\u987B\u901A\u8FC7 t() \u51FD\u6570\u5305\u88F9",
582
+ "\u786E\u4FDD\u6240\u6709\u8BED\u8A00\u7684\u7FFB\u8BD1\u6587\u4EF6\u540C\u6B65\u66F4\u65B0"
583
+ ]
584
+ };
585
+ }
586
+ /**
587
+ * 检测 react-intl 配置
588
+ */
589
+ static detectReactIntl(projectPath) {
590
+ return {
591
+ enabled: true,
592
+ type: "react-i18n",
593
+ configFiles: [],
594
+ messageFiles: [],
595
+ method: "formatMessage() \u6216 FormattedMessage",
596
+ example: `<FormattedMessage id="common.save" /> \u6216 intl.formatMessage({ id: 'common.save' })`,
597
+ tips: [
598
+ "\u4F7F\u7528 FormattedMessage \u7EC4\u4EF6\u6216 formatMessage \u65B9\u6CD5",
599
+ "\u6D88\u606F ID \u683C\u5F0F\uFF1Acommon.save",
600
+ "\u6240\u6709\u6587\u6848\u5FC5\u987B\u5B9A\u4E49\u5728\u6D88\u606F\u6587\u4EF6\u4E2D",
601
+ "\u786E\u4FDD\u591A\u8BED\u8A00\u6587\u4EF6\u7684\u6D88\u606F ID \u4FDD\u6301\u4E00\u81F4"
602
+ ]
603
+ };
604
+ }
605
+ /**
606
+ * 检测自定义国际化方案
607
+ */
608
+ static detectCustomI18n(projectPath) {
609
+ const messageFiles = [];
610
+ const possibleDirs = ["src/locales", "src/i18n", "src/lang"];
611
+ for (const dir of possibleDirs) {
612
+ const fullDir = path2.join(projectPath, dir);
613
+ if (fs2.existsSync(fullDir)) {
614
+ const files = fs2.readdirSync(fullDir);
615
+ for (const file of files) {
616
+ if (/messages?\.(ts|js)$/i.test(file)) {
617
+ messageFiles.push(path2.join(dir, file));
618
+ const content = fs2.readFileSync(path2.join(fullDir, file), "utf-8");
619
+ if (content.includes("[") && content.includes("],")) {
620
+ return {
621
+ enabled: true,
622
+ type: "custom",
623
+ configFiles: [],
624
+ messageFiles,
625
+ method: "$t()",
626
+ example: `{{ $t('\u4FDD\u5B58') }} \u6216 :label="$t('\u7528\u6237\u540D')"`,
627
+ tips: [
628
+ '\u4F7F\u7528\u76F4\u63A5\u952E\u540D\u683C\u5F0F\uFF1A$t("\u4FDD\u5B58")',
629
+ "\u6240\u6709\u6309\u94AE\u3001\u6807\u7B7E\u3001\u63D0\u793A\u6587\u5B57\u5FC5\u987B\u4F7F\u7528 $t()",
630
+ "\u8868\u5355\u9A8C\u8BC1\u89C4\u5219\u7684 message \u4E5F\u9700\u8981\u56FD\u9645\u5316",
631
+ "\u65B0\u589E\u6587\u6848\u65F6\u9700\u8981\u540C\u65F6\u6DFB\u52A0\u4E2D\u82F1\u6587\u7FFB\u8BD1"
632
+ ]
633
+ };
634
+ }
635
+ }
636
+ }
637
+ }
638
+ }
639
+ if (messageFiles.length > 0) {
640
+ return {
641
+ enabled: true,
642
+ type: "custom",
643
+ configFiles: [],
644
+ messageFiles,
645
+ method: "$t()",
646
+ example: "\u8BF7\u67E5\u770B\u9879\u76EE\u4E2D\u73B0\u6709\u9875\u9762\u7684\u4F7F\u7528\u65B9\u5F0F",
647
+ tips: [
648
+ "\u68C0\u6D4B\u5230\u56FD\u9645\u5316\u6587\u4EF6\uFF0C\u4F46\u683C\u5F0F\u672A\u77E5",
649
+ "\u8BF7\u67E5\u770B\u73B0\u6709\u9875\u9762\u786E\u8BA4\u4F7F\u7528\u65B9\u5F0F",
650
+ "\u786E\u4FDD\u6240\u6709\u65B0\u589E\u6587\u6848\u90FD\u9075\u5FAA\u9879\u76EE\u89C4\u8303"
651
+ ]
652
+ };
653
+ }
654
+ return {
655
+ enabled: false,
656
+ type: "none",
657
+ configFiles: [],
658
+ messageFiles: [],
659
+ method: "",
660
+ example: "",
661
+ tips: [
662
+ "\u26A0\uFE0F \u9879\u76EE\u672A\u914D\u7F6E\u56FD\u9645\u5316",
663
+ "\u5EFA\u8BAE\u6DFB\u52A0\u4E2D\u82F1\u53CC\u8BED\u652F\u6301",
664
+ "\u63A8\u8350\u4F7F\u7528 vue-i18n\uFF08Vue\uFF09\u6216 react-i18next\uFF08React\uFF09"
665
+ ]
666
+ };
667
+ }
668
+ /**
669
+ * 检测 Flutter 项目的国际化配置
670
+ */
671
+ static detectFlutterI18n(projectPath, pubspecPath) {
672
+ const content = fs2.readFileSync(pubspecPath, "utf-8");
673
+ if (content.includes("flutter_localizations")) {
674
+ const messageFiles = [];
675
+ const l10nDir = path2.join(projectPath, "lib", "l10n");
676
+ if (fs2.existsSync(l10nDir)) {
677
+ const files = fs2.readdirSync(l10nDir);
678
+ for (const file of files) {
679
+ if (file.endsWith(".arb")) {
680
+ messageFiles.push(`lib/l10n/${file}`);
681
+ }
682
+ }
683
+ }
684
+ const l10nConfigPath = path2.join(projectPath, "l10n.yaml");
685
+ const configFiles = fs2.existsSync(l10nConfigPath) ? ["l10n.yaml"] : [];
686
+ return {
687
+ enabled: true,
688
+ type: "flutter-intl",
689
+ configFiles,
690
+ messageFiles,
691
+ method: "AppLocalizations",
692
+ example: `AppLocalizations.of(context)!.save \u6216 S.of(context).save`,
693
+ tips: [
694
+ "\u4F7F\u7528 AppLocalizations.of(context)!.key",
695
+ "\u6240\u6709\u6587\u672C\u5FC5\u987B\u5728 .arb \u6587\u4EF6\u4E2D\u5B9A\u4E49",
696
+ "\u786E\u4FDD app_en.arb \u548C app_zh.arb \u7684\u952E\u540D\u5B8C\u5168\u4E00\u81F4",
697
+ "\u8FD0\u884C flutter gen-l10n \u751F\u6210\u4EE3\u7801"
698
+ ]
699
+ };
700
+ }
701
+ if (content.includes("easy_localization")) {
702
+ return {
703
+ enabled: true,
704
+ type: "flutter-intl",
705
+ configFiles: [],
706
+ messageFiles: [],
707
+ method: "tr()",
708
+ example: `'save'.tr() \u6216 Text('save'.tr())`,
709
+ tips: [
710
+ "\u4F7F\u7528 .tr() \u6269\u5C55\u65B9\u6CD5",
711
+ "\u7FFB\u8BD1\u6587\u4EF6\u901A\u5E38\u5728 assets/translations/",
712
+ "\u786E\u4FDD\u6240\u6709\u8BED\u8A00\u6587\u4EF6\u7684\u952E\u540D\u4E00\u81F4"
713
+ ]
714
+ };
715
+ }
716
+ return {
717
+ enabled: false,
718
+ type: "none",
719
+ configFiles: [],
720
+ messageFiles: [],
721
+ method: "",
722
+ example: "",
723
+ tips: [
724
+ "\u26A0\uFE0F Flutter \u9879\u76EE\u672A\u914D\u7F6E\u56FD\u9645\u5316",
725
+ "\u5EFA\u8BAE\u6DFB\u52A0 flutter_localizations",
726
+ "\u5728 pubspec.yaml \u4E2D\u6DFB\u52A0\uFF1A",
727
+ " flutter_localizations:",
728
+ " sdk: flutter",
729
+ " intl: any"
730
+ ]
731
+ };
732
+ }
733
+ };
734
+
735
+ // src/core/types.ts
736
+ var ConsoleLogger = class {
737
+ constructor(enableDebug = false) {
738
+ this.enableDebug = enableDebug;
739
+ }
740
+ log(message) {
741
+ console.error(`[MCP] [INFO] ${message}`);
742
+ }
743
+ error(message) {
744
+ console.error(`[MCP] [ERROR] ${message}`);
745
+ }
746
+ debug(message) {
747
+ if (this.enableDebug) {
748
+ console.error(`[MCP] [DEBUG] ${message}`);
749
+ }
750
+ }
751
+ };
752
+
753
+ // src/tools/analyzeProject.ts
754
+ async function analyzeProject(args) {
755
+ const logger3 = new ConsoleLogger();
756
+ try {
757
+ let projectPath = args.projectPath;
758
+ if (!projectPath) {
759
+ projectPath = process.cwd();
760
+ logger3.log(`\u{1F4CD} \u672A\u6307\u5B9A\u8DEF\u5F84\uFF0C\u4F7F\u7528\u5F53\u524D\u76EE\u5F55: ${projectPath}`);
761
+ }
762
+ if (!fs3.existsSync(projectPath)) {
763
+ return {
764
+ content: [{
765
+ type: "text",
766
+ text: JSON.stringify({
767
+ error: `\u9879\u76EE\u8DEF\u5F84\u4E0D\u5B58\u5728: ${projectPath}`
768
+ }, null, 2)
769
+ }]
770
+ };
771
+ }
772
+ const matcher = new SmartAgentMatcher(logger3);
773
+ const workspaceFolder = {
774
+ uri: { fsPath: projectPath },
775
+ name: path3.basename(projectPath),
776
+ index: 0
777
+ };
778
+ const features = await matcher.analyzeProject(workspaceFolder);
779
+ logger3.log(`\u{1F30D} \u68C0\u6D4B\u56FD\u9645\u5316\u914D\u7F6E...`);
780
+ const i18nConfig = await I18nDetector.detect(projectPath);
781
+ return {
782
+ content: [{
783
+ type: "text",
784
+ text: JSON.stringify({
785
+ success: true,
786
+ projectPath,
787
+ projectName: path3.basename(projectPath),
788
+ autoDetected: !args.projectPath,
789
+ features: {
790
+ projectType: features.projectType,
791
+ frameworks: features.frameworks,
792
+ languages: features.languages,
793
+ tools: features.tools,
794
+ keywords: features.keywords
795
+ },
796
+ i18n: {
797
+ enabled: i18nConfig.enabled,
798
+ type: i18nConfig.type,
799
+ configFiles: i18nConfig.configFiles,
800
+ messageFiles: i18nConfig.messageFiles,
801
+ method: i18nConfig.method,
802
+ example: i18nConfig.example,
803
+ tips: i18nConfig.tips
804
+ },
805
+ summary: `\u68C0\u6D4B\u5230 ${features.projectType} \u9879\u76EE\uFF0C\u4F7F\u7528 ${features.frameworks.join(", ")} \u6846\u67B6\u3002\u56FD\u9645\u5316\uFF1A${i18nConfig.enabled ? `\u5DF2\u914D\u7F6E (${i18nConfig.type})` : "\u672A\u914D\u7F6E"}`
806
+ }, null, 2)
807
+ }]
808
+ };
809
+ } catch (error) {
810
+ logger3.error(`\u5206\u6790\u9879\u76EE\u5931\u8D25: ${error}`);
811
+ return {
812
+ content: [{
813
+ type: "text",
814
+ text: JSON.stringify({
815
+ error: error instanceof Error ? error.message : String(error)
816
+ }, null, 2)
817
+ }]
818
+ };
819
+ }
820
+ }
821
+
822
+ // src/core/githubClient.ts
823
+ var import_axios = __toESM(require("axios"), 1);
824
+ var GitHubClient = class {
825
+ constructor(logger3) {
826
+ this.logger = logger3;
827
+ this.owner = "ForLear";
828
+ this.repo = "copilot-prompts";
829
+ this.branch = "main";
830
+ this.baseUrl = "https://api.github.com";
831
+ this.rawBaseUrl = "https://raw.githubusercontent.com";
832
+ }
833
+ /**
834
+ * 列出目录中的文件
835
+ */
836
+ async listDirectoryFiles(dirPath) {
837
+ var _a;
838
+ const url = `${this.baseUrl}/repos/${this.owner}/${this.repo}/contents/${dirPath}?ref=${this.branch}`;
839
+ try {
840
+ const response = await import_axios.default.get(url, {
841
+ headers: {
842
+ "Accept": "application/vnd.github.v3+json",
843
+ "User-Agent": "Copilot-Prompts-MCP-Server"
844
+ }
845
+ });
846
+ if (Array.isArray(response.data)) {
847
+ return response.data.map((item) => ({
848
+ name: item.name,
849
+ path: item.path,
850
+ type: item.type
851
+ }));
852
+ }
853
+ return [];
854
+ } catch (error) {
855
+ (_a = this.logger) == null ? void 0 : _a.error(`\u83B7\u53D6\u76EE\u5F55\u5931\u8D25: ${error}`);
856
+ return [];
857
+ }
858
+ }
859
+ /**
860
+ * 获取文件内容
861
+ */
862
+ async fetchFileContent(filePath) {
863
+ var _a;
864
+ const url = `${this.rawBaseUrl}/${this.owner}/${this.repo}/${this.branch}/${filePath}`;
865
+ try {
866
+ const response = await import_axios.default.get(url, {
867
+ headers: {
868
+ "User-Agent": "Copilot-Prompts-MCP-Server"
869
+ }
870
+ });
871
+ return response.data;
872
+ } catch (error) {
873
+ (_a = this.logger) == null ? void 0 : _a.error(`\u83B7\u53D6\u6587\u4EF6\u5931\u8D25: ${filePath}`);
874
+ throw error;
875
+ }
876
+ }
877
+ };
878
+
879
+ // src/tools/matchAgents.ts
880
+ async function matchAgents(args) {
881
+ const logger3 = new ConsoleLogger();
882
+ try {
883
+ const matcher = new SmartAgentMatcher(logger3);
884
+ const githubClient = new GitHubClient(logger3);
885
+ logger3.log("\u6B63\u5728\u4ECE GitHub \u83B7\u53D6\u53EF\u7528 Agents...");
886
+ const availableAgents = [];
887
+ try {
888
+ const agentFiles = await githubClient.listDirectoryFiles("agents");
889
+ for (const file of agentFiles) {
890
+ if (file.name.endsWith(".agent.md")) {
891
+ try {
892
+ const content = await githubClient.fetchFileContent(file.path);
893
+ const metadata = matcher.parseAgentMetadata(file.path, content);
894
+ availableAgents.push(metadata);
895
+ } catch (error) {
896
+ logger3.error(`\u89E3\u6790 ${file.name} \u5931\u8D25: ${error}`);
897
+ }
898
+ }
899
+ }
900
+ } catch (error) {
901
+ logger3.error(`\u83B7\u53D6 Agents \u5931\u8D25: ${error}`);
902
+ }
903
+ const matchedAgents = matcher.matchAgents(args.projectFeatures, availableAgents);
904
+ const limit = args.limit || 10;
905
+ const topAgents = matchedAgents.slice(0, limit);
906
+ return {
907
+ content: [{
908
+ type: "text",
909
+ text: JSON.stringify({
910
+ success: true,
911
+ totalAvailable: availableAgents.length,
912
+ matched: topAgents.length,
913
+ agents: topAgents.map((agent) => ({
914
+ id: agent.id,
915
+ title: agent.title,
916
+ description: agent.description,
917
+ score: agent.score,
918
+ tags: agent.tags,
919
+ path: agent.path
920
+ })),
921
+ recommendations: topAgents.slice(0, 5).map((a) => a.title)
922
+ }, null, 2)
923
+ }]
924
+ };
925
+ } catch (error) {
926
+ logger3.error(`\u5339\u914D Agents \u5931\u8D25: ${error}`);
927
+ return {
928
+ content: [{
929
+ type: "text",
930
+ text: JSON.stringify({
931
+ error: error instanceof Error ? error.message : String(error)
932
+ }, null, 2)
933
+ }]
934
+ };
935
+ }
936
+ }
937
+
938
+ // src/tools/listAgents.ts
939
+ async function listAvailableAgents() {
940
+ const logger3 = new ConsoleLogger();
941
+ try {
942
+ const githubClient = new GitHubClient(logger3);
943
+ logger3.log("\u6B63\u5728\u4ECE GitHub \u83B7\u53D6 Agents \u5217\u8868...");
944
+ const agentFiles = await githubClient.listDirectoryFiles("agents");
945
+ const agents = agentFiles.filter((f) => f.name.endsWith(".agent.md"));
946
+ const agentList = await Promise.all(
947
+ agents.map(async (file) => {
948
+ try {
949
+ const content = await githubClient.fetchFileContent(file.path);
950
+ const lines = content.split("\n");
951
+ let title = file.name.replace(".agent.md", "");
952
+ let description = "";
953
+ if (lines[0] === "---") {
954
+ const endIndex = lines.slice(1).findIndex((l) => l === "---");
955
+ if (endIndex > 0) {
956
+ const frontmatter = lines.slice(1, endIndex + 1).join("\n");
957
+ const descMatch = frontmatter.match(/description:\s*['"](.+)['"]/);
958
+ if (descMatch) {
959
+ description = descMatch[1];
960
+ }
961
+ }
962
+ }
963
+ const titleLine = lines.find((l) => l.startsWith("# "));
964
+ if (titleLine) {
965
+ title = titleLine.replace("# ", "").trim();
966
+ }
967
+ return {
968
+ id: file.name.replace(".agent.md", ""),
969
+ name: file.name,
970
+ title,
971
+ description: description || "\u6682\u65E0\u63CF\u8FF0",
972
+ path: file.path
973
+ };
974
+ } catch (error) {
975
+ logger3.error(`\u89E3\u6790 ${file.name} \u5931\u8D25: ${error}`);
976
+ return null;
977
+ }
978
+ })
979
+ );
980
+ const validAgents = agentList.filter((a) => a !== null);
981
+ return {
982
+ content: [{
983
+ type: "text",
984
+ text: JSON.stringify({
985
+ success: true,
986
+ total: validAgents.length,
987
+ agents: validAgents,
988
+ categories: {
989
+ general: validAgents.filter((a) => a.path.includes("common/")).length,
990
+ frameworks: validAgents.filter((a) => a.path.includes("vue/") || a.path.includes("react/")).length,
991
+ agents: validAgents.filter((a) => a.path.includes("agents/")).length
992
+ }
993
+ }, null, 2)
994
+ }]
995
+ };
996
+ } catch (error) {
997
+ logger3.error(`\u83B7\u53D6 Agents \u5217\u8868\u5931\u8D25: ${error}`);
998
+ return {
999
+ content: [{
1000
+ type: "text",
1001
+ text: JSON.stringify({
1002
+ error: error instanceof Error ? error.message : String(error)
1003
+ }, null, 2)
1004
+ }]
1005
+ };
1006
+ }
1007
+ }
1008
+
1009
+ // src/tools/generateConfig.ts
1010
+ var fs4 = __toESM(require("fs"), 1);
1011
+ var path4 = __toESM(require("path"), 1);
1012
+ var import_url = require("url");
1013
+
1014
+ // src/core/codeValidator.ts
1015
+ var CodeValidator = class {
1016
+ constructor(logger3) {
1017
+ this.logger = logger3 || new ConsoleLogger();
1018
+ }
1019
+ /**
1020
+ * 验证生成的配置文件内容
1021
+ */
1022
+ validateConfigContent(content) {
1023
+ const errors = [];
1024
+ const warnings = [];
1025
+ this.checkDuplicateTags(content, errors);
1026
+ this.checkBracketMatching(content, errors);
1027
+ this.checkMarkdownSyntax(content, errors);
1028
+ this.checkRequiredSections(content, warnings);
1029
+ this.checkCustomContentMarkers(content, warnings);
1030
+ return {
1031
+ isValid: errors.length === 0,
1032
+ errors,
1033
+ warnings
1034
+ };
1035
+ }
1036
+ /**
1037
+ * 检查重复的HTML标签
1038
+ */
1039
+ checkDuplicateTags(content, errors) {
1040
+ const lines = content.split("\n");
1041
+ const tagPattern = /<\/([\w-]+)>/g;
1042
+ for (let i = 0; i < lines.length; i++) {
1043
+ const line = lines[i];
1044
+ const matches = Array.from(line.matchAll(tagPattern));
1045
+ if (matches.length > 0) {
1046
+ const tags = matches.map((m) => m[1]);
1047
+ const tagCounts = /* @__PURE__ */ new Map();
1048
+ tags.forEach((tag) => {
1049
+ tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
1050
+ });
1051
+ tagCounts.forEach((count, tag) => {
1052
+ if (count > 1) {
1053
+ errors.push({
1054
+ type: "syntax",
1055
+ message: `\u91CD\u590D\u7684\u95ED\u5408\u6807\u7B7E </${tag}> \u5728\u540C\u4E00\u884C\u51FA\u73B0 ${count} \u6B21`,
1056
+ line: i + 1,
1057
+ suggestion: `\u68C0\u67E5\u662F\u5426\u6709\u591A\u4F59\u7684\u95ED\u5408\u6807\u7B7E\uFF0C\u5E94\u8BE5\u53EA\u4FDD\u7559\u4E00\u4E2A </${tag}>`
1058
+ });
1059
+ }
1060
+ });
1061
+ }
1062
+ }
1063
+ }
1064
+ /**
1065
+ * 检查括号匹配
1066
+ */
1067
+ checkBracketMatching(content, errors) {
1068
+ const brackets = {
1069
+ "(": ")",
1070
+ "[": "]",
1071
+ "{": "}",
1072
+ "<": ">"
1073
+ };
1074
+ const stack = [];
1075
+ const lines = content.split("\n");
1076
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
1077
+ const line = lines[lineNum];
1078
+ if (line.trim().startsWith("```")) {
1079
+ continue;
1080
+ }
1081
+ if (line.trim().startsWith(">")) {
1082
+ continue;
1083
+ }
1084
+ for (let col = 0; col < line.length; col++) {
1085
+ const char = line[col];
1086
+ if (char === ">" && (col === 0 || line[col - 1] === " ") && (col === line.length - 1 || line[col + 1] === " ")) {
1087
+ continue;
1088
+ }
1089
+ if (char in brackets) {
1090
+ stack.push({ char, line: lineNum + 1, col: col + 1 });
1091
+ } else if (Object.values(brackets).includes(char)) {
1092
+ if (stack.length === 0) {
1093
+ errors.push({
1094
+ type: "syntax",
1095
+ message: `\u672A\u914D\u5BF9\u7684\u95ED\u5408\u62EC\u53F7 '${char}'`,
1096
+ line: lineNum + 1,
1097
+ suggestion: `\u68C0\u67E5\u662F\u5426\u7F3A\u5C11\u5BF9\u5E94\u7684\u5F00\u653E\u62EC\u53F7`
1098
+ });
1099
+ } else {
1100
+ const last = stack.pop();
1101
+ const expectedClose = brackets[last.char];
1102
+ if (char !== expectedClose) {
1103
+ errors.push({
1104
+ type: "syntax",
1105
+ message: `\u62EC\u53F7\u4E0D\u5339\u914D: \u671F\u671B '${expectedClose}' \u4F46\u5F97\u5230 '${char}'`,
1106
+ line: lineNum + 1,
1107
+ suggestion: `\u68C0\u67E5\u7B2C ${last.line} \u884C\u7684 '${last.char}' \u5BF9\u5E94\u7684\u95ED\u5408\u62EC\u53F7`
1108
+ });
1109
+ }
1110
+ }
1111
+ }
1112
+ }
1113
+ }
1114
+ if (stack.length > 0) {
1115
+ stack.forEach((bracket) => {
1116
+ errors.push({
1117
+ type: "syntax",
1118
+ message: `\u672A\u95ED\u5408\u7684\u62EC\u53F7 '${bracket.char}'`,
1119
+ line: bracket.line,
1120
+ suggestion: `\u6DFB\u52A0\u5BF9\u5E94\u7684\u95ED\u5408\u62EC\u53F7 '${brackets[bracket.char]}'`
1121
+ });
1122
+ });
1123
+ }
1124
+ }
1125
+ /**
1126
+ * 检查 Markdown 语法
1127
+ */
1128
+ checkMarkdownSyntax(content, errors) {
1129
+ const lines = content.split("\n");
1130
+ let inCodeBlock = false;
1131
+ let codeBlockStart = 0;
1132
+ for (let i = 0; i < lines.length; i++) {
1133
+ const line = lines[i];
1134
+ if (line.trim().startsWith("```")) {
1135
+ if (inCodeBlock) {
1136
+ inCodeBlock = false;
1137
+ } else {
1138
+ inCodeBlock = true;
1139
+ codeBlockStart = i + 1;
1140
+ }
1141
+ }
1142
+ }
1143
+ if (inCodeBlock) {
1144
+ errors.push({
1145
+ type: "syntax",
1146
+ message: "\u672A\u95ED\u5408\u7684\u4EE3\u7801\u5757",
1147
+ line: codeBlockStart,
1148
+ suggestion: "\u5728\u4EE3\u7801\u5757\u672B\u5C3E\u6DFB\u52A0 ``` \u95ED\u5408\u6807\u8BB0"
1149
+ });
1150
+ }
1151
+ }
1152
+ /**
1153
+ * 检查必要章节完整性
1154
+ */
1155
+ checkRequiredSections(content, warnings) {
1156
+ const requiredSections = [
1157
+ { pattern: /## ⚠️ 强制工作流/i, name: "\u5F3A\u5236\u5DE5\u4F5C\u6D41\u7AE0\u8282" },
1158
+ { pattern: /## 📚 配置的 Agents/i, name: "Agents \u914D\u7F6E\u7AE0\u8282" }
1159
+ ];
1160
+ requiredSections.forEach((section) => {
1161
+ if (!section.pattern.test(content)) {
1162
+ warnings.push({
1163
+ type: "completeness",
1164
+ message: `\u7F3A\u5C11\u5FC5\u8981\u7AE0\u8282: ${section.name}`,
1165
+ suggestion: "\u786E\u4FDD\u751F\u6210\u7684\u914D\u7F6E\u6587\u4EF6\u5305\u542B\u6240\u6709\u5FC5\u8981\u7684\u7AE0\u8282"
1166
+ });
1167
+ }
1168
+ });
1169
+ }
1170
+ /**
1171
+ * 检查自定义内容标记
1172
+ */
1173
+ checkCustomContentMarkers(content, warnings) {
1174
+ const hasCustomStart = content.includes("<!-- CUSTOM_START -->");
1175
+ const hasCustomEnd = content.includes("<!-- CUSTOM_END -->");
1176
+ if (hasCustomStart !== hasCustomEnd) {
1177
+ warnings.push({
1178
+ type: "completeness",
1179
+ message: "CUSTOM \u6807\u8BB0\u4E0D\u5B8C\u6574",
1180
+ suggestion: "\u786E\u4FDD CUSTOM_START \u548C CUSTOM_END \u6210\u5BF9\u51FA\u73B0"
1181
+ });
1182
+ }
1183
+ }
1184
+ /**
1185
+ * 验证 Agent 内容
1186
+ */
1187
+ validateAgentContent(content, agentId) {
1188
+ const errors = [];
1189
+ const warnings = [];
1190
+ if (!content.includes("\u26A0\uFE0F \u5F3A\u5236\u5DE5\u4F5C\u6D41") && !content.includes("## \u5F3A\u5236\u5DE5\u4F5C\u6D41")) {
1191
+ warnings.push({
1192
+ type: "best-practice",
1193
+ message: `Agent ${agentId} \u7F3A\u5C11\u5F3A\u5236\u5DE5\u4F5C\u6D41\u8BF4\u660E`,
1194
+ suggestion: "\u5EFA\u8BAE\u5728 Agent \u4E2D\u5305\u542B MCP \u5DE5\u5177\u8C03\u7528\u7684\u5F3A\u5236\u8BF4\u660E"
1195
+ });
1196
+ }
1197
+ const syntaxValidation = this.validateConfigContent(content);
1198
+ errors.push(...syntaxValidation.errors);
1199
+ warnings.push(...syntaxValidation.warnings);
1200
+ return {
1201
+ isValid: errors.length === 0,
1202
+ errors,
1203
+ warnings
1204
+ };
1205
+ }
1206
+ /**
1207
+ * 生成验证报告
1208
+ */
1209
+ generateValidationReport(result) {
1210
+ let report = "";
1211
+ if (result.isValid && result.warnings.length === 0) {
1212
+ report = "\u2705 \u9A8C\u8BC1\u901A\u8FC7\uFF0C\u672A\u53D1\u73B0\u95EE\u9898\n";
1213
+ return report;
1214
+ }
1215
+ if (!result.isValid) {
1216
+ report += "\u274C \u9A8C\u8BC1\u5931\u8D25\uFF0C\u53D1\u73B0\u4EE5\u4E0B\u9519\u8BEF\uFF1A\n\n";
1217
+ result.errors.forEach((error, index) => {
1218
+ report += `${index + 1}. [${error.type}] ${error.message}
1219
+ `;
1220
+ if (error.line) {
1221
+ report += ` \u4F4D\u7F6E: \u7B2C ${error.line} \u884C
1222
+ `;
1223
+ }
1224
+ if (error.suggestion) {
1225
+ report += ` \u5EFA\u8BAE: ${error.suggestion}
1226
+ `;
1227
+ }
1228
+ report += "\n";
1229
+ });
1230
+ } else {
1231
+ report += "\u2705 \u9A8C\u8BC1\u901A\u8FC7\n\n";
1232
+ }
1233
+ if (result.warnings.length > 0) {
1234
+ report += "\u26A0\uFE0F \u53D1\u73B0\u4EE5\u4E0B\u8B66\u544A\uFF1A\n\n";
1235
+ result.warnings.forEach((warning, index) => {
1236
+ report += `${index + 1}. [${warning.type}] ${warning.message}
1237
+ `;
1238
+ if (warning.suggestion) {
1239
+ report += ` \u5EFA\u8BAE: ${warning.suggestion}
1240
+ `;
1241
+ }
1242
+ report += "\n";
1243
+ });
1244
+ }
1245
+ return report;
1246
+ }
1247
+ /**
1248
+ * 尝试自动修复简单的语法错误
1249
+ */
1250
+ attemptAutoFix(content) {
1251
+ let fixedContent = content;
1252
+ const changes = [];
1253
+ const tagPattern = /(<\/([\w-]+)>)\1+/g;
1254
+ const tagMatches = content.match(tagPattern);
1255
+ if (tagMatches) {
1256
+ fixedContent = fixedContent.replace(tagPattern, "$1");
1257
+ changes.push(`\u4FEE\u590D\u4E86\u91CD\u590D\u7684\u95ED\u5408\u6807\u7B7E: ${tagMatches.join(", ")}`);
1258
+ }
1259
+ const codeBlockCount = (fixedContent.match(/```/g) || []).length;
1260
+ if (codeBlockCount % 2 !== 0) {
1261
+ fixedContent += "\n```\n";
1262
+ changes.push("\u6DFB\u52A0\u4E86\u7F3A\u5931\u7684\u4EE3\u7801\u5757\u95ED\u5408\u6807\u8BB0");
1263
+ }
1264
+ return {
1265
+ fixed: changes.length > 0,
1266
+ content: fixedContent,
1267
+ changes
1268
+ };
1269
+ }
1270
+ };
1271
+
1272
+ // src/tools/generateConfig.ts
1273
+ var __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
1274
+ var __dirname2 = path4.dirname(__filename2);
1275
+ async function generateConfig(args) {
1276
+ const logger3 = new ConsoleLogger();
1277
+ try {
1278
+ if (!fs4.existsSync(args.projectPath)) {
1279
+ return {
1280
+ content: [{
1281
+ type: "text",
1282
+ text: JSON.stringify({
1283
+ error: `\u9879\u76EE\u8DEF\u5F84\u4E0D\u5B58\u5728: ${args.projectPath}`
1284
+ }, null, 2)
1285
+ }]
1286
+ };
1287
+ }
1288
+ const matcher = new SmartAgentMatcher(logger3);
1289
+ const githubClient = new GitHubClient(logger3);
1290
+ let selectedAgents = [];
1291
+ if (args.autoMatch !== false) {
1292
+ logger3.log("\u6B63\u5728\u5206\u6790\u9879\u76EE\u7279\u5F81...");
1293
+ const workspaceFolder = {
1294
+ uri: { fsPath: args.projectPath },
1295
+ name: path4.basename(args.projectPath),
1296
+ index: 0
1297
+ };
1298
+ const features = await matcher.analyzeProject(workspaceFolder);
1299
+ logger3.log("\u6B63\u5728\u5339\u914D Agents...");
1300
+ const availableAgents = [];
1301
+ try {
1302
+ logger3.log("\u{1F4E1} \u4ECE GitHub \u83B7\u53D6 Agents...");
1303
+ const agentFiles = await githubClient.listDirectoryFiles("agents");
1304
+ for (const file of agentFiles) {
1305
+ if (file.name.endsWith(".agent.md")) {
1306
+ try {
1307
+ const content2 = await githubClient.fetchFileContent(file.path);
1308
+ const metadata = matcher.parseAgentMetadata(file.path, content2);
1309
+ availableAgents.push(metadata);
1310
+ logger3.log(`\u2705 \u52A0\u8F7D Agent: ${metadata.title}`);
1311
+ } catch (error) {
1312
+ logger3.error(`\u89E3\u6790 ${file.name} \u5931\u8D25`);
1313
+ }
1314
+ }
1315
+ }
1316
+ logger3.log(`\u2705 \u4ECE GitHub \u6210\u529F\u52A0\u8F7D ${availableAgents.length} \u4E2A Agents`);
1317
+ } catch (githubError) {
1318
+ logger3.log("\u26A0\uFE0F GitHub \u83B7\u53D6\u5931\u8D25\uFF0C\u5C1D\u8BD5\u4ECE\u672C\u5730\u52A0\u8F7D...");
1319
+ const agentsDir = path4.join(__dirname2, "../../../agents");
1320
+ if (fs4.existsSync(agentsDir)) {
1321
+ const agentFiles = fs4.readdirSync(agentsDir);
1322
+ logger3.log(`\u627E\u5230 ${agentFiles.length} \u4E2A\u672C\u5730\u6587\u4EF6`);
1323
+ for (const file of agentFiles) {
1324
+ if (file.endsWith(".agent.md")) {
1325
+ try {
1326
+ const filePath = path4.join(agentsDir, file);
1327
+ const content2 = fs4.readFileSync(filePath, "utf-8");
1328
+ const metadata = matcher.parseAgentMetadata(`agents/${file}`, content2);
1329
+ availableAgents.push(metadata);
1330
+ logger3.log(`\u2705 \u52A0\u8F7D Agent: ${metadata.title}`);
1331
+ } catch (error) {
1332
+ logger3.error(`\u89E3\u6790 ${file} \u5931\u8D25`);
1333
+ }
1334
+ }
1335
+ }
1336
+ logger3.log(`\u2705 \u4ECE\u672C\u5730\u6210\u529F\u52A0\u8F7D ${availableAgents.length} \u4E2A Agents`);
1337
+ } else {
1338
+ throw new Error("\u65E0\u6CD5\u4ECE GitHub \u6216\u672C\u5730\u83B7\u53D6 Agents");
1339
+ }
1340
+ }
1341
+ logger3.log(`\u6210\u529F\u52A0\u8F7D ${availableAgents.length} \u4E2A Agents`);
1342
+ selectedAgents = matcher.matchAgents(features, availableAgents);
1343
+ logger3.log(`\u5339\u914D\u5230 ${selectedAgents.length} \u4E2A Agents`);
1344
+ selectedAgents = selectedAgents.slice(0, 5);
1345
+ }
1346
+ if (args.agentIds && args.agentIds.length > 0) {
1347
+ logger3.log(`\u4F7F\u7528\u6307\u5B9A\u7684 Agents: ${args.agentIds.join(", ")}`);
1348
+ selectedAgents = [];
1349
+ for (const id of args.agentIds) {
1350
+ try {
1351
+ let content2;
1352
+ const agentPath = `agents/${id}.agent.md`;
1353
+ try {
1354
+ logger3.log(`\u4ECE GitHub \u83B7\u53D6 Agent: ${id}`);
1355
+ content2 = await githubClient.fetchFileContent(agentPath);
1356
+ logger3.log(`\u2705 \u4ECE GitHub \u52A0\u8F7D\u6210\u529F: ${id}`);
1357
+ } catch (githubError) {
1358
+ logger3.log(`GitHub \u83B7\u53D6\u5931\u8D25\uFF0C\u5C1D\u8BD5\u672C\u5730: ${id}`);
1359
+ const agentsDir = path4.join(__dirname2, "../../../agents");
1360
+ const localPath = path4.join(agentsDir, `${id}.agent.md`);
1361
+ if (fs4.existsSync(localPath)) {
1362
+ content2 = fs4.readFileSync(localPath, "utf-8");
1363
+ logger3.log(`\u2705 \u4ECE\u672C\u5730\u52A0\u8F7D\u6210\u529F: ${id}`);
1364
+ } else {
1365
+ throw new Error(`Agent ${id} \u4E0D\u5B58\u5728\uFF08GitHub \u548C\u672C\u5730\u90FD\u672A\u627E\u5230\uFF09`);
1366
+ }
1367
+ }
1368
+ const metadata = matcher.parseAgentMetadata(`agents/${id}.agent.md`, content2);
1369
+ selectedAgents.push(metadata);
1370
+ } catch (error) {
1371
+ logger3.error(`\u83B7\u53D6 Agent ${id} \u5931\u8D25: ${error}`);
1372
+ }
1373
+ }
1374
+ }
1375
+ if (selectedAgents.length === 0) {
1376
+ return {
1377
+ content: [{
1378
+ type: "text",
1379
+ text: JSON.stringify({
1380
+ error: "\u672A\u627E\u5230\u5408\u9002\u7684 Agents"
1381
+ }, null, 2)
1382
+ }]
1383
+ };
1384
+ }
1385
+ logger3.log("\u6B63\u5728\u751F\u6210\u914D\u7F6E\u6587\u4EF6...");
1386
+ const githubDir = path4.join(args.projectPath, ".github");
1387
+ const configPath = path4.join(githubDir, "copilot-instructions.md");
1388
+ let existingCustomContent = "";
1389
+ let existingConfig = "";
1390
+ if (fs4.existsSync(configPath)) {
1391
+ existingConfig = fs4.readFileSync(configPath, "utf-8");
1392
+ const customMatch = existingConfig.match(/<!-- CUSTOM_START -->([\s\S]*?)<!-- CUSTOM_END -->/g);
1393
+ if (customMatch) {
1394
+ existingCustomContent = customMatch.join("\n\n");
1395
+ }
1396
+ }
1397
+ if (!fs4.existsSync(githubDir)) {
1398
+ fs4.mkdirSync(githubDir, { recursive: true });
1399
+ }
1400
+ const updateMode = args.updateMode || "merge";
1401
+ let content = "";
1402
+ if (updateMode === "merge") {
1403
+ content += `<!-- \u26A0\uFE0F \u6B64\u6587\u4EF6\u7531 Copilot Prompts MCP Server \u751F\u6210 -->
1404
+ `;
1405
+ content += `<!-- \u2139\uFE0F \u4F60\u53EF\u4EE5\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5185\u5BB9\uFF0C\u4F7F\u7528 CUSTOM_START/CUSTOM_END \u6807\u8BB0\u4FDD\u62A4 -->
1406
+ `;
1407
+ content += `<!-- \u793A\u4F8B: -->
1408
+ `;
1409
+ content += `<!-- CUSTOM_START -->
1410
+ `;
1411
+ content += `<!-- \u4F60\u7684\u81EA\u5B9A\u4E49\u89C4\u8303 -->
1412
+ `;
1413
+ content += `<!-- CUSTOM_END -->
1414
+
1415
+ `;
1416
+ } else {
1417
+ content += `<!-- \u26A0\uFE0F \u6B64\u6587\u4EF6\u7531 Copilot Prompts MCP Server \u81EA\u52A8\u751F\u6210 -->
1418
+ `;
1419
+ content += `<!-- \u26A0\uFE0F \u4F7F\u7528 --update-mode merge \u53EF\u4FDD\u62A4\u81EA\u5B9A\u4E49\u5185\u5BB9 -->
1420
+
1421
+ `;
1422
+ }
1423
+ const projectName = path4.basename(args.projectPath);
1424
+ const projectPath = args.projectPath;
1425
+ content += `<!-- \u{1F3AF} \u4F5C\u7528\u57DF\uFF1A\u6B64\u914D\u7F6E\u4EC5\u9002\u7528\u4E8E\u5F53\u524D\u9879\u76EE -->
1426
+ `;
1427
+ content += `<!-- \u9879\u76EE\u540D\u79F0: ${projectName} -->
1428
+ `;
1429
+ content += `<!-- \u9879\u76EE\u8DEF\u5F84: ${projectPath} -->
1430
+
1431
+ `;
1432
+ content += `# \u9879\u76EE\u5F00\u53D1\u89C4\u8303 - Copilot \u6307\u4EE4
1433
+
1434
+ `;
1435
+ content += `## \u26A0\uFE0F \u5F3A\u5236\u6267\u884C\u68C0\u67E5\u70B9
1436
+
1437
+ `;
1438
+ content += `> **\u6B64\u68C0\u67E5\u70B9\u7684\u4F18\u5148\u7EA7\u9AD8\u4E8E\u672C\u6587\u4EF6\u7684\u6240\u6709\u5176\u4ED6\u5185\u5BB9**
1439
+
1440
+ `;
1441
+ content += `\u5728\u6267\u884C**\u4EFB\u4F55**\u4EE5\u4E0B\u64CD\u4F5C\u524D\uFF0C\u5FC5\u987B\u5148\u5B8C\u6210\u89C4\u8303\u52A0\u8F7D\u9A8C\u8BC1\uFF1A
1442
+
1443
+ `;
1444
+ content += `### \u53D7\u9650\u64CD\u4F5C\u6E05\u5355
1445
+
1446
+ `;
1447
+ content += `- \u274C \u521B\u5EFA\u4EFB\u4F55\u4EE3\u7801\u6587\u4EF6\uFF08.vue\u3001.ts\u3001.tsx\u3001.js \u7B49\uFF09
1448
+ `;
1449
+ content += `- \u274C \u4FEE\u6539\u4EFB\u4F55\u4EE3\u7801\u6587\u4EF6
1450
+ `;
1451
+ content += `- \u274C \u4F7F\u7528 \`replace_string_in_file\` \u6216 \`multi_replace_string_in_file\`
1452
+ `;
1453
+ content += `- \u274C \u751F\u6210\u4EFB\u4F55\u4EE3\u7801\u7247\u6BB5
1454
+
1455
+ `;
1456
+ content += `### \u5F3A\u5236\u9A8C\u8BC1\u6D41\u7A0B
1457
+
1458
+ `;
1459
+ content += `1. **\u68C0\u67E5\u9879\u76EE\u4F5C\u7528\u57DF** - \u786E\u8BA4\u5F53\u524D\u64CD\u4F5C\u7684\u6587\u4EF6\u8DEF\u5F84\u5305\u542B \`/${projectName}/\`
1460
+ `;
1461
+ content += `2. **\u52A0\u8F7D\u76F8\u5173\u89C4\u8303** - \u6839\u636E\u6587\u4EF6\u7C7B\u578B\u8C03\u7528\u5BF9\u5E94\u7684 MCP \u5DE5\u5177\uFF1A
1462
+ `;
1463
+ content += ` - Vue \u6587\u4EF6 \u2192 \`get_smart_standards\` \u6216 \`use_preset\`
1464
+ `;
1465
+ content += ` - TypeScript \u6587\u4EF6 \u2192 \`get_smart_standards\` \u6216 \`use_preset\`
1466
+ `;
1467
+ content += ` - \u5176\u4ED6\u6587\u4EF6 \u2192 \u6839\u636E\u5B9E\u9645\u60C5\u51B5\u9009\u62E9
1468
+ `;
1469
+ content += `3. **\u9A8C\u8BC1\u52A0\u8F7D\u6210\u529F** - \u786E\u8BA4\u5DE5\u5177\u8FD4\u56DE\u4E86\u89C4\u8303\u5185\u5BB9
1470
+ `;
1471
+ content += `4. **\u58F0\u660E\u5DF2\u52A0\u8F7D** - \u5728\u54CD\u5E94\u4E2D\u660E\u786E\u8BF4\u660E\uFF1A\`\u2705 \u5DF2\u52A0\u8F7D\u89C4\u8303: [\u5DE5\u5177\u540D\u79F0]\`
1472
+
1473
+ `;
1474
+ content += `### \u8FDD\u89C4\u5904\u7406
1475
+
1476
+ `;
1477
+ content += `- \u5982\u679C\u672A\u52A0\u8F7D\u89C4\u8303\u5C31\u751F\u6210\u4EE3\u7801 \u2192 **\u6B64\u64CD\u4F5C\u65E0\u6548\uFF0C\u5FC5\u987B\u91CD\u65B0\u6267\u884C**
1478
+ `;
1479
+ content += `- \u5982\u679C\u51FA\u73B0\u8BED\u6CD5\u9519\u8BEF \u2192 **\u6DF1\u523B\u53CD\u601D\uFF0C\u68C0\u67E5\u662F\u5426\u9075\u5FAA\u4E86\u89C4\u8303**
1480
+ `;
1481
+ content += `- \u5982\u679C\u51FA\u73B0\u4F4E\u7EA7\u9519\u8BEF \u2192 **\u505C\u6B62\u64CD\u4F5C\uFF0C\u91CD\u65B0\u52A0\u8F7D\u89C4\u8303\u540E\u518D\u7EE7\u7EED**
1482
+
1483
+ `;
1484
+ content += `---
1485
+
1486
+ `;
1487
+ content += `## \u{1F3AF} \u4F5C\u7528\u57DF\u9650\u5236
1488
+
1489
+ `;
1490
+ content += `**\u26A0\uFE0F \u6B64\u914D\u7F6E\u4EC5\u5728\u4EE5\u4E0B\u60C5\u51B5\u751F\u6548\uFF1A**
1491
+
1492
+ `;
1493
+ content += `1. \u5F53\u524D\u7F16\u8F91\u7684\u6587\u4EF6\u8DEF\u5F84\u5305\u542B: \`/${projectName}/\`
1494
+ `;
1495
+ content += `2. \u6216\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u4E3A: \`${projectPath}\`
1496
+
1497
+ `;
1498
+ content += `**\u5982\u679C\u4F60\u5728\u5176\u4ED6\u9879\u76EE\u5DE5\u4F5C\uFF08\u5982 ${projectName} \u4E4B\u5916\u7684\u9879\u76EE\uFF09\uFF0C\u8BF7\u5B8C\u5168\u5FFD\u7565\u6B64\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u6240\u6709\u89C4\u8303\u548C\u6307\u4EE4\u3002**
1499
+
1500
+ `;
1501
+ content += `---
1502
+
1503
+ `;
1504
+ content += `> \u{1F4CC} **\u81EA\u52A8\u914D\u7F6E\u4FE1\u606F**
1505
+ `;
1506
+ content += `> - \u751F\u6210\u65F6\u95F4: ${(/* @__PURE__ */ new Date()).toLocaleString("zh-CN")}
1507
+ `;
1508
+ content += `> - \u5339\u914D\u7684 Agents: ${selectedAgents.length} \u4E2A
1509
+
1510
+ `;
1511
+ content += `---
1512
+
1513
+ `;
1514
+ if (args.configId) {
1515
+ try {
1516
+ const configFilePath = path4.join(__dirname2, "../../../configs", `element-plus-${args.configId}.json`);
1517
+ if (fs4.existsSync(configFilePath)) {
1518
+ const configData = JSON.parse(fs4.readFileSync(configFilePath, "utf-8"));
1519
+ content += `## \u{1F4E6} \u914D\u7F6E\u65B9\u6848
1520
+
1521
+ `;
1522
+ content += `**\u65B9\u6848ID**: ${configData.configId}
1523
+ `;
1524
+ content += `**\u540D\u79F0**: ${configData.name}
1525
+ `;
1526
+ content += `**\u63CF\u8FF0**: ${configData.description}
1527
+ `;
1528
+ content += `**\u7EF4\u62A4\u8005**: ${configData.maintainer}
1529
+
1530
+ `;
1531
+ if (configData.rules && configData.rules.table) {
1532
+ content += `### \u8868\u683C\u7EC4\u4EF6\u89C4\u8303
1533
+
1534
+ `;
1535
+ const tableRules = configData.rules.table;
1536
+ if (tableRules.border) content += `- \u2705 **\u5FC5\u987B\u6DFB\u52A0 border**
1537
+ `;
1538
+ if (tableRules["highlight-current-row"]) content += `- \u2705 **\u5FC5\u987B\u9AD8\u4EAE\u5F53\u524D\u884C**
1539
+ `;
1540
+ if (tableRules["v-loading"]) content += `- \u2705 **\u52A0\u8F7D\u72B6\u6001\u53D8\u91CF**: \`${tableRules["v-loading"].variable}\`
1541
+ `;
1542
+ content += `
1543
+ `;
1544
+ }
1545
+ content += `> \u8BE6\u7EC6\u89C4\u5219\u8BF7\u53C2\u8003: \`configs/element-plus-${args.configId}.json\`
1546
+
1547
+ `;
1548
+ content += `---
1549
+
1550
+ `;
1551
+ logger3.log(`\u2705 \u5DF2\u52A0\u8F7D\u914D\u7F6E\u65B9\u6848: ${configData.name}`);
1552
+ }
1553
+ } catch (error) {
1554
+ logger3.error(`\u52A0\u8F7D\u914D\u7F6E\u65B9\u6848\u5931\u8D25: ${error}`);
1555
+ }
1556
+ }
1557
+ content += `## \u26A0\uFE0F \u5F3A\u5236\u5DE5\u4F5C\u6D41
1558
+
1559
+ `;
1560
+ content += `**\u5728\u8FDB\u884C\u4EFB\u4F55\u4EE3\u7801\u751F\u6210\u6216\u4FEE\u6539\u4E4B\u524D\uFF0C\u5FC5\u987B\u5148\u8C03\u7528 MCP \u5DE5\u5177\u52A0\u8F7D\u76F8\u5173\u89C4\u8303\uFF01**
1561
+
1562
+ `;
1563
+ content += `\u6839\u636E\u6587\u4EF6\u7C7B\u578B\u548C\u573A\u666F\uFF0C\u8C03\u7528\u76F8\u5E94\u7684 MCP \u5DE5\u5177\uFF1A
1564
+
1565
+ `;
1566
+ content += `1. **Vue \u6587\u4EF6** \u2192 \`get_relevant_standards({ fileType: "vue" })\`
1567
+ `;
1568
+ content += `2. **TypeScript \u6587\u4EF6** \u2192 \`get_relevant_standards({ fileType: "ts" })\`
1569
+ `;
1570
+ content += `3. **React \u7EC4\u4EF6** \u2192 \`get_relevant_standards({ fileType: "tsx" })\`
1571
+ `;
1572
+ content += `4. **\u4F7F\u7528\u7279\u5B9A\u5E93\u65F6**\uFF1A
1573
+ `;
1574
+ content += ` - Element Plus: \`get_relevant_standards({ imports: ["element-plus"] })\`
1575
+ `;
1576
+ content += ` - Pinia: \`get_relevant_standards({ imports: ["pinia"] })\`
1577
+ `;
1578
+ content += ` - Vue Router: \`get_relevant_standards({ imports: ["vue-router"] })\`
1579
+ `;
1580
+ content += ` - LogicFlow: \`get_relevant_standards({ imports: ["@logicflow/core"] })\`
1581
+ `;
1582
+ content += `5. **\u7279\u5B9A\u573A\u666F**\uFF1A
1583
+ `;
1584
+ content += ` - API \u8C03\u7528: \`get_relevant_standards({ scenario: "API \u8C03\u7528" })\`
1585
+ `;
1586
+ content += ` - \u56FD\u9645\u5316: \`get_relevant_standards({ scenario: "\u56FD\u9645\u5316" })\`
1587
+
1588
+ `;
1589
+ content += `### \u6807\u51C6\u6D41\u7A0B
1590
+
1591
+ `;
1592
+ content += `1. \u2705 **\u5F3A\u5236**: \u52A0\u8F7D\u89C4\u8303 \u2192 2. \u7406\u89E3\u9700\u6C42 \u2192 3. \u7F16\u5199\u4EE3\u7801 \u2192 4. \u9A8C\u8BC1\u89C4\u8303
1593
+
1594
+ `;
1595
+ content += `---
1596
+
1597
+ `;
1598
+ content += `## \u{1F4DA} \u914D\u7F6E\u7684 Agents
1599
+
1600
+ `;
1601
+ content += `\u672C\u9879\u76EE\u4F7F\u7528\u4EE5\u4E0B Agents\uFF08\u89C4\u8303\u5185\u5BB9\u7531 Copilot \u901A\u8FC7 MCP \u5DE5\u5177\u5B9E\u65F6\u52A0\u8F7D\uFF09\uFF1A
1602
+
1603
+ `;
1604
+ for (const agent of selectedAgents) {
1605
+ content += `### ${agent.title}
1606
+
1607
+ `;
1608
+ content += `- **Agent ID**: \`${agent.id}\`
1609
+ `;
1610
+ content += `- **\u63CF\u8FF0**: ${agent.description || "\u6682\u65E0\u63CF\u8FF0"}
1611
+ `;
1612
+ content += `- **\u6765\u6E90**: \`${agent.path}\`
1613
+ `;
1614
+ if (agent.tags && agent.tags.length > 0) {
1615
+ content += `- **\u6807\u7B7E**: ${agent.tags.join(", ")}
1616
+ `;
1617
+ }
1618
+ content += `
1619
+ > \u{1F4A1} **\u4F7F\u7528\u65B9\u5F0F**: \u5728\u5F00\u53D1\u65F6\uFF0CCopilot \u4F1A\u81EA\u52A8\u901A\u8FC7 MCP \u5DE5\u5177\u52A0\u8F7D\u6B64 Agent \u7684\u5B8C\u6574\u89C4\u8303\u3002
1620
+
1621
+ `;
1622
+ }
1623
+ content += `---
1624
+
1625
+ `;
1626
+ if (updateMode === "merge" && existingCustomContent) {
1627
+ content += `
1628
+
1629
+ ## \u{1F4DD} \u81EA\u5B9A\u4E49\u89C4\u8303
1630
+
1631
+ `;
1632
+ content += existingCustomContent;
1633
+ logger3.log("\u2705 \u5DF2\u4FDD\u7559\u81EA\u5B9A\u4E49\u5185\u5BB9");
1634
+ }
1635
+ const validator = new CodeValidator(logger3);
1636
+ const validation = validator.validateConfigContent(content);
1637
+ if (!validation.isValid) {
1638
+ logger3.error("\u26A0\uFE0F \u914D\u7F6E\u5185\u5BB9\u9A8C\u8BC1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u4FEE\u590D...");
1639
+ const fixResult = validator.attemptAutoFix(content);
1640
+ if (fixResult.fixed) {
1641
+ content = fixResult.content;
1642
+ logger3.log(`\u2705 \u5DF2\u81EA\u52A8\u4FEE\u590D ${fixResult.changes.length} \u4E2A\u95EE\u9898:`);
1643
+ fixResult.changes.forEach((change) => logger3.log(` - ${change}`));
1644
+ const revalidation = validator.validateConfigContent(content);
1645
+ if (!revalidation.isValid) {
1646
+ const report = validator.generateValidationReport(revalidation);
1647
+ logger3.error("\u274C \u81EA\u52A8\u4FEE\u590D\u540E\u4ECD\u5B58\u5728\u95EE\u9898:");
1648
+ logger3.error(report);
1649
+ return {
1650
+ content: [{
1651
+ type: "text",
1652
+ text: JSON.stringify({
1653
+ error: "\u914D\u7F6E\u6587\u4EF6\u9A8C\u8BC1\u5931\u8D25",
1654
+ validationReport: report,
1655
+ message: "\u751F\u6210\u7684\u914D\u7F6E\u6587\u4EF6\u5B58\u5728\u8BED\u6CD5\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u5E76\u624B\u52A8\u4FEE\u590D"
1656
+ }, null, 2)
1657
+ }]
1658
+ };
1659
+ }
1660
+ } else {
1661
+ const report = validator.generateValidationReport(validation);
1662
+ logger3.error(report);
1663
+ return {
1664
+ content: [{
1665
+ type: "text",
1666
+ text: JSON.stringify({
1667
+ error: "\u914D\u7F6E\u6587\u4EF6\u9A8C\u8BC1\u5931\u8D25",
1668
+ validationReport: report,
1669
+ message: "\u751F\u6210\u7684\u914D\u7F6E\u6587\u4EF6\u5B58\u5728\u8BED\u6CD5\u9519\u8BEF\u4E14\u65E0\u6CD5\u81EA\u52A8\u4FEE\u590D"
1670
+ }, null, 2)
1671
+ }]
1672
+ };
1673
+ }
1674
+ } else if (validation.warnings.length > 0) {
1675
+ logger3.log("\u26A0\uFE0F \u914D\u7F6E\u5185\u5BB9\u9A8C\u8BC1\u901A\u8FC7\uFF0C\u4F46\u6709\u4EE5\u4E0B\u8B66\u544A:");
1676
+ validation.warnings.forEach((warning) => {
1677
+ logger3.log(` - [${warning.type}] ${warning.message}`);
1678
+ });
1679
+ } else {
1680
+ logger3.log("\u2705 \u914D\u7F6E\u5185\u5BB9\u9A8C\u8BC1\u901A\u8FC7");
1681
+ }
1682
+ fs4.writeFileSync(configPath, content, "utf-8");
1683
+ const gitignorePath = path4.join(args.projectPath, ".gitignore");
1684
+ if (fs4.existsSync(gitignorePath)) {
1685
+ let gitignoreContent = fs4.readFileSync(gitignorePath, "utf-8");
1686
+ if (!gitignoreContent.includes(".github/copilot-instructions.md")) {
1687
+ gitignoreContent += "\n# Copilot Prompts (auto-generated)\n.github/copilot-instructions.md\n";
1688
+ fs4.writeFileSync(gitignorePath, gitignoreContent, "utf-8");
1689
+ }
1690
+ }
1691
+ logger3.log(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u751F\u6210: ${configPath}`);
1692
+ return {
1693
+ content: [{
1694
+ type: "text",
1695
+ text: JSON.stringify({
1696
+ success: true,
1697
+ configPath,
1698
+ agents: selectedAgents.map((a) => ({
1699
+ id: a.id,
1700
+ title: a.title,
1701
+ score: a.score
1702
+ })),
1703
+ message: `\u5DF2\u6210\u529F\u751F\u6210\u914D\u7F6E\u6587\u4EF6\uFF0C\u5E94\u7528\u4E86 ${selectedAgents.length} \u4E2A Agents`
1704
+ }, null, 2)
1705
+ }]
1706
+ };
1707
+ } catch (error) {
1708
+ logger3.error(`\u751F\u6210\u914D\u7F6E\u5931\u8D25: ${error}`);
1709
+ return {
1710
+ content: [{
1711
+ type: "text",
1712
+ text: JSON.stringify({
1713
+ error: error instanceof Error ? error.message : String(error)
1714
+ }, null, 2)
1715
+ }]
1716
+ };
1717
+ }
1718
+ }
1719
+
1720
+ // src/tools/autoSetup.ts
1721
+ var fs5 = __toESM(require("fs"), 1);
1722
+ var path5 = __toESM(require("path"), 1);
1723
+ async function autoSetup(args) {
1724
+ var _a, _b, _c, _d, _e, _f, _g;
1725
+ const logger3 = new ConsoleLogger();
1726
+ try {
1727
+ const workspacePath = args.workspacePath || process.cwd();
1728
+ if (!fs5.existsSync(workspacePath)) {
1729
+ return {
1730
+ content: [{
1731
+ type: "text",
1732
+ text: JSON.stringify({
1733
+ error: `\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728: ${workspacePath}`
1734
+ }, null, 2)
1735
+ }]
1736
+ };
1737
+ }
1738
+ const results = {
1739
+ workspacePath,
1740
+ steps: [],
1741
+ warnings: []
1742
+ };
1743
+ logger3.log("\u{1F680} \u5F00\u59CB\u81EA\u52A8\u914D\u7F6E MCP \u670D\u52A1\u5668...");
1744
+ const vscodeDir = path5.join(workspacePath, ".vscode");
1745
+ if (!fs5.existsSync(vscodeDir)) {
1746
+ fs5.mkdirSync(vscodeDir, { recursive: true });
1747
+ results.steps.push({ step: "\u521B\u5EFA .vscode \u76EE\u5F55", status: "success" });
1748
+ } else {
1749
+ results.steps.push({ step: "\u68C0\u6D4B\u5230\u5DF2\u6709 .vscode \u76EE\u5F55", status: "skip" });
1750
+ }
1751
+ let mcpServerPath = "";
1752
+ const possiblePaths = [
1753
+ path5.join(workspacePath, "mcp-server/build/index.js"),
1754
+ path5.join(workspacePath, "../copilot-prompts/mcp-server/build/index.js"),
1755
+ path5.join(workspacePath, "copilot-prompts/mcp-server/build/index.js")
1756
+ ];
1757
+ for (const p of possiblePaths) {
1758
+ if (fs5.existsSync(p)) {
1759
+ mcpServerPath = p;
1760
+ break;
1761
+ }
1762
+ }
1763
+ if (!mcpServerPath) {
1764
+ const srcPath = path5.join(workspacePath, "mcp-server/src/index.ts");
1765
+ if (fs5.existsSync(srcPath)) {
1766
+ results.warnings.push("\u68C0\u6D4B\u5230\u5F00\u53D1\u6A21\u5F0F\uFF0C\u8BF7\u5148\u8FD0\u884C npm run build \u7F16\u8BD1\u670D\u52A1\u5668");
1767
+ mcpServerPath = "${workspaceFolder}/mcp-server/build/index.js";
1768
+ } else {
1769
+ return {
1770
+ content: [{
1771
+ type: "text",
1772
+ text: JSON.stringify({
1773
+ error: "MCP \u670D\u52A1\u5668\u672A\u627E\u5230",
1774
+ hint: "\u8BF7\u786E\u4FDD mcp-server/build/index.js \u5B58\u5728\uFF0C\u6216\u8FD0\u884C npm run build"
1775
+ }, null, 2)
1776
+ }]
1777
+ };
1778
+ }
1779
+ }
1780
+ const relativePath = mcpServerPath.startsWith(workspacePath) ? "${workspaceFolder}/" + path5.relative(workspacePath, mcpServerPath) : mcpServerPath;
1781
+ results.steps.push({
1782
+ step: "\u68C0\u6D4B MCP \u670D\u52A1\u5668\u8DEF\u5F84",
1783
+ status: "success",
1784
+ detail: relativePath
1785
+ });
1786
+ const mcpJsonPath = path5.join(vscodeDir, "mcp.json");
1787
+ const mcpConfig = {
1788
+ servers: {
1789
+ "copilot-prompts": {
1790
+ command: "node",
1791
+ args: [relativePath],
1792
+ env: {},
1793
+ autoStart: true
1794
+ }
1795
+ }
1796
+ };
1797
+ if (fs5.existsSync(mcpJsonPath)) {
1798
+ try {
1799
+ const existingConfig = JSON.parse(fs5.readFileSync(mcpJsonPath, "utf-8"));
1800
+ if (existingConfig.mcpServers && !existingConfig.servers) {
1801
+ results.warnings.push("\u68C0\u6D4B\u5230\u65E7\u7248\u914D\u7F6E\u683C\u5F0F(mcpServers)\uFF0C\u5DF2\u81EA\u52A8\u5347\u7EA7\u4E3A\u65B0\u683C\u5F0F(servers)");
1802
+ existingConfig.servers = existingConfig.mcpServers;
1803
+ delete existingConfig.mcpServers;
1804
+ }
1805
+ if ((_a = existingConfig.servers) == null ? void 0 : _a["copilot-prompts"]) {
1806
+ existingConfig.servers["copilot-prompts"] = {
1807
+ ...mcpConfig.servers["copilot-prompts"],
1808
+ ...existingConfig.servers["copilot-prompts"]
1809
+ };
1810
+ fs5.writeFileSync(mcpJsonPath, JSON.stringify(existingConfig, null, 2));
1811
+ results.steps.push({ step: "\u66F4\u65B0 mcp.json", status: "success" });
1812
+ } else {
1813
+ existingConfig.servers = {
1814
+ ...existingConfig.servers,
1815
+ ...mcpConfig.servers
1816
+ };
1817
+ fs5.writeFileSync(mcpJsonPath, JSON.stringify(existingConfig, null, 2));
1818
+ results.steps.push({ step: "\u5408\u5E76\u914D\u7F6E\u5230 mcp.json", status: "success" });
1819
+ }
1820
+ } catch (err) {
1821
+ fs5.writeFileSync(mcpJsonPath, JSON.stringify(mcpConfig, null, 2));
1822
+ results.steps.push({ step: "\u91CD\u65B0\u521B\u5EFA mcp.json", status: "success" });
1823
+ results.warnings.push(`\u539F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${err}`);
1824
+ }
1825
+ } else {
1826
+ fs5.writeFileSync(mcpJsonPath, JSON.stringify(mcpConfig, null, 2));
1827
+ results.steps.push({ step: "\u521B\u5EFA mcp.json", status: "success" });
1828
+ }
1829
+ const settingsJsonPath = path5.join(vscodeDir, "settings.json");
1830
+ const mcpSettings = {
1831
+ "github.copilot.chat.mcp.enabled": true,
1832
+ "github.copilot.chat.mcp.configFile": "${workspaceFolder}/.vscode/mcp.json",
1833
+ "github.copilot.chat.mcp.autoStart": true
1834
+ };
1835
+ if (fs5.existsSync(settingsJsonPath)) {
1836
+ try {
1837
+ const existingSettings = JSON.parse(fs5.readFileSync(settingsJsonPath, "utf-8"));
1838
+ const updated = { ...existingSettings, ...mcpSettings };
1839
+ fs5.writeFileSync(settingsJsonPath, JSON.stringify(updated, null, 2) + "\n");
1840
+ results.steps.push({ step: "\u66F4\u65B0 settings.json", status: "success" });
1841
+ } catch {
1842
+ fs5.writeFileSync(settingsJsonPath, JSON.stringify(mcpSettings, null, 2) + "\n");
1843
+ results.steps.push({ step: "\u91CD\u65B0\u521B\u5EFA settings.json", status: "success" });
1844
+ }
1845
+ } else {
1846
+ fs5.writeFileSync(settingsJsonPath, JSON.stringify(mcpSettings, null, 2) + "\n");
1847
+ results.steps.push({ step: "\u521B\u5EFA settings.json", status: "success" });
1848
+ }
1849
+ const extensionsJsonPath = path5.join(vscodeDir, "extensions.json");
1850
+ const recommendedExtensions = {
1851
+ recommendations: [
1852
+ "github.copilot",
1853
+ "github.copilot-chat"
1854
+ ]
1855
+ };
1856
+ if (!fs5.existsSync(extensionsJsonPath)) {
1857
+ fs5.writeFileSync(extensionsJsonPath, JSON.stringify(recommendedExtensions, null, 2));
1858
+ results.steps.push({ step: "\u521B\u5EFA extensions.json", status: "success" });
1859
+ } else {
1860
+ results.steps.push({ step: "extensions.json \u5DF2\u5B58\u5728", status: "skip" });
1861
+ }
1862
+ const gitignorePath = path5.join(workspacePath, ".gitignore");
1863
+ if (fs5.existsSync(gitignorePath)) {
1864
+ const gitignoreContent = fs5.readFileSync(gitignorePath, "utf-8");
1865
+ if (!gitignoreContent.includes(".vscode/mcp.json")) {
1866
+ const updatedContent = gitignoreContent + "\n# MCP \u914D\u7F6E\uFF08\u672C\u5730\uFF09\n.vscode/mcp.json\n";
1867
+ fs5.writeFileSync(gitignorePath, updatedContent);
1868
+ results.steps.push({ step: "\u6DFB\u52A0\u5230 .gitignore", status: "success" });
1869
+ } else {
1870
+ results.steps.push({ step: ".gitignore \u5DF2\u5305\u542B\u914D\u7F6E", status: "skip" });
1871
+ }
1872
+ } else {
1873
+ results.warnings.push("\u672A\u68C0\u6D4B\u5230 .gitignore\uFF0C\u5EFA\u8BAE\u624B\u52A8\u6DFB\u52A0 .vscode/mcp.json");
1874
+ }
1875
+ const generateInstructions = args.generateInstructions !== false;
1876
+ if (generateInstructions) {
1877
+ logger3.log("\u{1F50D} \u5206\u6790\u9879\u76EE\u5E76\u751F\u6210 copilot-instructions.md...");
1878
+ try {
1879
+ const analysisResult = await analyzeProject({ projectPath: workspacePath });
1880
+ const analysisContent = analysisResult.content[0];
1881
+ if (analysisContent.type === "text") {
1882
+ const analysisData = JSON.parse(analysisContent.text);
1883
+ if (analysisData.success && analysisData.features) {
1884
+ const agentIds = [];
1885
+ const features = analysisData.features;
1886
+ if (((_b = features.frameworks) == null ? void 0 : _b.includes("Vue 3")) || ((_c = features.frameworks) == null ? void 0 : _c.includes("Vue"))) {
1887
+ agentIds.push("vue3");
1888
+ }
1889
+ if ((_d = features.tools) == null ? void 0 : _d.includes("LogicFlow")) {
1890
+ agentIds.push("logicflow");
1891
+ }
1892
+ if (((_e = features.keywords) == null ? void 0 : _e.includes("i18n")) || ((_f = features.keywords) == null ? void 0 : _f.includes("\u56FD\u9645\u5316"))) {
1893
+ agentIds.push("i18n");
1894
+ }
1895
+ if (features.projectType === "flutter") {
1896
+ agentIds.push("flutter");
1897
+ }
1898
+ if (features.projectType === "wechat-miniprogram") {
1899
+ agentIds.push("wechat-miniprogram");
1900
+ }
1901
+ if (agentIds.length > 0) {
1902
+ const configResult = await generateConfig({
1903
+ projectPath: workspacePath,
1904
+ agentIds,
1905
+ autoMatch: false,
1906
+ updateMode: "merge"
1907
+ });
1908
+ const configContent = configResult.content[0];
1909
+ if (configContent.type === "text") {
1910
+ const configData = JSON.parse(configContent.text);
1911
+ if (configData.success) {
1912
+ results.steps.push({
1913
+ step: "\u751F\u6210 copilot-instructions.md",
1914
+ status: "success",
1915
+ detail: `\u5E94\u7528\u4E86 ${((_g = configData.agents) == null ? void 0 : _g.length) || 0} \u4E2A Agents: ${agentIds.join(", ")}`
1916
+ });
1917
+ } else {
1918
+ results.warnings.push(`\u914D\u7F6E\u751F\u6210\u5931\u8D25: ${configData.error || "\u672A\u77E5\u9519\u8BEF"}`);
1919
+ }
1920
+ }
1921
+ } else {
1922
+ results.warnings.push("\u672A\u627E\u5230\u5339\u914D\u7684 Agents\uFF0C\u8DF3\u8FC7\u914D\u7F6E\u751F\u6210");
1923
+ results.warnings.push("\u4F60\u53EF\u4EE5\u7A0D\u540E\u624B\u52A8\u8FD0\u884C generate_config \u5DE5\u5177\u5E76\u6307\u5B9A agentIds");
1924
+ }
1925
+ } else {
1926
+ results.warnings.push(`\u9879\u76EE\u5206\u6790\u5931\u8D25: ${analysisData.error || "\u672A\u77E5\u9519\u8BEF"}`);
1927
+ }
1928
+ }
1929
+ } catch (error) {
1930
+ results.warnings.push(`\u81EA\u52A8\u751F\u6210\u914D\u7F6E\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
1931
+ results.warnings.push("\u4F60\u53EF\u4EE5\u7A0D\u540E\u624B\u52A8\u8FD0\u884C generate_config \u5DE5\u5177\u751F\u6210\u914D\u7F6E");
1932
+ }
1933
+ } else {
1934
+ results.steps.push({ step: "\u8DF3\u8FC7 copilot-instructions.md \u751F\u6210", status: "skip" });
1935
+ }
1936
+ logger3.log("\u2705 \u81EA\u52A8\u914D\u7F6E\u5B8C\u6210\uFF01");
1937
+ return {
1938
+ content: [{
1939
+ type: "text",
1940
+ text: JSON.stringify({
1941
+ success: true,
1942
+ message: "\u{1F389} MCP \u670D\u52A1\u5668\u5DF2\u81EA\u52A8\u914D\u7F6E\u5230\u5DE5\u4F5C\u533A",
1943
+ ...results,
1944
+ nextSteps: [
1945
+ "1. \u91CD\u65B0\u52A0\u8F7D VS Code \u7A97\u53E3 (Cmd+Shift+P \u2192 Reload Window)",
1946
+ "2. \u6253\u5F00 GitHub Copilot Chat",
1947
+ "3. \u5F00\u59CB\u4F7F\u7528\uFF1ACopilot \u4F1A\u81EA\u52A8\u5E94\u7528\u9879\u76EE\u89C4\u8303",
1948
+ '4. \u9AD8\u7EA7\u7528\u6CD5\uFF1A\u5C1D\u8BD5\u8BF4"\u83B7\u53D6 Vue 3 \u76F8\u5173\u89C4\u8303"'
1949
+ ]
1950
+ }, null, 2)
1951
+ }]
1952
+ };
1953
+ } catch (error) {
1954
+ logger3.error(`\u81EA\u52A8\u914D\u7F6E\u5931\u8D25: ${error}`);
1955
+ return {
1956
+ content: [{
1957
+ type: "text",
1958
+ text: JSON.stringify({
1959
+ error: error instanceof Error ? error.message : String(error)
1960
+ }, null, 2)
1961
+ }]
1962
+ };
1963
+ }
1964
+ }
1965
+
1966
+ // src/tools/getSmartStandards.ts
1967
+ var fs8 = __toESM(require("fs"), 1);
1968
+
1969
+ // src/core/standardsManager.ts
1970
+ var fs6 = __toESM(require("fs"), 1);
1971
+ var path6 = __toESM(require("path"), 1);
1972
+ var import_url2 = require("url");
1973
+ var __filename3 = (0, import_url2.fileURLToPath)(importMetaUrl);
1974
+ var __dirname3 = path6.dirname(__filename3);
1975
+ var StandardsManager = class {
1976
+ constructor() {
1977
+ // v1.2.0: 底层必须加载的核心规范
1978
+ this.MANDATORY_CORE_STANDARDS = [
1979
+ "standards://core/code-style",
1980
+ // 代码风格规范(命名、格式等)
1981
+ "standards://core/typescript-base",
1982
+ // TypeScript基础规范
1983
+ "standards://core/code-generation"
1984
+ // 代码生成规范(注释、文档等)
1985
+ ];
1986
+ // Phase 3: 缓存系统
1987
+ this.contentCache = /* @__PURE__ */ new Map();
1988
+ this.CACHE_DURATION = 30 * 60 * 1e3;
1989
+ // 30分钟
1990
+ this.MAX_CACHE_SIZE = 50;
1991
+ // 最多缓存50个条目
1992
+ // Phase 3: 使用统计
1993
+ this.stats = {
1994
+ standardCombinations: /* @__PURE__ */ new Map(),
1995
+ individualStandards: /* @__PURE__ */ new Map(),
1996
+ averageTokens: 0,
1997
+ totalCalls: 0
1998
+ };
1999
+ // Phase 3: 性能指标
2000
+ this.metrics = {
2001
+ totalCalls: 0,
2002
+ cacheHits: 0,
2003
+ cacheMisses: 0,
2004
+ averageResponseTime: 0,
2005
+ totalTokensSaved: 0
2006
+ };
2007
+ const devPath = path6.resolve(__dirname3, "../../../standards");
2008
+ const npmPath = path6.resolve(__dirname3, "../../standards");
2009
+ this.standardsPath = fs6.existsSync(npmPath) ? npmPath : devPath;
2010
+ }
2011
+ /**
2012
+ * 获取所有可用的规范资源
2013
+ */
2014
+ getAvailableStandards() {
2015
+ const standards = [];
2016
+ const categories = [
2017
+ { dir: "core", name: "\u6838\u5FC3\u89C4\u8303" },
2018
+ { dir: "frameworks", name: "\u6846\u67B6\u89C4\u8303" },
2019
+ { dir: "libraries", name: "\u5E93\u89C4\u8303" },
2020
+ { dir: "patterns", name: "\u8BBE\u8BA1\u6A21\u5F0F" }
2021
+ ];
2022
+ categories.forEach(({ dir, name: categoryName }) => {
2023
+ const categoryPath = path6.join(this.standardsPath, dir);
2024
+ if (!fs6.existsSync(categoryPath)) {
2025
+ return;
2026
+ }
2027
+ const files = fs6.readdirSync(categoryPath).filter((file) => file.endsWith(".md"));
2028
+ files.forEach((file) => {
2029
+ const standardId = file.replace(".md", "");
2030
+ standards.push({
2031
+ uri: `standards://${dir}/${standardId}`,
2032
+ name: this.getStandardName(dir, standardId),
2033
+ description: `${categoryName} - ${this.getStandardDescription(dir, standardId)}`,
2034
+ category: dir
2035
+ });
2036
+ });
2037
+ });
2038
+ return standards;
2039
+ }
2040
+ /**
2041
+ * 读取特定规范内容(Phase 3: 带缓存)
2042
+ */
2043
+ readStandard(uri) {
2044
+ const startTime = Date.now();
2045
+ const cached = this.contentCache.get(uri);
2046
+ if (cached && Date.now() - cached.timestamp < this.CACHE_DURATION) {
2047
+ cached.accessCount++;
2048
+ this.metrics.cacheHits++;
2049
+ return cached.content;
2050
+ }
2051
+ this.metrics.cacheMisses++;
2052
+ const match = uri.match(/^standards:\/\/([^/]+)\/(.+)$/);
2053
+ if (!match) {
2054
+ throw new Error(`Invalid standards URI: ${uri}`);
2055
+ }
2056
+ const [, category, standardId] = match;
2057
+ const filePath = path6.join(this.standardsPath, category, `${standardId}.md`);
2058
+ if (!fs6.existsSync(filePath)) {
2059
+ throw new Error(`Standard not found: ${uri}`);
2060
+ }
2061
+ const content = fs6.readFileSync(filePath, "utf-8");
2062
+ this.updateCache(uri, content);
2063
+ this.stats.individualStandards.set(
2064
+ uri,
2065
+ (this.stats.individualStandards.get(uri) || 0) + 1
2066
+ );
2067
+ const responseTime = Date.now() - startTime;
2068
+ this.updateAverageResponseTime(responseTime);
2069
+ return content;
2070
+ }
2071
+ /**
2072
+ * 更新缓存
2073
+ */
2074
+ updateCache(uri, content) {
2075
+ if (this.contentCache.size >= this.MAX_CACHE_SIZE) {
2076
+ let minAccessCount = Infinity;
2077
+ let lruKey = null;
2078
+ this.contentCache.forEach((entry, key) => {
2079
+ if (entry.accessCount < minAccessCount) {
2080
+ minAccessCount = entry.accessCount;
2081
+ lruKey = key;
2082
+ }
2083
+ });
2084
+ if (lruKey) {
2085
+ this.contentCache.delete(lruKey);
2086
+ }
2087
+ }
2088
+ this.contentCache.set(uri, {
2089
+ content,
2090
+ timestamp: Date.now(),
2091
+ accessCount: 1
2092
+ });
2093
+ }
2094
+ /**
2095
+ * 根据技术栈获取相关规范(增强版 - Phase 2)
2096
+ */
2097
+ getRelevantStandards(context) {
2098
+ const standardScores = /* @__PURE__ */ new Map();
2099
+ const WEIGHTS = {
2100
+ CORE: 100,
2101
+ // 核心规范始终包含
2102
+ FILE_TYPE: 50,
2103
+ // 文件类型匹配
2104
+ IMPORT_DIRECT: 40,
2105
+ // 直接导入匹配
2106
+ IMPORT_RELATED: 20,
2107
+ // 相关导入匹配
2108
+ SCENARIO: 30,
2109
+ // 场景匹配
2110
+ CONTENT: 15,
2111
+ // 内容关键词匹配
2112
+ THRESHOLD: 10
2113
+ // 最低阈值
2114
+ };
2115
+ this.MANDATORY_CORE_STANDARDS.forEach((standard) => {
2116
+ standardScores.set(standard, WEIGHTS.CORE);
2117
+ });
2118
+ let detectedImports = context.imports || [];
2119
+ if (context.fileContent && !context.imports) {
2120
+ detectedImports = this.detectImports(context.fileContent);
2121
+ }
2122
+ if (context.fileType) {
2123
+ this.scoreByFileType(context.fileType, standardScores, WEIGHTS);
2124
+ }
2125
+ if (detectedImports.length > 0) {
2126
+ this.scoreByImports(detectedImports, standardScores, WEIGHTS);
2127
+ }
2128
+ if (context.scenario) {
2129
+ this.scoreByScenario(context.scenario, standardScores, WEIGHTS);
2130
+ }
2131
+ if (context.fileContent) {
2132
+ this.scoreByContent(context.fileContent, standardScores, WEIGHTS);
2133
+ }
2134
+ const sortedStandards = Array.from(standardScores.entries()).filter(([_, score]) => score >= WEIGHTS.THRESHOLD).sort((a, b) => b[1] - a[1]).map(([uri]) => uri);
2135
+ this.stats.totalCalls++;
2136
+ const combinationKey = sortedStandards.join("|");
2137
+ this.stats.standardCombinations.set(
2138
+ combinationKey,
2139
+ (this.stats.standardCombinations.get(combinationKey) || 0) + 1
2140
+ );
2141
+ return sortedStandards;
2142
+ }
2143
+ /**
2144
+ * 自动检测文件中的导入语句
2145
+ */
2146
+ detectImports(content) {
2147
+ const imports = [];
2148
+ const importRegex = /import\s+(?:(?:{[^}]*}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/g;
2149
+ let match;
2150
+ while ((match = importRegex.exec(content)) !== null) {
2151
+ imports.push(match[1]);
2152
+ }
2153
+ const requireRegex = /require\(['"]([^'"]+)['"]\)/g;
2154
+ while ((match = requireRegex.exec(content)) !== null) {
2155
+ imports.push(match[1]);
2156
+ }
2157
+ return imports;
2158
+ }
2159
+ /**
2160
+ * 根据文件类型评分
2161
+ */
2162
+ scoreByFileType(fileType, scores, weights) {
2163
+ const type = fileType.toLowerCase();
2164
+ if (type === "vue" || type.endsWith(".vue")) {
2165
+ this.addScore(scores, "standards://frameworks/vue3-composition", weights.FILE_TYPE);
2166
+ this.addScore(scores, "standards://patterns/component-design", weights.FILE_TYPE * 0.6);
2167
+ }
2168
+ if (type === "wxml" || type.endsWith(".wxml") || type === "wxss" || type.endsWith(".wxss") || type === "wxs" || type.endsWith(".wxs")) {
2169
+ this.addScore(scores, "standards://frameworks/wechat-miniprogram", weights.FILE_TYPE);
2170
+ }
2171
+ if (type === "ts" || type === "typescript" || type.endsWith(".ts")) {
2172
+ this.addScore(scores, "standards://core/typescript-base", weights.FILE_TYPE * 0.3);
2173
+ }
2174
+ if (type === "dart" || type.endsWith(".dart")) {
2175
+ this.addScore(scores, "standards://frameworks/flutter", weights.FILE_TYPE);
2176
+ this.addScore(scores, "standards://frameworks/flutter-ui-system", weights.FILE_TYPE);
2177
+ this.addScore(scores, "standards://core/dart-base", weights.FILE_TYPE * 0.5);
2178
+ }
2179
+ }
2180
+ /**
2181
+ * 根据导入评分
2182
+ */
2183
+ scoreByImports(imports, scores, weights) {
2184
+ imports.forEach((imp) => {
2185
+ const normalized = imp.toLowerCase();
2186
+ if (normalized === "vue" || normalized.startsWith("vue/")) {
2187
+ this.addScore(scores, "standards://frameworks/vue3-composition", weights.IMPORT_DIRECT);
2188
+ } else if (normalized.includes("vue")) {
2189
+ this.addScore(scores, "standards://frameworks/vue3-composition", weights.IMPORT_RELATED);
2190
+ }
2191
+ if (normalized === "pinia" || normalized.startsWith("pinia/")) {
2192
+ this.addScore(scores, "standards://frameworks/pinia", weights.IMPORT_DIRECT);
2193
+ }
2194
+ if (normalized === "element-plus" || normalized.startsWith("element-plus/")) {
2195
+ this.addScore(scores, "standards://libraries/element-plus", weights.IMPORT_DIRECT);
2196
+ } else if (normalized.includes("element")) {
2197
+ this.addScore(scores, "standards://libraries/element-plus", weights.IMPORT_RELATED);
2198
+ }
2199
+ if (normalized === "vue-i18n" || normalized.includes("i18n")) {
2200
+ this.addScore(scores, "standards://libraries/i18n", weights.IMPORT_DIRECT);
2201
+ }
2202
+ if (normalized === "wx" || normalized.includes("weixin") || normalized.includes("miniprogram")) {
2203
+ this.addScore(scores, "standards://frameworks/wechat-miniprogram", weights.IMPORT_DIRECT);
2204
+ }
2205
+ if (normalized === "axios" || normalized.includes("axios")) {
2206
+ this.addScore(scores, "standards://patterns/api-layer", weights.IMPORT_DIRECT);
2207
+ }
2208
+ if (normalized.includes("component") || normalized.startsWith("./components/")) {
2209
+ this.addScore(scores, "standards://patterns/component-design", weights.IMPORT_RELATED);
2210
+ }
2211
+ if (normalized === "flutter" || normalized.startsWith("flutter/") || normalized.startsWith("package:flutter")) {
2212
+ this.addScore(scores, "standards://frameworks/flutter", weights.IMPORT_DIRECT);
2213
+ this.addScore(scores, "standards://frameworks/flutter-ui-system", weights.IMPORT_DIRECT);
2214
+ }
2215
+ if (normalized === "get" || normalized.startsWith("get/") || normalized.startsWith("package:get")) {
2216
+ this.addScore(scores, "standards://frameworks/flutter", weights.IMPORT_DIRECT);
2217
+ }
2218
+ });
2219
+ }
2220
+ /**
2221
+ * 根据场景评分
2222
+ */
2223
+ scoreByScenario(scenario, scores, weights) {
2224
+ const normalized = scenario.toLowerCase();
2225
+ if (normalized.includes("api") || normalized.includes("request") || normalized.includes("fetch") || normalized.includes("axios")) {
2226
+ this.addScore(scores, "standards://patterns/api-layer", weights.SCENARIO);
2227
+ }
2228
+ if (normalized.includes("component") || normalized.includes("\u7EC4\u4EF6") || normalized.includes("widget") || normalized.includes("\u5C01\u88C5")) {
2229
+ this.addScore(scores, "standards://patterns/component-design", weights.SCENARIO);
2230
+ }
2231
+ if (normalized.includes("form") || normalized.includes("\u8868\u5355") || normalized.includes("input") || normalized.includes("validation")) {
2232
+ this.addScore(scores, "standards://libraries/element-plus", weights.SCENARIO);
2233
+ this.addScore(scores, "standards://patterns/component-design", weights.SCENARIO * 0.5);
2234
+ }
2235
+ if (normalized.includes("store") || normalized.includes("state") || normalized.includes("\u72B6\u6001") || normalized.includes("pinia")) {
2236
+ this.addScore(scores, "standards://frameworks/pinia", weights.SCENARIO);
2237
+ }
2238
+ if (normalized.includes("i18n") || normalized.includes("translate") || normalized.includes("\u56FD\u9645\u5316") || normalized.includes("\u7FFB\u8BD1") || normalized.includes("locale") || normalized.includes("\u591A\u8BED\u8A00") || normalized.includes("messages.ts") || normalized.includes("$t(")) {
2239
+ this.addScore(scores, "standards://libraries/i18n", weights.SCENARIO);
2240
+ }
2241
+ if (normalized.includes("css") || normalized.includes("\u6837\u5F0F") || normalized.includes("style") || normalized.includes("scoped") || normalized.includes("\u5D4C\u5957") || normalized.includes("nesting") || normalized.includes("\u5185\u8054") || normalized.includes("inline") || normalized.includes("\u5DE5\u5177\u7C7B") || normalized.includes("utilities") || normalized.includes(".ml_") || normalized.includes(".mr_") || normalized.includes(".mt_") || normalized.includes(".mb_") || normalized.includes(".w_") || normalized.includes(":deep(")) {
2242
+ this.addScore(scores, "standards://patterns/vue-css-nesting", weights.SCENARIO);
2243
+ }
2244
+ if (normalized.includes("\u5C0F\u7A0B\u5E8F") || normalized.includes("miniprogram") || normalized.includes("wechat") || normalized.includes("\u5FAE\u4FE1") || normalized.includes("wx.") || normalized.includes("page(") || normalized.includes("component(") || normalized.includes("\u4E91\u5F00\u53D1") || normalized.includes("\u4E91\u51FD\u6570") || normalized.includes("\u4E91\u6570\u636E\u5E93") || normalized.includes("\u4E91\u5B58\u50A8")) {
2245
+ this.addScore(scores, "standards://frameworks/wechat-miniprogram", weights.SCENARIO);
2246
+ }
2247
+ if (normalized.includes("flutter") || normalized.includes("dart") || normalized.includes("widget") || normalized.includes("ui\u7CFB\u7EDF") || normalized.includes("ui \u7CFB\u7EDF") || normalized.includes("flutter ui") || normalized.includes("design token") || normalized.includes("token") || normalized.includes("\u4E3B\u9898") || normalized.includes("theme")) {
2248
+ this.addScore(scores, "standards://frameworks/flutter", weights.SCENARIO);
2249
+ this.addScore(scores, "standards://frameworks/flutter-ui-system", weights.SCENARIO);
2250
+ }
2251
+ if (normalized.includes("flexbutton") || normalized.includes("flexcard") || normalized.includes("flexinput") || normalized.includes("flex\u7EC4\u4EF6") || normalized.includes("$c") || normalized.includes("$s") || normalized.includes("$t") || normalized.includes("$r")) {
2252
+ this.addScore(scores, "standards://frameworks/flutter-ui-system", weights.SCENARIO * 1.5);
2253
+ }
2254
+ }
2255
+ /**
2256
+ * 根据文件内容关键词评分
2257
+ */
2258
+ scoreByContent(content, scores, weights) {
2259
+ const normalized = content.toLowerCase();
2260
+ if (normalized.includes("defineprops") || normalized.includes("defineemits") || normalized.includes("ref(") || normalized.includes("computed(") || normalized.includes("watch(") || normalized.includes("onmounted")) {
2261
+ this.addScore(scores, "standards://frameworks/vue3-composition", weights.CONTENT);
2262
+ }
2263
+ if (normalized.includes("definestore") || normalized.includes("usestore") || normalized.includes("$patch") || normalized.includes("$subscribe")) {
2264
+ this.addScore(scores, "standards://frameworks/pinia", weights.CONTENT);
2265
+ }
2266
+ if (normalized.includes("el-form") || normalized.includes("el-table") || normalized.includes("el-dialog") || normalized.includes("elmessage")) {
2267
+ this.addScore(scores, "standards://libraries/element-plus", weights.CONTENT);
2268
+ }
2269
+ if (normalized.includes("$t(") || normalized.includes("t('") || normalized.includes("usei18n") || normalized.includes("locale") || normalized.includes("messages.ts") || normalized.includes("localestore") || normalized.includes("setlocale") || normalized.includes("togglelocale")) {
2270
+ this.addScore(scores, "standards://libraries/i18n", weights.CONTENT);
2271
+ }
2272
+ if (normalized.includes("<style scoped>") || normalized.includes("&:hover") || normalized.includes("&.active") || normalized.includes("&::before") || normalized.includes(":deep(") || normalized.includes(":global(") || normalized.includes('style="') || normalized.includes('class="ml_') || normalized.includes('class="mr_') || normalized.includes('class="mt_') || normalized.includes('class="w_')) {
2273
+ this.addScore(scores, "standards://patterns/vue-css-nesting", weights.CONTENT);
2274
+ }
2275
+ if (normalized.includes("wx.") || normalized.includes("page({") || normalized.includes("component({") || normalized.includes("setdata") || normalized.includes("onload") || normalized.includes("onshow") || normalized.includes("wx:for") || normalized.includes("wx:if") || normalized.includes("wx.cloud") || normalized.includes("cloudfunctions") || normalized.includes("callfunction") || normalized.includes("wx-server-sdk") || normalized.includes("cloud.init") || normalized.includes("exports.main")) {
2276
+ this.addScore(scores, "standards://frameworks/wechat-miniprogram", weights.CONTENT);
2277
+ }
2278
+ if (normalized.includes("axios.") || normalized.includes(".get(") || normalized.includes(".post(") || normalized.includes("interceptor")) {
2279
+ this.addScore(scores, "standards://patterns/api-layer", weights.CONTENT);
2280
+ }
2281
+ if (normalized.includes("statelesswidget") || normalized.includes("statefulwidget") || normalized.includes("buildcontext") || normalized.includes("@override") || normalized.includes("widget build(") || normalized.includes("getx") || normalized.includes("get.find") || normalized.includes("obx(")) {
2282
+ this.addScore(scores, "standards://frameworks/flutter", weights.CONTENT);
2283
+ }
2284
+ if (normalized.includes("$c.") || normalized.includes("$s.") || normalized.includes("$t.") || normalized.includes("$r.") || normalized.includes("$shadow.") || normalized.includes("$b.") || normalized.includes("flexbutton") || normalized.includes("flexcard") || normalized.includes("flexinput") || normalized.includes("flexbox") || normalized.includes("tokenmanager") || normalized.includes("designtokens") || normalized.includes("thememanager") || normalized.includes("gap(")) {
2285
+ this.addScore(scores, "standards://frameworks/flutter-ui-system", weights.CONTENT * 2);
2286
+ }
2287
+ }
2288
+ /**
2289
+ * 添加分数(累加)
2290
+ */
2291
+ addScore(scores, uri, points) {
2292
+ const current = scores.get(uri) || 0;
2293
+ scores.set(uri, current + points);
2294
+ }
2295
+ /**
2296
+ * 组合多个规范内容(Phase 3: 优化去重与顺序)
2297
+ */
2298
+ combineStandards(uris) {
2299
+ const startTime = Date.now();
2300
+ const uniqueUris = Array.from(new Set(uris));
2301
+ const coreUris = uniqueUris.filter((uri) => uri.startsWith("standards://core/"));
2302
+ const otherUris = uniqueUris.filter((uri) => !uri.startsWith("standards://core/"));
2303
+ const sortedUris = [...coreUris, ...otherUris];
2304
+ const contents = [];
2305
+ let totalSize = 0;
2306
+ sortedUris.forEach((uri) => {
2307
+ try {
2308
+ const content = this.readStandard(uri);
2309
+ const standardName = this.extractStandardName(uri);
2310
+ const section = `
2311
+ ## \u{1F4DA} ${standardName}
2312
+
2313
+ ${content}
2314
+ `;
2315
+ contents.push(section);
2316
+ totalSize += section.length;
2317
+ } catch (error) {
2318
+ console.error(`Failed to read standard ${uri}:`, error);
2319
+ }
2320
+ });
2321
+ const combined = contents.join("\n---\n");
2322
+ const estimatedTokens = Math.ceil(combined.length / 4);
2323
+ const baselineTokens = 1e4;
2324
+ const tokensSaved = baselineTokens - estimatedTokens;
2325
+ this.metrics.totalTokensSaved += Math.max(0, tokensSaved);
2326
+ const processingTime = Date.now() - startTime;
2327
+ console.log(`[StandardsManager] Combined ${sortedUris.length} standards in ${processingTime}ms, ~${estimatedTokens} tokens (saved ${tokensSaved})`);
2328
+ return combined;
2329
+ }
2330
+ /**
2331
+ * 提取规范名称
2332
+ */
2333
+ extractStandardName(uri) {
2334
+ const match = uri.match(/^standards:\/\/([^/]+)\/(.+)$/);
2335
+ if (match) {
2336
+ const [, category, standardId] = match;
2337
+ return this.getStandardName(category, standardId);
2338
+ }
2339
+ return uri;
2340
+ }
2341
+ /**
2342
+ * 获取规范显示名称
2343
+ */
2344
+ getStandardName(category, standardId) {
2345
+ var _a;
2346
+ const nameMap = {
2347
+ core: {
2348
+ "code-style": "\u4EE3\u7801\u98CE\u683C\u89C4\u8303",
2349
+ "typescript-base": "TypeScript \u57FA\u7840",
2350
+ "dart-base": "Dart \u57FA\u7840"
2351
+ },
2352
+ frameworks: {
2353
+ "vue3-composition": "Vue 3 Composition API",
2354
+ "pinia": "Pinia \u72B6\u6001\u7BA1\u7406",
2355
+ "flutter": "Flutter \u5F00\u53D1\u89C4\u8303",
2356
+ "flutter-ui-system": "Flutter UI \u7CFB\u7EDF\u89C4\u8303",
2357
+ "wechat-miniprogram": "\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F\u5F00\u53D1"
2358
+ },
2359
+ libraries: {
2360
+ "element-plus": "Element Plus \u7EC4\u4EF6\u5E93",
2361
+ "i18n": "\u56FD\u9645\u5316 (i18n)"
2362
+ },
2363
+ patterns: {
2364
+ "api-layer": "API \u5C42\u8BBE\u8BA1",
2365
+ "component-design": "\u7EC4\u4EF6\u8BBE\u8BA1\u6A21\u5F0F",
2366
+ "vue-css-nesting": "Vue CSS \u5D4C\u5957\u5199\u6CD5",
2367
+ "vue-api-mock-layer": "Vue API Mock \u5C42"
2368
+ }
2369
+ };
2370
+ return ((_a = nameMap[category]) == null ? void 0 : _a[standardId]) || standardId;
2371
+ }
2372
+ /**
2373
+ * 获取规范描述
2374
+ */
2375
+ getStandardDescription(category, standardId) {
2376
+ var _a;
2377
+ const descMap = {
2378
+ core: {
2379
+ "code-style": "\u547D\u540D\u89C4\u8303\u3001\u4EE3\u7801\u7EC4\u7EC7\u3001\u6CE8\u91CA\u89C4\u8303",
2380
+ "typescript-base": "\u57FA\u7840\u7C7B\u578B\u3001\u51FD\u6570\u3001\u6CDB\u578B\u4F7F\u7528",
2381
+ "dart-base": "\u7A7A\u5B89\u5168\u3001\u5F02\u6B65\u7F16\u7A0B\u3001\u7C7B\u548C\u5BF9\u8C61"
2382
+ },
2383
+ frameworks: {
2384
+ "vue3-composition": "Props\u3001Emits\u3001\u751F\u547D\u5468\u671F\u3001Composables",
2385
+ "pinia": "Store \u5B9A\u4E49\u3001\u72B6\u6001\u7BA1\u7406\u3001\u6301\u4E45\u5316",
2386
+ "flutter": "Widget \u8BBE\u8BA1\u3001\u72B6\u6001\u7BA1\u7406\u3001\u6027\u80FD\u4F18\u5316",
2387
+ "flutter-ui-system": "Design Token\u3001Flex\u7EC4\u4EF6\u3001\u4E3B\u9898\u7CFB\u7EDF\u3001$\u5FEB\u6377\u65B9\u5F0F",
2388
+ "wechat-miniprogram": "Page/Component\u3001\u7F51\u7EDC\u8BF7\u6C42\u3001\u6027\u80FD\u4F18\u5316"
2389
+ },
2390
+ libraries: {
2391
+ "element-plus": "\u8868\u5355\u3001\u8868\u683C\u3001\u5BF9\u8BDD\u6846\u3001\u6D88\u606F\u63D0\u793A",
2392
+ "i18n": "\u7FFB\u8BD1\u6587\u4EF6\u3001\u7EC4\u4EF6\u4F7F\u7528\u3001\u53C2\u6570\u5316"
2393
+ },
2394
+ patterns: {
2395
+ "api-layer": "Axios \u914D\u7F6E\u3001API \u6A21\u5757\u5316\u3001\u9519\u8BEF\u5904\u7406",
2396
+ "component-design": "\u7EC4\u4EF6\u901A\u4FE1\u3001Props \u9A8C\u8BC1\u3001\u6027\u80FD\u4F18\u5316",
2397
+ "vue-css-nesting": "\u539F\u751F\u5D4C\u5957\u8BED\u6CD5\u3001\u4F2A\u7C7B\u4F2A\u5143\u7D20\u3001\u6DF1\u5EA6\u9009\u62E9\u5668",
2398
+ "vue-api-mock-layer": "Axios\u5C01\u88C5\u3001Mock\u6570\u636E\u3001\u6A21\u5757\u5316API"
2399
+ }
2400
+ };
2401
+ return ((_a = descMap[category]) == null ? void 0 : _a[standardId]) || "";
2402
+ }
2403
+ /**
2404
+ * 更新平均响应时间
2405
+ */
2406
+ updateAverageResponseTime(responseTime) {
2407
+ const { totalCalls, averageResponseTime } = this.metrics;
2408
+ this.metrics.totalCalls++;
2409
+ this.metrics.averageResponseTime = (averageResponseTime * totalCalls + responseTime) / this.metrics.totalCalls;
2410
+ }
2411
+ /**
2412
+ * 获取性能指标
2413
+ */
2414
+ getPerformanceMetrics() {
2415
+ return {
2416
+ ...this.metrics,
2417
+ cacheHitRate: this.metrics.totalCalls > 0 ? (this.metrics.cacheHits / this.metrics.totalCalls * 100).toFixed(2) + "%" : "0%"
2418
+ };
2419
+ }
2420
+ /**
2421
+ * 获取使用统计
2422
+ */
2423
+ getUsageStats() {
2424
+ const topCombinations = Array.from(this.stats.standardCombinations.entries()).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([combination, count]) => ({ combination, count }));
2425
+ const topStandards = Array.from(this.stats.individualStandards.entries()).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([standard, count]) => ({ standard, count }));
2426
+ return {
2427
+ topCombinations,
2428
+ topStandards,
2429
+ totalCalls: this.stats.totalCalls
2430
+ };
2431
+ }
2432
+ /**
2433
+ * 清除缓存
2434
+ */
2435
+ clearCache() {
2436
+ this.contentCache.clear();
2437
+ console.log("[StandardsManager] Cache cleared");
2438
+ }
2439
+ /**
2440
+ * 获取缓存统计
2441
+ */
2442
+ getCacheStats() {
2443
+ const entries = Array.from(this.contentCache.entries()).map(([uri, entry]) => ({
2444
+ uri,
2445
+ accessCount: entry.accessCount,
2446
+ age: Math.floor((Date.now() - entry.timestamp) / 1e3)
2447
+ // 秒
2448
+ })).sort((a, b) => b.accessCount - a.accessCount);
2449
+ return {
2450
+ size: this.contentCache.size,
2451
+ maxSize: this.MAX_CACHE_SIZE,
2452
+ entries
2453
+ };
2454
+ }
2455
+ };
2456
+
2457
+ // src/core/autoInitializer.ts
2458
+ var fs7 = __toESM(require("fs"), 1);
2459
+ var path7 = __toESM(require("path"), 1);
2460
+ var AutoInitializer = class {
2461
+ constructor(logger3) {
2462
+ this.logger = logger3;
2463
+ this.initialized = /* @__PURE__ */ new Map();
2464
+ }
2465
+ /**
2466
+ * 检查并初始化项目配置
2467
+ * @param workspacePath 工作区路径
2468
+ * @returns 是否需要初始化(返回 true 表示已执行初始化)
2469
+ */
2470
+ async ensureProjectConfig(workspacePath) {
2471
+ var _a, _b, _c, _d;
2472
+ const projectPath = workspacePath || this.detectWorkspacePath();
2473
+ if (!projectPath) {
2474
+ return {
2475
+ needsInit: false,
2476
+ initialized: false,
2477
+ message: "\u672A\u68C0\u6D4B\u5230\u5DE5\u4F5C\u533A\u8DEF\u5F84"
2478
+ };
2479
+ }
2480
+ if (this.initialized.get(projectPath)) {
2481
+ return {
2482
+ needsInit: false,
2483
+ initialized: true,
2484
+ message: `\u9879\u76EE\u5DF2\u914D\u7F6E: ${path7.basename(projectPath)}`
2485
+ };
2486
+ }
2487
+ const configPath = path7.join(projectPath, ".github", "copilot-instructions.md");
2488
+ const hasConfig = fs7.existsSync(configPath);
2489
+ if (hasConfig) {
2490
+ this.initialized.set(projectPath, true);
2491
+ return {
2492
+ needsInit: false,
2493
+ initialized: true,
2494
+ message: `\u9879\u76EE\u5DF2\u6709\u914D\u7F6E: ${path7.basename(projectPath)}`
2495
+ };
2496
+ }
2497
+ this.log(`\u{1F50D} \u68C0\u6D4B\u5230\u9879\u76EE\u672A\u914D\u7F6E\uFF0C\u5F00\u59CB\u81EA\u52A8\u5206\u6790\u548C\u751F\u6210\u914D\u7F6E...`);
2498
+ this.log(`\u{1F4C1} \u9879\u76EE\u8DEF\u5F84: ${projectPath}`);
2499
+ try {
2500
+ this.log("1\uFE0F\u20E3 \u5206\u6790\u9879\u76EE\u6280\u672F\u6808...");
2501
+ const analysisResult = await analyzeProject({ projectPath });
2502
+ if ((_b = (_a = analysisResult.content) == null ? void 0 : _a[0]) == null ? void 0 : _b.text) {
2503
+ const analysis = JSON.parse(analysisResult.content[0].text);
2504
+ this.log(`\u2705 \u68C0\u6D4B\u5230: ${((_c = analysis.frameworks) == null ? void 0 : _c.join(", ")) || "\u672A\u77E5\u6280\u672F\u6808"}`);
2505
+ this.log("2\uFE0F\u20E3 \u751F\u6210\u9879\u76EE\u914D\u7F6E\u6587\u4EF6...");
2506
+ await generateConfig({
2507
+ projectPath,
2508
+ autoMatch: true
2509
+ });
2510
+ this.initialized.set(projectPath, true);
2511
+ return {
2512
+ needsInit: true,
2513
+ initialized: true,
2514
+ message: `\u2705 \u9879\u76EE\u914D\u7F6E\u5DF2\u81EA\u52A8\u751F\u6210
2515
+ \u{1F4C1} \u8DEF\u5F84: ${configPath}
2516
+ \u{1F3AF} \u6280\u672F\u6808: ${(_d = analysis.frameworks) == null ? void 0 : _d.join(", ")}`
2517
+ };
2518
+ }
2519
+ } catch (error) {
2520
+ this.log(`\u274C \u81EA\u52A8\u521D\u59CB\u5316\u5931\u8D25: ${error}`);
2521
+ return {
2522
+ needsInit: true,
2523
+ initialized: false,
2524
+ message: `\u26A0\uFE0F \u81EA\u52A8\u521D\u59CB\u5316\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`
2525
+ };
2526
+ }
2527
+ return {
2528
+ needsInit: true,
2529
+ initialized: false,
2530
+ message: "\u26A0\uFE0F \u65E0\u6CD5\u5B8C\u6210\u81EA\u52A8\u521D\u59CB\u5316"
2531
+ };
2532
+ }
2533
+ /**
2534
+ * 检测工作区路径
2535
+ */
2536
+ detectWorkspacePath() {
2537
+ if (process.env.WORKSPACE_PATH) {
2538
+ return process.env.WORKSPACE_PATH;
2539
+ }
2540
+ const cwd = process.cwd();
2541
+ if (this.isValidProject(cwd)) {
2542
+ return cwd;
2543
+ }
2544
+ const possiblePaths = [
2545
+ path7.join(cwd, ".."),
2546
+ path7.join(cwd, "../..")
2547
+ ];
2548
+ for (const possiblePath of possiblePaths) {
2549
+ if (this.isValidProject(possiblePath)) {
2550
+ return possiblePath;
2551
+ }
2552
+ }
2553
+ return null;
2554
+ }
2555
+ /**
2556
+ * 判断是否是有效的项目目录
2557
+ */
2558
+ isValidProject(dirPath) {
2559
+ if (!fs7.existsSync(dirPath)) {
2560
+ return false;
2561
+ }
2562
+ const markers = [
2563
+ "package.json",
2564
+ "pubspec.yaml",
2565
+ "pom.xml",
2566
+ "go.mod",
2567
+ "Cargo.toml",
2568
+ ".git"
2569
+ ];
2570
+ return markers.some(
2571
+ (marker) => fs7.existsSync(path7.join(dirPath, marker))
2572
+ );
2573
+ }
2574
+ /**
2575
+ * 重置初始化状态(用于测试)
2576
+ */
2577
+ reset() {
2578
+ this.initialized.clear();
2579
+ }
2580
+ log(message) {
2581
+ if (this.logger) {
2582
+ this.logger.log(message);
2583
+ } else {
2584
+ console.error(`[AutoInit] ${message}`);
2585
+ }
2586
+ }
2587
+ };
2588
+
2589
+ // src/tools/getSmartStandards.ts
2590
+ async function getSmartStandards(args) {
2591
+ var _a;
2592
+ const logger3 = new ConsoleLogger();
2593
+ const manager = new StandardsManager();
2594
+ const autoInit = new AutoInitializer(logger3);
2595
+ try {
2596
+ const initResult = await autoInit.ensureProjectConfig();
2597
+ if (initResult.needsInit) {
2598
+ logger3.log("\u{1F4CB} " + initResult.message);
2599
+ if (initResult.initialized) {
2600
+ return {
2601
+ content: [{
2602
+ type: "text",
2603
+ text: `\u{1F389} **\u9996\u6B21\u4F7F\u7528\u81EA\u52A8\u914D\u7F6E\u5B8C\u6210**
2604
+
2605
+ ${initResult.message}
2606
+
2607
+ \u73B0\u5728\u53EF\u4EE5\u7EE7\u7EED\u4F7F\u7528 @mta \u8FDB\u884C\u5F00\u53D1\u4E86\uFF01
2608
+
2609
+ \u{1F4A1} \u63D0\u793A\uFF1A\u9879\u76EE\u914D\u7F6E\u6587\u4EF6\u5DF2\u751F\u6210\u5728 .github/copilot-instructions.md`
2610
+ }]
2611
+ };
2612
+ }
2613
+ }
2614
+ let detectedFileType = "unknown";
2615
+ let detectedImports = [];
2616
+ let detectedScenario = "";
2617
+ let analysisSource = "none";
2618
+ if (args.currentFile && fs8.existsSync(args.currentFile)) {
2619
+ analysisSource = "file-path";
2620
+ const ext = ((_a = args.currentFile.split(".").pop()) == null ? void 0 : _a.toLowerCase()) || "";
2621
+ const extMap = {
2622
+ "vue": "vue",
2623
+ "ts": "ts",
2624
+ "tsx": "tsx",
2625
+ "js": "js",
2626
+ "jsx": "jsx"
2627
+ };
2628
+ detectedFileType = extMap[ext] || "unknown";
2629
+ try {
2630
+ const content = fs8.readFileSync(args.currentFile, "utf-8");
2631
+ const imports = extractImports(content);
2632
+ detectedImports = imports;
2633
+ detectedScenario = inferScenario(content, detectedFileType);
2634
+ } catch {
2635
+ logger3.log("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u4EC5\u4F7F\u7528\u6587\u4EF6\u7C7B\u578B");
2636
+ }
2637
+ }
2638
+ if (args.fileContent) {
2639
+ analysisSource = "file-content";
2640
+ const imports = extractImports(args.fileContent);
2641
+ detectedImports = [...detectedImports, ...imports];
2642
+ if (detectedFileType === "unknown") {
2643
+ if (args.fileContent.includes("<template>")) {
2644
+ detectedFileType = "vue";
2645
+ } else if (args.fileContent.includes("interface ") || args.fileContent.includes("type ")) {
2646
+ detectedFileType = "ts";
2647
+ }
2648
+ }
2649
+ const scenario = inferScenario(args.fileContent, detectedFileType);
2650
+ if (scenario) detectedScenario = scenario;
2651
+ }
2652
+ if (detectedFileType === "unknown") {
2653
+ analysisSource = "environment";
2654
+ const cwd = process.cwd();
2655
+ const packageJsonPath = `${cwd}/package.json`;
2656
+ if (fs8.existsSync(packageJsonPath)) {
2657
+ try {
2658
+ const pkg = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
2659
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
2660
+ if (deps["vue"]) {
2661
+ detectedFileType = "vue";
2662
+ detectedImports.push("vue");
2663
+ }
2664
+ if (deps["react"]) {
2665
+ detectedFileType = "tsx";
2666
+ detectedImports.push("react");
2667
+ }
2668
+ if (deps["element-plus"]) detectedImports.push("element-plus");
2669
+ if (deps["pinia"]) detectedImports.push("pinia");
2670
+ if (deps["vue-i18n"]) detectedImports.push("vue-i18n");
2671
+ } catch {
2672
+ logger3.log("\u65E0\u6CD5\u89E3\u6790 package.json");
2673
+ }
2674
+ }
2675
+ }
2676
+ detectedImports = [...new Set(detectedImports)];
2677
+ logger3.log(`\u{1F50D} \u667A\u80FD\u68C0\u6D4B\u7ED3\u679C: fileType=${detectedFileType}, imports=${detectedImports.join(",")}, scenario=${detectedScenario}`);
2678
+ const standards = manager.getRelevantStandards({
2679
+ fileType: detectedFileType !== "unknown" ? detectedFileType : void 0,
2680
+ imports: detectedImports.length > 0 ? detectedImports : void 0,
2681
+ scenario: detectedScenario || void 0
2682
+ });
2683
+ const combinedContent = manager.combineStandards(standards);
2684
+ return {
2685
+ content: [{
2686
+ type: "text",
2687
+ text: JSON.stringify({
2688
+ success: true,
2689
+ analysis: {
2690
+ source: analysisSource,
2691
+ fileType: detectedFileType,
2692
+ imports: detectedImports,
2693
+ scenario: detectedScenario
2694
+ },
2695
+ standards,
2696
+ content: combinedContent,
2697
+ stats: {
2698
+ standardsCount: standards.length,
2699
+ contentLength: combinedContent.length,
2700
+ estimatedTokens: Math.ceil(combinedContent.length / 4)
2701
+ }
2702
+ }, null, 2)
2703
+ }]
2704
+ };
2705
+ } catch (error) {
2706
+ logger3.error(`\u667A\u80FD\u89C4\u8303\u63A8\u8350\u5931\u8D25: ${error}`);
2707
+ return {
2708
+ content: [{
2709
+ type: "text",
2710
+ text: JSON.stringify({
2711
+ error: error instanceof Error ? error.message : String(error)
2712
+ }, null, 2)
2713
+ }]
2714
+ };
2715
+ }
2716
+ }
2717
+ function extractImports(content) {
2718
+ const imports = [];
2719
+ const es6Regex = /import\s+.*?\s+from\s+['"]([^'"]+)['"]/g;
2720
+ let match;
2721
+ while ((match = es6Regex.exec(content)) !== null) {
2722
+ const pkg = match[1];
2723
+ if (!pkg.startsWith(".") && !pkg.startsWith("/")) {
2724
+ imports.push(pkg.split("/")[0]);
2725
+ }
2726
+ }
2727
+ const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
2728
+ while ((match = requireRegex.exec(content)) !== null) {
2729
+ const pkg = match[1];
2730
+ if (!pkg.startsWith(".") && !pkg.startsWith("/")) {
2731
+ imports.push(pkg.split("/")[0]);
2732
+ }
2733
+ }
2734
+ return [...new Set(imports)];
2735
+ }
2736
+ function inferScenario(content, fileType) {
2737
+ const scenarios = [];
2738
+ if (fileType === "vue") {
2739
+ if (content.includes("ElForm") || content.includes("<el-form")) {
2740
+ scenarios.push("\u8868\u5355\u7EC4\u4EF6");
2741
+ }
2742
+ if (content.includes("ElTable") || content.includes("<el-table")) {
2743
+ scenarios.push("\u8868\u683C\u7EC4\u4EF6");
2744
+ }
2745
+ if (content.includes("defineStore")) {
2746
+ scenarios.push("\u72B6\u6001\u7BA1\u7406");
2747
+ }
2748
+ if (content.includes("useI18n") || content.includes("$t(")) {
2749
+ scenarios.push("\u56FD\u9645\u5316");
2750
+ }
2751
+ }
2752
+ if (content.includes("fetch(") || content.includes("axios.")) {
2753
+ scenarios.push("API \u8C03\u7528");
2754
+ }
2755
+ if (content.includes("interface ") || content.includes("type ")) {
2756
+ scenarios.push("\u7C7B\u578B\u5B9A\u4E49");
2757
+ }
2758
+ return scenarios.join("\u3001");
2759
+ }
2760
+
2761
+ // src/tools/usePreset.ts
2762
+ var PRESETS = {
2763
+ "vue3-component": {
2764
+ name: "Vue 3 \u7EC4\u4EF6\u5F00\u53D1",
2765
+ fileType: "vue",
2766
+ imports: ["vue", "element-plus"],
2767
+ scenario: "\u7EC4\u4EF6\u5F00\u53D1",
2768
+ description: "\u5F00\u53D1 Vue 3 \u5355\u6587\u4EF6\u7EC4\u4EF6\uFF0C\u5305\u542B Composition API \u548C Element Plus"
2769
+ },
2770
+ "vue3-form": {
2771
+ name: "Vue 3 \u8868\u5355\u5F00\u53D1",
2772
+ fileType: "vue",
2773
+ imports: ["vue", "element-plus"],
2774
+ scenario: "\u8868\u5355\u7EC4\u4EF6",
2775
+ description: "Element Plus \u8868\u5355\u7EC4\u4EF6\u5F00\u53D1\uFF0C\u5305\u542B\u9A8C\u8BC1\u548C\u56FD\u9645\u5316"
2776
+ },
2777
+ "vue3-table": {
2778
+ name: "Vue 3 \u8868\u683C\u5F00\u53D1",
2779
+ fileType: "vue",
2780
+ imports: ["vue", "element-plus"],
2781
+ scenario: "\u8868\u683C\u7EC4\u4EF6",
2782
+ description: "Element Plus \u8868\u683C\u7EC4\u4EF6\u5F00\u53D1\uFF0C\u5305\u542B\u5206\u9875\u548C\u64CD\u4F5C"
2783
+ },
2784
+ "pinia-store": {
2785
+ name: "Pinia \u72B6\u6001\u7BA1\u7406",
2786
+ fileType: "ts",
2787
+ imports: ["vue", "pinia"],
2788
+ scenario: "\u72B6\u6001\u7BA1\u7406",
2789
+ description: "Pinia store \u5B9A\u4E49\uFF0C\u5305\u542B actions\u3001getters \u548C\u6301\u4E45\u5316"
2790
+ },
2791
+ "api-call": {
2792
+ name: "API \u8C03\u7528\u5C42",
2793
+ fileType: "ts",
2794
+ imports: ["axios"],
2795
+ scenario: "API \u8C03\u7528",
2796
+ description: "RESTful API \u8C03\u7528\u5C01\u88C5\uFF0C\u5305\u542B\u9519\u8BEF\u5904\u7406\u548C\u7C7B\u578B\u5B9A\u4E49"
2797
+ },
2798
+ "typescript-strict": {
2799
+ name: "TypeScript \u4E25\u683C\u6A21\u5F0F",
2800
+ fileType: "ts",
2801
+ imports: [],
2802
+ scenario: "\u7C7B\u578B\u5B9A\u4E49",
2803
+ description: "TypeScript \u4E25\u683C\u7C7B\u578B\u5B9A\u4E49\u548C\u7C7B\u578B\u5B88\u536B"
2804
+ },
2805
+ "i18n": {
2806
+ name: "\u56FD\u9645\u5316\u5F00\u53D1",
2807
+ fileType: "vue",
2808
+ imports: ["vue", "vue-i18n"],
2809
+ scenario: "\u56FD\u9645\u5316",
2810
+ description: "Vue I18n \u591A\u8BED\u8A00\u652F\u6301\uFF0C\u5305\u542B\u7FFB\u8BD1\u6587\u4EF6\u7BA1\u7406"
2811
+ },
2812
+ "composable": {
2813
+ name: "Vue 3 Composable",
2814
+ fileType: "ts",
2815
+ imports: ["vue"],
2816
+ scenario: "\u53EF\u7EC4\u5408\u51FD\u6570",
2817
+ description: "Vue 3 \u7EC4\u5408\u5F0F\u51FD\u6570\u5F00\u53D1\uFF0C\u590D\u7528\u903B\u8F91"
2818
+ }
2819
+ };
2820
+ async function usePreset(args) {
2821
+ const logger3 = new ConsoleLogger();
2822
+ const manager = new StandardsManager();
2823
+ try {
2824
+ if (!(args.preset in PRESETS)) {
2825
+ return {
2826
+ content: [{
2827
+ type: "text",
2828
+ text: JSON.stringify({
2829
+ error: `\u672A\u77E5\u7684\u9884\u8BBE: ${args.preset}`,
2830
+ availablePresets: Object.keys(PRESETS).map((id) => ({
2831
+ id,
2832
+ name: PRESETS[id].name,
2833
+ description: PRESETS[id].description
2834
+ }))
2835
+ }, null, 2)
2836
+ }]
2837
+ };
2838
+ }
2839
+ const preset = PRESETS[args.preset];
2840
+ logger3.log(`\u{1F3AF} \u4F7F\u7528\u9884\u8BBE: ${preset.name}`);
2841
+ const imports = args.customImports ? [...preset.imports, ...args.customImports] : [...preset.imports];
2842
+ const standards = manager.getRelevantStandards({
2843
+ fileType: preset.fileType,
2844
+ imports: imports.length > 0 ? imports : void 0,
2845
+ scenario: preset.scenario
2846
+ });
2847
+ const combinedContent = manager.combineStandards(standards);
2848
+ return {
2849
+ content: [{
2850
+ type: "text",
2851
+ text: JSON.stringify({
2852
+ success: true,
2853
+ preset: {
2854
+ id: args.preset,
2855
+ name: preset.name,
2856
+ description: preset.description
2857
+ },
2858
+ applied: {
2859
+ fileType: preset.fileType,
2860
+ imports,
2861
+ scenario: preset.scenario
2862
+ },
2863
+ standards,
2864
+ content: combinedContent,
2865
+ stats: {
2866
+ standardsCount: standards.length,
2867
+ contentLength: combinedContent.length,
2868
+ estimatedTokens: Math.ceil(combinedContent.length / 4)
2869
+ }
2870
+ }, null, 2)
2871
+ }]
2872
+ };
2873
+ } catch (error) {
2874
+ logger3.error(`\u4F7F\u7528\u9884\u8BBE\u5931\u8D25: ${error}`);
2875
+ return {
2876
+ content: [{
2877
+ type: "text",
2878
+ text: JSON.stringify({
2879
+ error: error instanceof Error ? error.message : String(error)
2880
+ }, null, 2)
2881
+ }]
2882
+ };
2883
+ }
2884
+ }
2885
+ async function listPresets() {
2886
+ const presetList = Object.entries(PRESETS).map(([id, preset]) => ({
2887
+ id,
2888
+ name: preset.name,
2889
+ description: preset.description,
2890
+ fileType: preset.fileType,
2891
+ imports: preset.imports,
2892
+ scenario: preset.scenario
2893
+ }));
2894
+ return {
2895
+ content: [{
2896
+ type: "text",
2897
+ text: JSON.stringify({
2898
+ success: true,
2899
+ total: presetList.length,
2900
+ presets: presetList,
2901
+ usage: "\u4F7F\u7528\u65B9\u5F0F: \u8C03\u7528 use_preset \u5DE5\u5177\u5E76\u6307\u5B9A preset \u53C2\u6570"
2902
+ }, null, 2)
2903
+ }]
2904
+ };
2905
+ }
2906
+
2907
+ // src/tools/healthCheck.ts
2908
+ var fs9 = __toESM(require("fs"), 1);
2909
+ var path8 = __toESM(require("path"), 1);
2910
+ var import_url3 = require("url");
2911
+ var __filename4 = (0, import_url3.fileURLToPath)(importMetaUrl);
2912
+ var __dirname4 = path8.dirname(__filename4);
2913
+ async function healthCheck(args) {
2914
+ var _a, _b, _c, _d, _e, _f, _g;
2915
+ const logger3 = new ConsoleLogger();
2916
+ const verbose = (_a = args.verbose) != null ? _a : false;
2917
+ try {
2918
+ const checks = {
2919
+ server: { status: "unknown", details: [] },
2920
+ configuration: { status: "unknown", details: [] },
2921
+ dependencies: { status: "unknown", details: [] },
2922
+ standards: { status: "unknown", details: [] },
2923
+ workspace: { status: "unknown", details: [] }
2924
+ };
2925
+ logger3.log("\u{1F50D} \u68C0\u67E5\u670D\u52A1\u5668\u72B6\u6001...");
2926
+ try {
2927
+ checks.server.status = "healthy";
2928
+ checks.server.details.push("\u2705 MCP \u670D\u52A1\u5668\u6B63\u5728\u8FD0\u884C");
2929
+ checks.server.details.push(`\u{1F4CD} \u8FDB\u7A0B PID: ${process.pid}`);
2930
+ checks.server.details.push(`\u{1F550} \u8FD0\u884C\u65F6\u95F4: ${Math.floor(process.uptime())}\u79D2`);
2931
+ } catch {
2932
+ checks.server.status = "error";
2933
+ checks.server.details.push("\u274C \u670D\u52A1\u5668\u672A\u54CD\u5E94");
2934
+ }
2935
+ logger3.log("\u{1F50D} \u68C0\u67E5\u914D\u7F6E\u6587\u4EF6...");
2936
+ const workspacePath = args.workspacePath || process.cwd();
2937
+ const vscodeDir = path8.join(workspacePath, ".vscode");
2938
+ if (fs9.existsSync(vscodeDir)) {
2939
+ checks.workspace.status = "healthy";
2940
+ checks.workspace.details.push(`\u2705 \u5DE5\u4F5C\u533A\u8DEF\u5F84: ${workspacePath}`);
2941
+ const mcpJsonPath = path8.join(vscodeDir, "mcp.json");
2942
+ if (fs9.existsSync(mcpJsonPath)) {
2943
+ try {
2944
+ const config = JSON.parse(fs9.readFileSync(mcpJsonPath, "utf-8"));
2945
+ const hasNewFormat = (_b = config.servers) == null ? void 0 : _b["copilot-prompts"];
2946
+ const hasOldFormat = (_c = config.mcpServers) == null ? void 0 : _c["copilot-prompts"];
2947
+ if (hasNewFormat) {
2948
+ checks.configuration.status = "healthy";
2949
+ checks.configuration.details.push("\u2705 mcp.json \u914D\u7F6E\u6B63\u786E (\u4F7F\u7528\u65B0\u683C\u5F0F)");
2950
+ const serverConfig = config.servers["copilot-prompts"];
2951
+ if (verbose) {
2952
+ checks.configuration.details.push(` Command: ${serverConfig.command}`);
2953
+ checks.configuration.details.push(` Args: ${(_d = serverConfig.args) == null ? void 0 : _d.join(" ")}`);
2954
+ checks.configuration.details.push(` AutoStart: ${(_e = serverConfig.autoStart) != null ? _e : "undefined"}`);
2955
+ checks.configuration.details.push(` Env: ${JSON.stringify((_f = serverConfig.env) != null ? _f : {})}`);
2956
+ }
2957
+ if (!serverConfig.env) {
2958
+ checks.configuration.details.push('\u{1F4A1} \u5EFA\u8BAE: \u6DFB\u52A0 "env": {} \u5B57\u6BB5');
2959
+ }
2960
+ if (!serverConfig.autoStart) {
2961
+ checks.configuration.details.push('\u{1F4A1} \u5EFA\u8BAE: \u6DFB\u52A0 "autoStart": true \u5B57\u6BB5');
2962
+ }
2963
+ } else if (hasOldFormat) {
2964
+ checks.configuration.status = "warning";
2965
+ checks.configuration.details.push("\u26A0\uFE0F mcp.json \u4F7F\u7528\u65E7\u683C\u5F0F (mcpServers)");
2966
+ checks.configuration.details.push("\u{1F4A1} \u5EFA\u8BAE: \u8FD0\u884C auto_setup \u5DE5\u5177\u5347\u7EA7\u5230\u65B0\u683C\u5F0F (servers)");
2967
+ if (verbose) {
2968
+ const serverConfig = config.mcpServers["copilot-prompts"];
2969
+ checks.configuration.details.push(` Command: ${serverConfig.command}`);
2970
+ checks.configuration.details.push(` Args: ${(_g = serverConfig.args) == null ? void 0 : _g.join(" ")}`);
2971
+ }
2972
+ } else {
2973
+ checks.configuration.status = "warning";
2974
+ checks.configuration.details.push("\u26A0\uFE0F mcp.json \u7F3A\u5C11 copilot-prompts \u914D\u7F6E");
2975
+ checks.configuration.details.push("\u{1F4A1} \u5EFA\u8BAE: \u8FD0\u884C auto_setup \u5DE5\u5177\u6DFB\u52A0\u914D\u7F6E");
2976
+ }
2977
+ } catch (error) {
2978
+ checks.configuration.status = "error";
2979
+ checks.configuration.details.push(`\u274C mcp.json \u683C\u5F0F\u9519\u8BEF: ${error}`);
2980
+ checks.configuration.details.push("\u{1F4A1} \u4FEE\u590D: \u8FD0\u884C auto_setup \u5DE5\u5177\u91CD\u65B0\u751F\u6210\u914D\u7F6E");
2981
+ }
2982
+ } else {
2983
+ checks.configuration.status = "warning";
2984
+ checks.configuration.details.push("\u26A0\uFE0F mcp.json \u4E0D\u5B58\u5728");
2985
+ checks.configuration.details.push("\u{1F4A1} \u5EFA\u8BAE: \u8FD0\u884C auto_setup \u5DE5\u5177\u81EA\u52A8\u914D\u7F6E");
2986
+ }
2987
+ const settingsPath = path8.join(vscodeDir, "settings.json");
2988
+ if (fs9.existsSync(settingsPath)) {
2989
+ try {
2990
+ const settings = JSON.parse(fs9.readFileSync(settingsPath, "utf-8"));
2991
+ if (settings["github.copilot.chat.mcp.enabled"] === true) {
2992
+ checks.configuration.details.push("\u2705 VS Code MCP \u5DF2\u542F\u7528");
2993
+ } else {
2994
+ checks.configuration.details.push("\u26A0\uFE0F VS Code MCP \u672A\u542F\u7528");
2995
+ }
2996
+ } catch {
2997
+ checks.configuration.details.push("\u26A0\uFE0F settings.json \u683C\u5F0F\u9519\u8BEF");
2998
+ }
2999
+ }
3000
+ } else {
3001
+ checks.workspace.status = "error";
3002
+ checks.workspace.details.push("\u274C .vscode \u76EE\u5F55\u4E0D\u5B58\u5728");
3003
+ }
3004
+ logger3.log("\u{1F50D} \u68C0\u67E5\u4F9D\u8D56...");
3005
+ const serverRoot = path8.resolve(__dirname4, "../..");
3006
+ const packageJsonPath = path8.join(serverRoot, "package.json");
3007
+ if (fs9.existsSync(packageJsonPath)) {
3008
+ try {
3009
+ const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8"));
3010
+ checks.dependencies.status = "healthy";
3011
+ checks.dependencies.details.push(`\u2705 \u670D\u52A1\u5668\u7248\u672C: ${pkg.version}`);
3012
+ if (verbose && pkg.dependencies) {
3013
+ const deps = Object.entries(pkg.dependencies).slice(0, 3);
3014
+ deps.forEach(([name, version]) => {
3015
+ checks.dependencies.details.push(` ${name}: ${version}`);
3016
+ });
3017
+ }
3018
+ const requiredDeps = ["@modelcontextprotocol/sdk"];
3019
+ const missing = requiredDeps.filter((dep) => {
3020
+ var _a2;
3021
+ return !((_a2 = pkg.dependencies) == null ? void 0 : _a2[dep]);
3022
+ });
3023
+ if (missing.length > 0) {
3024
+ checks.dependencies.status = "error";
3025
+ checks.dependencies.details.push(`\u274C \u7F3A\u5C11\u4F9D\u8D56: ${missing.join(", ")}`);
3026
+ }
3027
+ } catch {
3028
+ checks.dependencies.status = "error";
3029
+ checks.dependencies.details.push("\u274C \u65E0\u6CD5\u8BFB\u53D6 package.json");
3030
+ }
3031
+ }
3032
+ logger3.log("\u{1F50D} \u68C0\u67E5\u89C4\u8303\u6587\u4EF6...");
3033
+ const standardsDir = path8.join(serverRoot, "standards");
3034
+ if (fs9.existsSync(standardsDir)) {
3035
+ const categories = ["core", "frameworks", "libraries", "patterns"];
3036
+ const foundStandards = [];
3037
+ for (const category of categories) {
3038
+ const categoryPath = path8.join(standardsDir, category);
3039
+ if (fs9.existsSync(categoryPath)) {
3040
+ const files = fs9.readdirSync(categoryPath).filter((f) => f.endsWith(".md"));
3041
+ foundStandards.push(...files.map((f) => `${category}/${f}`));
3042
+ }
3043
+ }
3044
+ if (foundStandards.length > 0) {
3045
+ checks.standards.status = "healthy";
3046
+ checks.standards.details.push(`\u2705 \u627E\u5230 ${foundStandards.length} \u4E2A\u89C4\u8303\u6587\u4EF6`);
3047
+ if (verbose) {
3048
+ foundStandards.slice(0, 5).forEach((s) => {
3049
+ checks.standards.details.push(` \u{1F4C4} ${s}`);
3050
+ });
3051
+ if (foundStandards.length > 5) {
3052
+ checks.standards.details.push(` ... \u8FD8\u6709 ${foundStandards.length - 5} \u4E2A\u6587\u4EF6`);
3053
+ }
3054
+ }
3055
+ } else {
3056
+ checks.standards.status = "warning";
3057
+ checks.standards.details.push("\u26A0\uFE0F \u672A\u627E\u5230\u89C4\u8303\u6587\u4EF6");
3058
+ }
3059
+ } else {
3060
+ checks.standards.status = "error";
3061
+ checks.standards.details.push("\u274C standards \u76EE\u5F55\u4E0D\u5B58\u5728");
3062
+ }
3063
+ const allStatuses = Object.values(checks).map((c) => c.status);
3064
+ const overallStatus = allStatuses.includes("error") ? "error" : allStatuses.includes("warning") ? "warning" : "healthy";
3065
+ const statusEmoji = {
3066
+ healthy: "\u2705",
3067
+ warning: "\u26A0\uFE0F",
3068
+ error: "\u274C",
3069
+ unknown: "\u2753"
3070
+ };
3071
+ logger3.log(`${statusEmoji[overallStatus]} \u5065\u5EB7\u68C0\u67E5\u5B8C\u6210`);
3072
+ return {
3073
+ content: [{
3074
+ type: "text",
3075
+ text: JSON.stringify({
3076
+ success: true,
3077
+ overallStatus,
3078
+ summary: `${statusEmoji[overallStatus]} MCP \u670D\u52A1\u5668\u72B6\u6001: ${overallStatus}`,
3079
+ checks,
3080
+ recommendations: generateRecommendations(checks)
3081
+ }, null, 2)
3082
+ }]
3083
+ };
3084
+ } catch (error) {
3085
+ logger3.error(`\u5065\u5EB7\u68C0\u67E5\u5931\u8D25: ${error}`);
3086
+ return {
3087
+ content: [{
3088
+ type: "text",
3089
+ text: JSON.stringify({
3090
+ error: error instanceof Error ? error.message : String(error)
3091
+ }, null, 2)
3092
+ }]
3093
+ };
3094
+ }
3095
+ }
3096
+ function generateRecommendations(checks) {
3097
+ const recommendations = [];
3098
+ if (checks.configuration.status !== "healthy") {
3099
+ recommendations.push("\u{1F527} \u8FD0\u884C auto_setup \u5DE5\u5177\u81EA\u52A8\u914D\u7F6E MCP \u670D\u52A1\u5668");
3100
+ }
3101
+ if (checks.workspace.status === "error") {
3102
+ recommendations.push("\u{1F4C1} \u786E\u4FDD\u5728\u6B63\u786E\u7684\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E2D\u8FD0\u884C");
3103
+ }
3104
+ if (checks.dependencies.status === "error") {
3105
+ recommendations.push("\u{1F4E6} \u8FD0\u884C npm install \u5B89\u88C5\u4F9D\u8D56");
3106
+ }
3107
+ if (checks.standards.status !== "healthy") {
3108
+ recommendations.push("\u{1F4DA} \u68C0\u67E5 standards \u76EE\u5F55\u662F\u5426\u5B58\u5728\u89C4\u8303\u6587\u4EF6");
3109
+ }
3110
+ if (recommendations.length === 0) {
3111
+ recommendations.push("\u{1F389} \u4E00\u5207\u6B63\u5E38\uFF01\u60A8\u53EF\u4EE5\u5F00\u59CB\u4F7F\u7528 MCP \u670D\u52A1\u5668\u4E86");
3112
+ }
3113
+ return recommendations;
3114
+ }
3115
+
3116
+ // src/tools/getCompactStandards.ts
3117
+ var fs10 = __toESM(require("fs"), 1);
3118
+ async function getCompactStandards(args) {
3119
+ const logger3 = new ConsoleLogger();
3120
+ const manager = new StandardsManager();
3121
+ const mode = args.mode || "key-rules";
3122
+ try {
3123
+ const context = detectContext(args, logger3);
3124
+ const standardUris = manager.getRelevantStandards({
3125
+ fileType: context.fileType,
3126
+ imports: context.imports,
3127
+ scenario: args.scenario || context.scenario
3128
+ });
3129
+ let responseContent;
3130
+ switch (mode) {
3131
+ case "summary":
3132
+ responseContent = buildSummaryResponse(standardUris, manager);
3133
+ break;
3134
+ case "key-rules":
3135
+ responseContent = buildKeyRulesResponse(standardUris, context, manager);
3136
+ break;
3137
+ case "full":
3138
+ responseContent = buildFullResponse(standardUris, manager);
3139
+ break;
3140
+ }
3141
+ return {
3142
+ content: [{
3143
+ type: "text",
3144
+ text: JSON.stringify(responseContent, null, 2)
3145
+ }]
3146
+ };
3147
+ } catch (error) {
3148
+ logger3.error(`\u89C4\u8303\u83B7\u53D6\u5931\u8D25: ${error}`);
3149
+ return {
3150
+ content: [{
3151
+ type: "text",
3152
+ text: JSON.stringify({
3153
+ error: error instanceof Error ? error.message : String(error)
3154
+ }, null, 2)
3155
+ }]
3156
+ };
3157
+ }
3158
+ }
3159
+ function detectContext(args, logger3) {
3160
+ var _a;
3161
+ let fileType = "unknown";
3162
+ let imports = [];
3163
+ let scenario = "";
3164
+ if (args.currentFile && fs10.existsSync(args.currentFile)) {
3165
+ const ext = ((_a = args.currentFile.split(".").pop()) == null ? void 0 : _a.toLowerCase()) || "";
3166
+ const extMap = {
3167
+ "vue": "vue",
3168
+ "ts": "ts",
3169
+ "tsx": "tsx",
3170
+ "js": "js",
3171
+ "jsx": "jsx",
3172
+ "dart": "dart"
3173
+ };
3174
+ fileType = extMap[ext] || "unknown";
3175
+ try {
3176
+ const content = fs10.readFileSync(args.currentFile, "utf-8");
3177
+ imports = extractImports2(content);
3178
+ scenario = inferScenario2(content, fileType);
3179
+ } catch {
3180
+ }
3181
+ }
3182
+ if (args.fileContent) {
3183
+ imports = [...imports, ...extractImports2(args.fileContent)];
3184
+ if (fileType === "unknown") {
3185
+ if (args.fileContent.includes("<template>")) fileType = "vue";
3186
+ else if (args.fileContent.includes("interface ")) fileType = "ts";
3187
+ }
3188
+ scenario = scenario || inferScenario2(args.fileContent, fileType);
3189
+ }
3190
+ return { fileType, imports: [...new Set(imports)], scenario };
3191
+ }
3192
+ function buildSummaryResponse(uris, manager) {
3193
+ const standards = manager.getAvailableStandards();
3194
+ const matched = uris.map((uri) => {
3195
+ const std = standards.find((s) => s.uri === uri);
3196
+ return {
3197
+ uri,
3198
+ name: (std == null ? void 0 : std.name) || uri,
3199
+ description: (std == null ? void 0 : std.description) || ""
3200
+ };
3201
+ });
3202
+ return {
3203
+ success: true,
3204
+ mode: "summary",
3205
+ message: '\u5DF2\u8BC6\u522B\u76F8\u5173\u89C4\u8303\uFF0C\u5982\u9700\u8BE6\u7EC6\u5185\u5BB9\u8BF7\u4F7F\u7528 mode: "key-rules" \u6216 "full"',
3206
+ standards: matched,
3207
+ stats: {
3208
+ count: matched.length,
3209
+ estimatedTokens: 500
3210
+ }
3211
+ };
3212
+ }
3213
+ function buildKeyRulesResponse(uris, context, manager) {
3214
+ const keyRules = [];
3215
+ if (context.fileType === "vue") {
3216
+ keyRules.push(...getVueKeyRules(context.imports));
3217
+ } else if (context.fileType === "dart") {
3218
+ keyRules.push(...getFlutterKeyRules());
3219
+ } else if (context.fileType === "ts" || context.fileType === "tsx") {
3220
+ keyRules.push(...getTypeScriptKeyRules());
3221
+ }
3222
+ if (context.imports.includes("element-plus")) {
3223
+ keyRules.push(...getElementPlusKeyRules());
3224
+ }
3225
+ if (context.imports.some((i) => i.includes("i18n") || i.includes("locale"))) {
3226
+ keyRules.push(...getI18nKeyRules());
3227
+ }
3228
+ if (context.imports.includes("pinia")) {
3229
+ keyRules.push(...getPiniaKeyRules());
3230
+ }
3231
+ return {
3232
+ success: true,
3233
+ mode: "key-rules",
3234
+ context: {
3235
+ fileType: context.fileType,
3236
+ detectedImports: context.imports,
3237
+ scenario: context.scenario
3238
+ },
3239
+ keyRules: keyRules.join("\n\n"),
3240
+ standardUris: uris,
3241
+ // 提供完整 URI 供按需加载
3242
+ stats: {
3243
+ rulesCount: keyRules.length,
3244
+ estimatedTokens: Math.ceil(keyRules.join("").length / 4)
3245
+ }
3246
+ };
3247
+ }
3248
+ function buildFullResponse(uris, manager) {
3249
+ const content = manager.combineStandards(uris);
3250
+ return {
3251
+ success: true,
3252
+ mode: "full",
3253
+ standards: uris,
3254
+ content,
3255
+ stats: {
3256
+ standardsCount: uris.length,
3257
+ contentLength: content.length,
3258
+ estimatedTokens: Math.ceil(content.length / 4)
3259
+ }
3260
+ };
3261
+ }
3262
+ function getVueKeyRules(imports) {
3263
+ return [
3264
+ `## Vue 3 \u5173\u952E\u89C4\u5219
3265
+
3266
+ 1. **\u4F7F\u7528 \`<script setup lang="ts">\`** - \u5FC5\u987B\u4F7F\u7528 Composition API
3267
+ 2. **Props/Emits \u7C7B\u578B\u5B9A\u4E49** - \u5FC5\u987B\u4F7F\u7528 interface \u5B9A\u4E49\u7C7B\u578B
3268
+ 3. **\u7981\u6B62\u5185\u8054\u6837\u5F0F** - \u4F7F\u7528 scoped CSS \u6216 class
3269
+ 4. **\u6A21\u677F\u7B80\u6D01** - \u590D\u6742\u903B\u8F91\u63D0\u53D6\u5230 computed \u6216\u65B9\u6CD5
3270
+ 5. **\u54CD\u5E94\u5F0F** - \u57FA\u672C\u7C7B\u578B\u7528 ref\uFF0C\u5BF9\u8C61\u7528 reactive\uFF08\u4E0D\u91CD\u65B0\u8D4B\u503C\uFF09`,
3271
+ `## \u7EC4\u4EF6\u7ED3\u6784\u987A\u5E8F
3272
+ \`\`\`vue
3273
+ <script setup lang="ts">
3274
+ // 1. \u7C7B\u578B\u5BFC\u5165
3275
+ // 2. Props/Emits \u5B9A\u4E49
3276
+ // 3. \u54CD\u5E94\u5F0F\u72B6\u6001
3277
+ // 4. \u8BA1\u7B97\u5C5E\u6027
3278
+ // 5. \u65B9\u6CD5
3279
+ // 6. \u751F\u547D\u5468\u671F
3280
+ </script>
3281
+ \`\`\``
3282
+ ];
3283
+ }
3284
+ function getElementPlusKeyRules() {
3285
+ return [
3286
+ `## Element Plus \u5173\u952E\u89C4\u5219
3287
+
3288
+ ### \u8868\u683C\u89C4\u8303
3289
+ - **\u5FC5\u987B** \`border\` + \`highlight-current-row\`
3290
+ - \u64CD\u4F5C\u5217 \`fixed="right"\`\uFF0C\u5BBD\u5EA6\uFF1A2\u6309\u94AE160px/3\u6309\u94AE240px/4\u6309\u94AE280px
3291
+ - \u4F7F\u7528 \`v-loading\` \u663E\u793A\u52A0\u8F7D\u72B6\u6001
3292
+
3293
+ ### \u8868\u5355\u89C4\u8303
3294
+ - \u4F7F\u7528 \`label-position="top"\` \u6216 \`label-width="120px"\`
3295
+ - \u9A8C\u8BC1\u89C4\u5219\u4F7F\u7528 \`FormRules<T>\` \u7C7B\u578B
3296
+ - \u9A8C\u8BC1\u6D88\u606F\u5FC5\u987B\u56FD\u9645\u5316
3297
+
3298
+ ### \u5F39\u7A97\u89C4\u8303
3299
+ - \u4F7F\u7528 \`destroy-on-close\` \u91CD\u7F6E\u72B6\u6001
3300
+ - \u5BBD\u5EA6\uFF1A\u7B80\u5355500px/\u6807\u51C6700px/\u590D\u6742900px
3301
+
3302
+ ### \u6D88\u606F\u63D0\u793A
3303
+ \`\`\`typescript
3304
+ ElMessage.success($t('\u4FDD\u5B58\u6210\u529F'))
3305
+ ElMessageBox.confirm($t('\u786E\u8BA4\u5220\u9664\uFF1F'), $t('\u8B66\u544A'), { type: 'warning' })
3306
+ \`\`\``,
3307
+ `## \u8868\u683C\u793A\u4F8B
3308
+ \`\`\`vue
3309
+ <el-table v-loading="listLoading" :data="list" border highlight-current-row>
3310
+ <el-table-column type="index" :label="$t('\u5E8F\u53F7')" width="70" />
3311
+ <el-table-column prop="name" :label="$t('\u540D\u79F0')" min-width="120" />
3312
+ <el-table-column fixed="right" :label="$t('\u64CD\u4F5C')" width="240">
3313
+ <template #default="{ row }">
3314
+ <el-button link type="primary" @click="handleEdit(row)">{{ $t('\u7F16\u8F91') }}</el-button>
3315
+ <el-button link type="danger" @click="handleDelete(row)">{{ $t('\u5220\u9664') }}</el-button>
3316
+ </template>
3317
+ </el-table-column>
3318
+ </el-table>
3319
+ \`\`\``
3320
+ ];
3321
+ }
3322
+ function getI18nKeyRules() {
3323
+ return [
3324
+ `## \u56FD\u9645\u5316\u5173\u952E\u89C4\u5219
3325
+
3326
+ ### \u5FC5\u987B\u56FD\u9645\u5316\u7684\u5185\u5BB9
3327
+ - \u6240\u6709\u6309\u94AE\u6587\u5B57\uFF1A\`{{ $t('\u4FDD\u5B58') }}\`
3328
+ - \u8868\u5355\u6807\u7B7E\uFF1A\`:label="$t('\u5BA2\u6237\u540D\u79F0')"\`
3329
+ - \u5360\u4F4D\u7B26\uFF1A\`:placeholder="$t('\u8BF7\u8F93\u5165')"\`
3330
+ - \u8868\u683C\u5217\u6807\u9898\uFF1A\`:label="$t('\u8BA2\u5355\u7F16\u53F7')"\`
3331
+ - \u5F39\u7A97\u6807\u9898\uFF1A\`:title="$t('\u65B0\u589E\u5BA2\u6237')"\`
3332
+ - \u63D0\u793A\u6D88\u606F\uFF1A\`ElMessage.success($t('\u4FDD\u5B58\u6210\u529F'))\`
3333
+ - \u9A8C\u8BC1\u89C4\u5219\uFF1A\`message: $t('\u8BF7\u8F93\u5165\u7528\u6237\u540D')\`
3334
+
3335
+ ### \u7981\u6B62
3336
+ - \u274C \`<el-button>\u65B0\u589E</el-button>\` (\u786C\u7F16\u7801)
3337
+ - \u274C \`label="\u5BA2\u6237\u540D\u79F0"\` (\u786C\u7F16\u7801)
3338
+ - \u274C \`ElMessage.success('\u4FDD\u5B58\u6210\u529F')\` (\u786C\u7F16\u7801)`
3339
+ ];
3340
+ }
3341
+ function getPiniaKeyRules() {
3342
+ return [
3343
+ `## Pinia \u5173\u952E\u89C4\u5219
3344
+
3345
+ ### Setup Store \u8BED\u6CD5\uFF08\u63A8\u8350\uFF09
3346
+ \`\`\`typescript
3347
+ export const useUserStore = defineStore('user', () => {
3348
+ const user = ref<User | null>(null)
3349
+ const isLoggedIn = computed(() => !!user.value)
3350
+
3351
+ async function login(credentials: Credentials) {
3352
+ user.value = await authApi.login(credentials)
3353
+ }
3354
+
3355
+ return { user, isLoggedIn, login }
3356
+ })
3357
+ \`\`\`
3358
+
3359
+ ### \u89C4\u8303\u8981\u6C42
3360
+ - Store ID \u4F7F\u7528\u5C0F\u5199\u77ED\u6A2A\u7EBF\u547D\u540D
3361
+ - \u4F7F\u7528 Setup Store \u8BED\u6CD5\u800C\u975E Options Store
3362
+ - \u5F02\u6B65\u64CD\u4F5C\u76F4\u63A5\u7528 async/await
3363
+ - \u590D\u6742\u72B6\u6001\u64CD\u4F5C\u4F7F\u7528 $patch`
3364
+ ];
3365
+ }
3366
+ function getTypeScriptKeyRules() {
3367
+ return [
3368
+ `## TypeScript \u5173\u952E\u89C4\u5219
3369
+
3370
+ ### \u7C7B\u578B\u5B9A\u4E49
3371
+ - \u5FC5\u987B\u5B9A\u4E49\u51FD\u6570\u53C2\u6570\u548C\u8FD4\u56DE\u7C7B\u578B
3372
+ - \u4F7F\u7528 interface \u5B9A\u4E49\u5BF9\u8C61\u7C7B\u578B
3373
+ - \u907F\u514D\u4F7F\u7528 any\uFF0C\u4F7F\u7528 unknown \u66FF\u4EE3
3374
+
3375
+ ### \u547D\u540D\u89C4\u8303
3376
+ - \u53D8\u91CF/\u51FD\u6570\uFF1AcamelCase
3377
+ - \u7C7B/\u63A5\u53E3/\u7C7B\u578B\uFF1APascalCase
3378
+ - \u5E38\u91CF\uFF1AUPPER_SNAKE_CASE
3379
+
3380
+ ### \u793A\u4F8B
3381
+ \`\`\`typescript
3382
+ interface User {
3383
+ id: number
3384
+ name: string
3385
+ email?: string
3386
+ }
3387
+
3388
+ async function fetchUser(id: number): Promise<User | null> {
3389
+ // ...
3390
+ }
3391
+ \`\`\``
3392
+ ];
3393
+ }
3394
+ function getFlutterKeyRules() {
3395
+ return [
3396
+ `## Flutter UI \u7CFB\u7EDF\u5173\u952E\u89C4\u5219
3397
+
3398
+ ### Design Token \u5FEB\u6377\u65B9\u5F0F\uFF08\u5FC5\u987B\u4F7F\u7528\uFF09
3399
+ | \u5FEB\u6377\u65B9\u5F0F | \u7528\u9014 | \u793A\u4F8B |
3400
+ |---------|------|------|
3401
+ | \`$c\` | \u989C\u8272 | \`$c.primary\`, \`$c.text.primary\` |
3402
+ | \`$s\` | \u95F4\u8DDD | \`$s.sm\`, \`$s.md\`, \`$s.px(14)\` |
3403
+ | \`$t\` | \u6392\u7248 | \`$t.displayLarge\`, \`$t.bodyMedium\` |
3404
+ | \`$r\` | \u5706\u89D2 | \`$r.sm\`, \`$r.md\`, \`$r.full\` |
3405
+
3406
+ ### Flex \u7EC4\u4EF6\u5E93\uFF08\u5FC5\u987B\u4F7F\u7528\uFF09
3407
+ - \`FlexButton\` \u66FF\u4EE3 ElevatedButton/TextButton
3408
+ - \`FlexCard\` \u66FF\u4EE3 Card/Container
3409
+ - \`FlexInput\` \u66FF\u4EE3 TextField
3410
+ - \`Gap\` \u66FF\u4EE3 SizedBox\uFF08\u95F4\u9694\uFF09
3411
+
3412
+ ### \u7981\u6B62
3413
+ - \u274C \`Color(0xFF3B82F6)\` \u786C\u7F16\u7801\u989C\u8272
3414
+ - \u274C \`EdgeInsets.all(16)\` \u786C\u7F16\u7801\u95F4\u8DDD
3415
+ - \u274C \`Colors.blue\` Material \u989C\u8272\u5E38\u91CF`
3416
+ ];
3417
+ }
3418
+ function extractImports2(content) {
3419
+ const imports = [];
3420
+ const esImportRegex = /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/g;
3421
+ let match;
3422
+ while ((match = esImportRegex.exec(content)) !== null) {
3423
+ imports.push(match[1]);
3424
+ }
3425
+ const requireRegex = /require\(['"]([^'"]+)['"]\)/g;
3426
+ while ((match = requireRegex.exec(content)) !== null) {
3427
+ imports.push(match[1]);
3428
+ }
3429
+ return imports;
3430
+ }
3431
+ function inferScenario2(content, fileType) {
3432
+ const scenarios = [];
3433
+ const lower = content.toLowerCase();
3434
+ if (lower.includes("el-table") || lower.includes("el-form")) {
3435
+ scenarios.push("\u8868\u683C\u7EC4\u4EF6", "\u8868\u5355\u7EC4\u4EF6");
3436
+ }
3437
+ if (lower.includes("$t(") || lower.includes("i18n")) {
3438
+ scenarios.push("\u56FD\u9645\u5316");
3439
+ }
3440
+ if (lower.includes("interface ") || lower.includes("type ")) {
3441
+ scenarios.push("\u7C7B\u578B\u5B9A\u4E49");
3442
+ }
3443
+ return scenarios.join("\u3001");
3444
+ }
3445
+
3446
+ // src/tools/getStandardById.ts
3447
+ var fs11 = __toESM(require("fs"), 1);
3448
+ var path9 = __toESM(require("path"), 1);
3449
+ var STANDARD_DIRS = [
3450
+ "standards/core",
3451
+ "standards/frameworks",
3452
+ "standards/libraries",
3453
+ "standards/patterns",
3454
+ "standards/workflows"
3455
+ ];
3456
+ var standardsCache = null;
3457
+ async function getStandardById(args) {
3458
+ const logger3 = new ConsoleLogger();
3459
+ const mode = args.mode || "key-rules";
3460
+ try {
3461
+ const idsToLoad = args.ids || (args.id ? [args.id] : []);
3462
+ if (idsToLoad.length === 0) {
3463
+ return {
3464
+ content: [{
3465
+ type: "text",
3466
+ text: JSON.stringify({
3467
+ error: "\u8BF7\u63D0\u4F9B id \u6216 ids \u53C2\u6570",
3468
+ availableIds: listAvailableStandards()
3469
+ }, null, 2)
3470
+ }]
3471
+ };
3472
+ }
3473
+ ensureCache();
3474
+ const results = [];
3475
+ for (const id of idsToLoad) {
3476
+ const filePath = standardsCache.get(id);
3477
+ if (!filePath) {
3478
+ results.push({
3479
+ id,
3480
+ found: false,
3481
+ error: `\u89C4\u8303 "${id}" \u4E0D\u5B58\u5728`
3482
+ });
3483
+ continue;
3484
+ }
3485
+ try {
3486
+ const fullContent = fs11.readFileSync(filePath, "utf-8");
3487
+ const content = formatContent(fullContent, mode);
3488
+ results.push({
3489
+ id,
3490
+ found: true,
3491
+ content
3492
+ });
3493
+ } catch (error) {
3494
+ results.push({
3495
+ id,
3496
+ found: false,
3497
+ error: `\u8BFB\u53D6\u5931\u8D25: ${error}`
3498
+ });
3499
+ }
3500
+ }
3501
+ const successCount = results.filter((r) => r.found).length;
3502
+ const totalLength = results.reduce((sum, r) => {
3503
+ var _a;
3504
+ return sum + (((_a = r.content) == null ? void 0 : _a.length) || 0);
3505
+ }, 0);
3506
+ return {
3507
+ content: [{
3508
+ type: "text",
3509
+ text: JSON.stringify({
3510
+ success: true,
3511
+ mode,
3512
+ stats: {
3513
+ requested: idsToLoad.length,
3514
+ found: successCount,
3515
+ totalChars: totalLength,
3516
+ estimatedTokens: Math.ceil(totalLength / 4)
3517
+ },
3518
+ standards: results
3519
+ }, null, 2)
3520
+ }]
3521
+ };
3522
+ } catch (error) {
3523
+ logger3.error(`\u83B7\u53D6\u89C4\u8303\u5931\u8D25: ${error}`);
3524
+ return {
3525
+ content: [{
3526
+ type: "text",
3527
+ text: JSON.stringify({
3528
+ error: error instanceof Error ? error.message : String(error)
3529
+ }, null, 2)
3530
+ }]
3531
+ };
3532
+ }
3533
+ }
3534
+ function listAvailableStandards() {
3535
+ ensureCache();
3536
+ return Array.from(standardsCache.keys());
3537
+ }
3538
+ function ensureCache() {
3539
+ if (standardsCache) return;
3540
+ standardsCache = /* @__PURE__ */ new Map();
3541
+ const baseDir = findBaseDir();
3542
+ for (const dir of STANDARD_DIRS) {
3543
+ const fullDir = path9.join(baseDir, dir);
3544
+ if (!fs11.existsSync(fullDir)) continue;
3545
+ scanDirectory(fullDir, standardsCache);
3546
+ }
3547
+ }
3548
+ function findBaseDir() {
3549
+ const possiblePaths = [
3550
+ process.cwd(),
3551
+ path9.join(process.cwd(), ".."),
3552
+ path9.join(__dirname, "..", "..", "..")
3553
+ ];
3554
+ for (const p of possiblePaths) {
3555
+ if (fs11.existsSync(path9.join(p, "standards"))) {
3556
+ return p;
3557
+ }
3558
+ }
3559
+ return process.cwd();
3560
+ }
3561
+ function scanDirectory(dir, cache) {
3562
+ const items = fs11.readdirSync(dir);
3563
+ for (const item of items) {
3564
+ const fullPath = path9.join(dir, item);
3565
+ const stat = fs11.statSync(fullPath);
3566
+ if (stat.isDirectory()) {
3567
+ scanDirectory(fullPath, cache);
3568
+ } else if (item.endsWith(".md")) {
3569
+ const id = path9.basename(item, ".md");
3570
+ cache.set(id, fullPath);
3571
+ }
3572
+ }
3573
+ }
3574
+ function formatContent(content, mode) {
3575
+ switch (mode) {
3576
+ case "summary":
3577
+ return extractSummary(content);
3578
+ case "key-rules":
3579
+ return extractKeyRules(content);
3580
+ case "full":
3581
+ return content;
3582
+ default:
3583
+ return content;
3584
+ }
3585
+ }
3586
+ function extractSummary(content) {
3587
+ const lines = content.split("\n");
3588
+ const summaryLines = [];
3589
+ const titleMatch = content.match(/^#\s+(.+)$/m);
3590
+ if (titleMatch) {
3591
+ summaryLines.push(`# ${titleMatch[1]}`);
3592
+ }
3593
+ let foundDescription = false;
3594
+ for (const line of lines) {
3595
+ if (line.startsWith("#") || line.trim() === "") continue;
3596
+ if (line.startsWith(">")) {
3597
+ summaryLines.push(line);
3598
+ foundDescription = true;
3599
+ break;
3600
+ }
3601
+ if (line.startsWith("-") || line.startsWith("*")) continue;
3602
+ summaryLines.push(line);
3603
+ foundDescription = true;
3604
+ break;
3605
+ }
3606
+ const sectionHeaders = lines.filter((l) => l.match(/^##\s+/)).slice(0, 5);
3607
+ if (sectionHeaders.length > 0) {
3608
+ summaryLines.push("\n**\u4E3B\u8981\u7AE0\u8282**:");
3609
+ summaryLines.push(...sectionHeaders.map((h) => `- ${h.replace(/^##\s+/, "")}`));
3610
+ }
3611
+ return summaryLines.join("\n");
3612
+ }
3613
+ function extractKeyRules(content) {
3614
+ const lines = content.split("\n");
3615
+ const keyRulesLines = [];
3616
+ const titleMatch = content.match(/^#\s+(.+)$/m);
3617
+ if (titleMatch) {
3618
+ keyRulesLines.push(`# ${titleMatch[1]}`);
3619
+ }
3620
+ const keyPatterns = [
3621
+ /强制|必须|禁止|规则|核心|关键|重要/,
3622
+ /MUST|REQUIRED|SHOULD|必选|核心原则/,
3623
+ /✅|❌|⚠️/
3624
+ ];
3625
+ let inKeySection = false;
3626
+ let sectionDepth = 0;
3627
+ let lineCount = 0;
3628
+ const maxLines = 80;
3629
+ for (const line of lines) {
3630
+ const headerMatch = line.match(/^(#{2,3})\s+(.+)$/);
3631
+ if (headerMatch) {
3632
+ const depth = headerMatch[1].length;
3633
+ const title = headerMatch[2];
3634
+ inKeySection = keyPatterns.some((p) => p.test(title));
3635
+ sectionDepth = depth;
3636
+ if (inKeySection) {
3637
+ keyRulesLines.push("");
3638
+ keyRulesLines.push(line);
3639
+ lineCount++;
3640
+ }
3641
+ continue;
3642
+ }
3643
+ if (inKeySection && lineCount < maxLines) {
3644
+ if (line.match(/^#{2}\s+/) && sectionDepth >= 2) {
3645
+ inKeySection = false;
3646
+ continue;
3647
+ }
3648
+ keyRulesLines.push(line);
3649
+ lineCount++;
3650
+ }
3651
+ if (!inKeySection && lineCount < maxLines) {
3652
+ if (line.includes("\u2705") || line.includes("\u274C") || line.includes("\u26A0\uFE0F")) {
3653
+ keyRulesLines.push(line);
3654
+ lineCount++;
3655
+ }
3656
+ }
3657
+ }
3658
+ if (keyRulesLines.length < 20) {
3659
+ const codeBlockMatch = content.match(/```[\s\S]{50,500}?```/);
3660
+ if (codeBlockMatch) {
3661
+ keyRulesLines.push("\n**\u793A\u4F8B**:");
3662
+ keyRulesLines.push(codeBlockMatch[0]);
3663
+ }
3664
+ }
3665
+ return keyRulesLines.join("\n").trim() || extractSummary(content);
3666
+ }
3667
+
3668
+ // src/core/mappings/scenarioMappings.ts
3669
+ var SCENARIO_STANDARDS = {
3670
+ // ========== Vue 相关场景 ==========
3671
+ "vue3-component": ["vue3-composition", "typescript-strict"],
3672
+ "vue3-form": ["vue3-composition", "element-plus", "form-validation"],
3673
+ "vue3-table": ["vue3-composition", "element-plus", "pagination"],
3674
+ "pinia-store": ["pinia-store", "typescript-strict"],
3675
+ "composable": ["vue3-composition", "composable-patterns"],
3676
+ // ========== API 相关 ==========
3677
+ "api-call": ["axios-interceptor", "error-handling", "typescript-strict"],
3678
+ "api-design": ["api-design", "restful-patterns"],
3679
+ // ========== 国际化 ==========
3680
+ "i18n": ["i18n", "vue-i18n"],
3681
+ // ========== 测试 ==========
3682
+ "unit-test": ["vitest-guide", "testing-patterns"],
3683
+ // ========== 特殊场景 ==========
3684
+ "logicflow": ["logicflow", "vue3-composition"],
3685
+ "permission": ["permission-design", "route-guard"],
3686
+ "performance": ["performance-optimization", "lazy-loading"]
3687
+ };
3688
+ var FILETYPE_STANDARDS = {
3689
+ "vue": ["vue3-composition"],
3690
+ "ts": ["typescript-strict"],
3691
+ "tsx": ["react-hooks", "typescript-strict"],
3692
+ "dart": ["dart-style", "flutter-bloc"]
3693
+ };
3694
+ var IMPORT_STANDARDS = {
3695
+ "vue": ["vue3-composition"],
3696
+ "element-plus": ["element-plus"],
3697
+ "pinia": ["pinia-store"],
3698
+ "axios": ["axios-interceptor"],
3699
+ "vue-i18n": ["i18n"],
3700
+ "@logicflow/core": ["logicflow"],
3701
+ "vitest": ["vitest-guide"]
3702
+ };
3703
+ function getStandardsForScenario(scenario) {
3704
+ return SCENARIO_STANDARDS[scenario] || [];
3705
+ }
3706
+ function getStandardsForFileType(fileType) {
3707
+ return FILETYPE_STANDARDS[fileType] || [];
3708
+ }
3709
+ function getStandardsForImport(importName) {
3710
+ const normalizedImport = importName.startsWith("@") ? importName.split("/").slice(0, 2).join("/") : importName.split("/")[0];
3711
+ return IMPORT_STANDARDS[normalizedImport] || [];
3712
+ }
3713
+ function listAvailableScenarios() {
3714
+ return Object.keys(SCENARIO_STANDARDS);
3715
+ }
3716
+ function suggestStandards(options) {
3717
+ const suggestions = [];
3718
+ if (options.scenario) {
3719
+ suggestions.push(...getStandardsForScenario(options.scenario));
3720
+ }
3721
+ if (options.fileType) {
3722
+ suggestions.push(...getStandardsForFileType(options.fileType));
3723
+ }
3724
+ if (options.imports) {
3725
+ for (const imp of options.imports) {
3726
+ suggestions.push(...getStandardsForImport(imp));
3727
+ }
3728
+ }
3729
+ return [...new Set(suggestions)];
3730
+ }
3731
+
3732
+ // src/tools/queryMappings.ts
3733
+ async function queryMappings(args) {
3734
+ const logger3 = new ConsoleLogger();
3735
+ try {
3736
+ if (args.listAll) {
3737
+ return {
3738
+ content: [{
3739
+ type: "text",
3740
+ text: JSON.stringify({
3741
+ success: true,
3742
+ description: "\u573A\u666F-\u89C4\u8303\u6620\u5C04\u8868\uFF0CAI \u53EF\u53C2\u8003\u8FD9\u4E9B\u6620\u5C04\u81EA\u884C\u51B3\u5B9A\u4F7F\u7528\u54EA\u4E9B\u89C4\u8303",
3743
+ mappings: {
3744
+ scenarios: SCENARIO_STANDARDS,
3745
+ fileTypes: FILETYPE_STANDARDS,
3746
+ imports: IMPORT_STANDARDS
3747
+ },
3748
+ availableScenarios: listAvailableScenarios()
3749
+ }, null, 2)
3750
+ }]
3751
+ };
3752
+ }
3753
+ const result = {
3754
+ success: true,
3755
+ query: {},
3756
+ suggestions: []
3757
+ };
3758
+ if (args.scenario) {
3759
+ result.query.scenario = args.scenario;
3760
+ result.scenarioStandards = SCENARIO_STANDARDS[args.scenario] || [];
3761
+ }
3762
+ if (args.fileType) {
3763
+ result.query.fileType = args.fileType;
3764
+ result.fileTypeStandards = FILETYPE_STANDARDS[args.fileType] || [];
3765
+ }
3766
+ if (args.imports && args.imports.length > 0) {
3767
+ result.query.imports = args.imports;
3768
+ result.importStandards = {};
3769
+ for (const imp of args.imports) {
3770
+ const normalizedImport = imp.startsWith("@") ? imp.split("/").slice(0, 2).join("/") : imp.split("/")[0];
3771
+ result.importStandards[imp] = IMPORT_STANDARDS[normalizedImport] || [];
3772
+ }
3773
+ }
3774
+ result.suggestions = suggestStandards({
3775
+ scenario: args.scenario,
3776
+ fileType: args.fileType,
3777
+ imports: args.imports
3778
+ });
3779
+ result.note = "AI \u53EF\u6839\u636E\u5177\u4F53\u60C5\u51B5\u9009\u62E9\u4F7F\u7528\u54EA\u4E9B\u89C4\u8303\uFF0C\u8FD9\u53EA\u662F\u5EFA\u8BAE\u5217\u8868";
3780
+ return {
3781
+ content: [{
3782
+ type: "text",
3783
+ text: JSON.stringify(result, null, 2)
3784
+ }]
3785
+ };
3786
+ } catch (error) {
3787
+ logger3.error(`\u67E5\u8BE2\u6620\u5C04\u5931\u8D25: ${error}`);
3788
+ return {
3789
+ content: [{
3790
+ type: "text",
3791
+ text: JSON.stringify({
3792
+ error: error instanceof Error ? error.message : String(error)
3793
+ }, null, 2)
3794
+ }]
3795
+ };
3796
+ }
3797
+ }
3798
+ async function listScenarios() {
3799
+ return {
3800
+ content: [{
3801
+ type: "text",
3802
+ text: JSON.stringify({
3803
+ success: true,
3804
+ scenarios: listAvailableScenarios(),
3805
+ description: "AI \u53EF\u4F7F\u7528\u8FD9\u4E9B\u573A\u666F\u540D\u79F0\u8C03\u7528 use_preset \u6216 query_mappings"
3806
+ }, null, 2)
3807
+ }]
3808
+ };
3809
+ }
3810
+
3811
+ // src/core/templates/discovery.ts
3812
+ var fs12 = __toESM(require("fs"), 1);
3813
+ var path10 = __toESM(require("path"), 1);
3814
+ var TEMPLATES_DIR = path10.resolve(
3815
+ path10.dirname(new URL(importMetaUrl).pathname),
3816
+ "../../../../templates"
3817
+ );
3818
+ var templatesCache = null;
3819
+ function ensureCache2() {
3820
+ if (templatesCache) return;
3821
+ templatesCache = /* @__PURE__ */ new Map();
3822
+ scanTemplates(TEMPLATES_DIR, "");
3823
+ }
3824
+ function scanTemplates(dir, prefix) {
3825
+ if (!fs12.existsSync(dir)) return;
3826
+ const entries = fs12.readdirSync(dir, { withFileTypes: true });
3827
+ for (const entry of entries) {
3828
+ if (!entry.isDirectory()) continue;
3829
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
3830
+ const fullPath = path10.join(dir, entry.name);
3831
+ const templateId = prefix ? `${prefix}/${entry.name}` : entry.name;
3832
+ const configPath = path10.join(fullPath, "_CONFIG.md");
3833
+ if (fs12.existsSync(configPath)) {
3834
+ const metadata = parseConfigMd(configPath, templateId, fullPath);
3835
+ if (metadata) {
3836
+ templatesCache.set(templateId, metadata);
3837
+ }
3838
+ }
3839
+ scanTemplates(fullPath, templateId);
3840
+ }
3841
+ }
3842
+ function parseConfigMd(configPath, templateId, templateDir) {
3843
+ try {
3844
+ const content = fs12.readFileSync(configPath, "utf-8");
3845
+ const titleMatch = content.match(/^#\s+(.+)$/m);
3846
+ const name = titleMatch ? titleMatch[1].trim() : templateId;
3847
+ const descMatch = content.match(/^>\s*(.+)$/m);
3848
+ const description = descMatch ? descMatch[1].trim() : "";
3849
+ const frameworkMatch = content.match(/\*\*适用框架\*\*:\s*(.+)/i);
3850
+ const frameworks = frameworkMatch ? frameworkMatch[1].split(/[,\/+]/).map((f) => f.trim()) : [];
3851
+ const type = inferTemplateType(templateId, name);
3852
+ const files = getTemplateFiles(templateDir);
3853
+ const dependencies = extractDependencies(content);
3854
+ const pathMatch = content.match(/复制到.*?`([^`]+)`/i);
3855
+ const suggestedPath = pathMatch ? pathMatch[1] : void 0;
3856
+ return {
3857
+ id: templateId,
3858
+ name,
3859
+ description,
3860
+ frameworks,
3861
+ type,
3862
+ files,
3863
+ dependencies,
3864
+ configFile: "_CONFIG.md",
3865
+ suggestedPath,
3866
+ keywords: extractKeywords(name, description, frameworks)
3867
+ };
3868
+ } catch (error) {
3869
+ console.error(`\u89E3\u6790\u6A21\u677F\u914D\u7F6E\u5931\u8D25: ${configPath}`, error);
3870
+ return null;
3871
+ }
3872
+ }
3873
+ function inferTemplateType(templateId, name) {
3874
+ const lower = (templateId + name).toLowerCase();
3875
+ if (lower.includes("api") || lower.includes("request") || lower.includes("axios")) {
3876
+ return "api-layer";
3877
+ }
3878
+ if (lower.includes("component")) return "component";
3879
+ if (lower.includes("store") || lower.includes("pinia")) return "store";
3880
+ if (lower.includes("composable") || lower.includes("hook")) return "composable";
3881
+ if (lower.includes("config")) return "config";
3882
+ if (lower.includes("type")) return "types";
3883
+ return "other";
3884
+ }
3885
+ function getTemplateFiles(dir, prefix = "") {
3886
+ const files = [];
3887
+ const entries = fs12.readdirSync(dir, { withFileTypes: true });
3888
+ for (const entry of entries) {
3889
+ const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
3890
+ if (entry.name === "_CONFIG.md" || entry.name === "_template.json") {
3891
+ continue;
3892
+ }
3893
+ if (entry.isDirectory()) {
3894
+ files.push(...getTemplateFiles(path10.join(dir, entry.name), relativePath));
3895
+ } else {
3896
+ files.push(relativePath);
3897
+ }
3898
+ }
3899
+ return files;
3900
+ }
3901
+ function extractDependencies(content) {
3902
+ const depsMatch = content.match(/"dependencies":\s*\{([^}]+)\}/);
3903
+ if (!depsMatch) return void 0;
3904
+ const deps = {};
3905
+ const pairs = depsMatch[1].matchAll(/"([^"]+)":\s*"([^"]+)"/g);
3906
+ for (const match of pairs) {
3907
+ deps[match[1]] = match[2];
3908
+ }
3909
+ return Object.keys(deps).length > 0 ? deps : void 0;
3910
+ }
3911
+ function extractKeywords(name, description, frameworks) {
3912
+ const text = `${name} ${description}`.toLowerCase();
3913
+ const keywords = new Set(frameworks.map((f) => f.toLowerCase()));
3914
+ const commonKeywords = ["axios", "api", "mock", "request", "http", "fetch", "store", "pinia", "vuex"];
3915
+ for (const kw of commonKeywords) {
3916
+ if (text.includes(kw)) keywords.add(kw);
3917
+ }
3918
+ return Array.from(keywords);
3919
+ }
3920
+ function listAllTemplates() {
3921
+ ensureCache2();
3922
+ const result = [];
3923
+ for (const [id, metadata] of templatesCache) {
3924
+ result.push({
3925
+ id,
3926
+ name: metadata.name,
3927
+ description: metadata.description,
3928
+ frameworks: metadata.frameworks,
3929
+ type: metadata.type,
3930
+ fileCount: metadata.files.length,
3931
+ suggestedPath: metadata.suggestedPath
3932
+ });
3933
+ }
3934
+ return result;
3935
+ }
3936
+ function listTemplatesByType(type) {
3937
+ return listAllTemplates().filter((t) => t.type === type);
3938
+ }
3939
+ function listTemplatesByFramework(framework) {
3940
+ const lower = framework.toLowerCase();
3941
+ return listAllTemplates().filter(
3942
+ (t) => t.frameworks.some((f) => f.toLowerCase().includes(lower))
3943
+ );
3944
+ }
3945
+ function getTemplateById(templateId, includeFiles = false) {
3946
+ ensureCache2();
3947
+ const metadata = templatesCache.get(templateId);
3948
+ if (!metadata) return null;
3949
+ const templateDir = path10.join(TEMPLATES_DIR, templateId);
3950
+ const configPath = path10.join(templateDir, "_CONFIG.md");
3951
+ const configGuide = fs12.existsSync(configPath) ? fs12.readFileSync(configPath, "utf-8") : "";
3952
+ const result = {
3953
+ metadata,
3954
+ configGuide
3955
+ };
3956
+ if (includeFiles) {
3957
+ result.files = [];
3958
+ for (const filePath of metadata.files) {
3959
+ const fullPath = path10.join(templateDir, filePath);
3960
+ if (fs12.existsSync(fullPath)) {
3961
+ result.files.push({
3962
+ path: filePath,
3963
+ content: fs12.readFileSync(fullPath, "utf-8"),
3964
+ isConfig: filePath.startsWith("_")
3965
+ });
3966
+ }
3967
+ }
3968
+ }
3969
+ return result;
3970
+ }
3971
+ function getTemplateDir(templateId) {
3972
+ ensureCache2();
3973
+ if (!templatesCache.has(templateId)) return null;
3974
+ return path10.join(TEMPLATES_DIR, templateId);
3975
+ }
3976
+ function searchTemplates(query) {
3977
+ const lower = query.toLowerCase();
3978
+ return listAllTemplates().filter(
3979
+ (t) => t.id.toLowerCase().includes(lower) || t.name.toLowerCase().includes(lower) || t.description.toLowerCase().includes(lower) || t.frameworks.some((f) => f.toLowerCase().includes(lower))
3980
+ );
3981
+ }
3982
+
3983
+ // src/tools/listTemplates.ts
3984
+ async function listTemplates(args) {
3985
+ const logger3 = new ConsoleLogger();
3986
+ try {
3987
+ let templates;
3988
+ if (args.search) {
3989
+ templates = searchTemplates(args.search);
3990
+ } else if (args.type) {
3991
+ templates = listTemplatesByType(args.type);
3992
+ } else if (args.framework) {
3993
+ templates = listTemplatesByFramework(args.framework);
3994
+ } else {
3995
+ templates = listAllTemplates();
3996
+ }
3997
+ const grouped = {};
3998
+ for (const t of templates) {
3999
+ if (!grouped[t.type]) grouped[t.type] = [];
4000
+ grouped[t.type].push(t);
4001
+ }
4002
+ return {
4003
+ content: [{
4004
+ type: "text",
4005
+ text: JSON.stringify({
4006
+ success: true,
4007
+ total: templates.length,
4008
+ templates,
4009
+ byType: grouped,
4010
+ usage: {
4011
+ getDetails: 'get_template({ id: "\u6A21\u677FID" })',
4012
+ getWithFiles: 'get_template({ id: "\u6A21\u677FID", includeFiles: true })',
4013
+ note: "AI \u53EF\u76F4\u63A5\u8BFB\u53D6\u6A21\u677F\u6587\u4EF6\u5E76\u590D\u5236\u5230\u76EE\u6807\u9879\u76EE"
4014
+ }
4015
+ }, null, 2)
4016
+ }]
4017
+ };
4018
+ } catch (error) {
4019
+ logger3.error(`\u5217\u51FA\u6A21\u677F\u5931\u8D25: ${error}`);
4020
+ return {
4021
+ content: [{
4022
+ type: "text",
4023
+ text: JSON.stringify({
4024
+ error: error instanceof Error ? error.message : String(error)
4025
+ }, null, 2)
4026
+ }]
4027
+ };
4028
+ }
4029
+ }
4030
+
4031
+ // src/tools/getTemplate.ts
4032
+ async function getTemplate(args) {
4033
+ var _a;
4034
+ const logger3 = new ConsoleLogger();
4035
+ try {
4036
+ const result = getTemplateById(args.id, (_a = args.includeFiles) != null ? _a : false);
4037
+ if (!result) {
4038
+ return {
4039
+ content: [{
4040
+ type: "text",
4041
+ text: JSON.stringify({
4042
+ error: `\u6A21\u677F "${args.id}" \u4E0D\u5B58\u5728`,
4043
+ hint: "\u4F7F\u7528 list_templates \u67E5\u770B\u53EF\u7528\u6A21\u677F"
4044
+ }, null, 2)
4045
+ }]
4046
+ };
4047
+ }
4048
+ if (args.files && result.files) {
4049
+ result.files = result.files.filter(
4050
+ (f) => args.files.some(
4051
+ (requested) => f.path === requested || f.path.endsWith(requested)
4052
+ )
4053
+ );
4054
+ }
4055
+ const templateDir = getTemplateDir(args.id);
4056
+ return {
4057
+ content: [{
4058
+ type: "text",
4059
+ text: JSON.stringify({
4060
+ success: true,
4061
+ template: {
4062
+ ...result,
4063
+ absolutePath: templateDir
4064
+ },
4065
+ aiGuidance: {
4066
+ step1: "\u9605\u8BFB configGuide \u4E86\u89E3\u914D\u7F6E\u8981\u6C42",
4067
+ step2: "\u6839\u636E\u76EE\u6807\u9879\u76EE\u60C5\u51B5\u51B3\u5B9A\u5982\u4F55\u4FEE\u6539\u6A21\u677F",
4068
+ step3: "\u5C06\u6587\u4EF6\u590D\u5236\u5230\u76EE\u6807\u9879\u76EE\u5E76\u9002\u914D",
4069
+ note: "\u6A21\u677F\u6587\u4EF6\u53EF\u80FD\u9700\u8981\u6839\u636E\u9879\u76EE\u5B9E\u9645\u60C5\u51B5\u8C03\u6574\uFF08\u5982 UI \u6846\u67B6\u3001\u540E\u7AEF\u54CD\u5E94\u683C\u5F0F\u7B49\uFF09"
4070
+ }
4071
+ }, null, 2)
4072
+ }]
4073
+ };
4074
+ } catch (error) {
4075
+ logger3.error(`\u83B7\u53D6\u6A21\u677F\u5931\u8D25: ${error}`);
4076
+ return {
4077
+ content: [{
4078
+ type: "text",
4079
+ text: JSON.stringify({
4080
+ error: error instanceof Error ? error.message : String(error)
4081
+ }, null, 2)
4082
+ }]
4083
+ };
4084
+ }
4085
+ }
4086
+
4087
+ // src/core/errors.ts
4088
+ var ERROR_MESSAGES = {
4089
+ [1e3 /* UNKNOWN */]: "\u672A\u77E5\u9519\u8BEF",
4090
+ [1001 /* INVALID_PARAMETER */]: "\u53C2\u6570\u65E0\u6548",
4091
+ [1002 /* NOT_FOUND */]: "\u8D44\u6E90\u672A\u627E\u5230",
4092
+ [1003 /* PERMISSION_DENIED */]: "\u6743\u9650\u4E0D\u8DB3",
4093
+ [2001 /* PROJECT_NOT_FOUND */]: "\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728",
4094
+ [2002 /* PROJECT_PARSE_ERROR */]: "\u9879\u76EE\u89E3\u6790\u5931\u8D25",
4095
+ [2003 /* CONFIG_READ_ERROR */]: "\u914D\u7F6E\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25",
4096
+ [3001 /* STANDARD_NOT_FOUND */]: "\u89C4\u8303\u672A\u627E\u5230",
4097
+ [3002 /* STANDARD_LOAD_ERROR */]: "\u89C4\u8303\u52A0\u8F7D\u5931\u8D25",
4098
+ [3003 /* PRESET_NOT_FOUND */]: "\u9884\u8BBE\u672A\u627E\u5230",
4099
+ [4001 /* TEMPLATE_NOT_FOUND */]: "\u6A21\u677F\u672A\u627E\u5230",
4100
+ [4002 /* TEMPLATE_PARSE_ERROR */]: "\u6A21\u677F\u89E3\u6790\u5931\u8D25",
4101
+ [5001 /* AGENT_NOT_FOUND */]: "Agent \u672A\u627E\u5230",
4102
+ [5002 /* AGENT_LOAD_ERROR */]: "Agent \u52A0\u8F7D\u5931\u8D25",
4103
+ [6001 /* CONFIG_GENERATE_ERROR */]: "\u914D\u7F6E\u751F\u6210\u5931\u8D25",
4104
+ [6002 /* FILE_WRITE_ERROR */]: "\u6587\u4EF6\u5199\u5165\u5931\u8D25"
4105
+ };
4106
+ var MCPError = class _MCPError extends Error {
4107
+ constructor(code, message, options) {
4108
+ const defaultMessage = ERROR_MESSAGES[code] || "\u672A\u77E5\u9519\u8BEF";
4109
+ super(message || defaultMessage);
4110
+ this.name = "MCPError";
4111
+ this.code = code;
4112
+ this.cause = options == null ? void 0 : options.cause;
4113
+ this.context = options == null ? void 0 : options.context;
4114
+ Object.setPrototypeOf(this, _MCPError.prototype);
4115
+ }
4116
+ /**
4117
+ * 转换为 JSON 格式(用于 MCP 响应)
4118
+ */
4119
+ toJSON() {
4120
+ return {
4121
+ error: true,
4122
+ code: this.code,
4123
+ message: this.message,
4124
+ ...this.context && { context: this.context }
4125
+ };
4126
+ }
4127
+ /**
4128
+ * 转换为 MCP 响应格式
4129
+ */
4130
+ toResponse() {
4131
+ return {
4132
+ content: [{
4133
+ type: "text",
4134
+ text: JSON.stringify(this.toJSON(), null, 2)
4135
+ }]
4136
+ };
4137
+ }
4138
+ };
4139
+ function errorResponse(error) {
4140
+ if (error instanceof MCPError) {
4141
+ return error.toResponse();
4142
+ }
4143
+ const message = error instanceof Error ? error.message : String(error);
4144
+ return {
4145
+ content: [{
4146
+ type: "text",
4147
+ text: JSON.stringify({
4148
+ error: true,
4149
+ code: 1e3 /* UNKNOWN */,
4150
+ message
4151
+ }, null, 2)
4152
+ }]
4153
+ };
4154
+ }
4155
+
4156
+ // src/core/logger.ts
4157
+ var LOG_LEVEL_NAMES = {
4158
+ [0 /* DEBUG */]: "DEBUG",
4159
+ [1 /* INFO */]: "INFO",
4160
+ [2 /* WARN */]: "WARN",
4161
+ [3 /* ERROR */]: "ERROR",
4162
+ [4 /* SILENT */]: "SILENT"
4163
+ };
4164
+ var globalConfig = {
4165
+ level: process.env.DEBUG ? 0 /* DEBUG */ : 1 /* INFO */,
4166
+ timestamp: false,
4167
+ prefix: "[MCP]"
4168
+ };
4169
+ var Logger = class _Logger {
4170
+ constructor(name, config) {
4171
+ this.name = name || "";
4172
+ this.config = { ...globalConfig, ...config };
4173
+ }
4174
+ /**
4175
+ * 格式化日志消息
4176
+ */
4177
+ format(level, message, ...args) {
4178
+ const parts = [];
4179
+ if (this.config.timestamp) {
4180
+ parts.push((/* @__PURE__ */ new Date()).toISOString());
4181
+ }
4182
+ parts.push(this.config.prefix);
4183
+ if (this.name) {
4184
+ parts.push(`[${this.name}]`);
4185
+ }
4186
+ parts.push(`[${LOG_LEVEL_NAMES[level]}]`);
4187
+ parts.push(message);
4188
+ if (args.length > 0) {
4189
+ const formatted = args.map((arg) => {
4190
+ if (typeof arg === "object") {
4191
+ try {
4192
+ return JSON.stringify(arg, null, 2);
4193
+ } catch {
4194
+ return String(arg);
4195
+ }
4196
+ }
4197
+ return String(arg);
4198
+ });
4199
+ parts.push(...formatted);
4200
+ }
4201
+ return parts.join(" ");
4202
+ }
4203
+ /**
4204
+ * 检查日志级别是否应该输出
4205
+ */
4206
+ shouldLog(level) {
4207
+ return level >= this.config.level;
4208
+ }
4209
+ /**
4210
+ * 调试日志
4211
+ */
4212
+ debug(message, ...args) {
4213
+ if (this.shouldLog(0 /* DEBUG */)) {
4214
+ console.error(this.format(0 /* DEBUG */, message, ...args));
4215
+ }
4216
+ }
4217
+ /**
4218
+ * 信息日志
4219
+ */
4220
+ info(message, ...args) {
4221
+ if (this.shouldLog(1 /* INFO */)) {
4222
+ console.error(this.format(1 /* INFO */, message, ...args));
4223
+ }
4224
+ }
4225
+ /**
4226
+ * 简化的 log 方法(等同于 info)
4227
+ */
4228
+ log(message, ...args) {
4229
+ this.info(message, ...args);
4230
+ }
4231
+ /**
4232
+ * 警告日志
4233
+ */
4234
+ warn(message, ...args) {
4235
+ if (this.shouldLog(2 /* WARN */)) {
4236
+ console.error(this.format(2 /* WARN */, message, ...args));
4237
+ }
4238
+ }
4239
+ /**
4240
+ * 错误日志
4241
+ */
4242
+ error(message, ...args) {
4243
+ if (this.shouldLog(3 /* ERROR */)) {
4244
+ console.error(this.format(3 /* ERROR */, message, ...args));
4245
+ }
4246
+ }
4247
+ /**
4248
+ * 创建子 Logger
4249
+ */
4250
+ child(name) {
4251
+ const childName = this.name ? `${this.name}:${name}` : name;
4252
+ return new _Logger(childName, this.config);
4253
+ }
4254
+ };
4255
+ var logger = new Logger();
4256
+ function createLogger(name) {
4257
+ return new Logger(name);
4258
+ }
4259
+
4260
+ // src/index.ts
4261
+ var SERVER_VERSION = "2.2.0";
4262
+ var logger2 = createLogger("Server");
4263
+ var CopilotPromptsMCPServer = class {
4264
+ constructor() {
4265
+ this.standardsManager = new StandardsManager();
4266
+ this.codeValidator = new CodeValidator();
4267
+ this.server = new import_server.Server(
4268
+ {
4269
+ name: "mta",
4270
+ version: SERVER_VERSION
4271
+ },
4272
+ {
4273
+ capabilities: {
4274
+ tools: {},
4275
+ resources: {}
4276
+ }
4277
+ }
4278
+ );
4279
+ this.setupToolHandlers();
4280
+ this.setupResourceHandlers();
4281
+ this.setupErrorHandlers();
4282
+ }
4283
+ /**
4284
+ * 设置错误处理器
4285
+ */
4286
+ setupErrorHandlers() {
4287
+ this.server.onerror = (error) => {
4288
+ logger2.error("MCP \u670D\u52A1\u5668\u9519\u8BEF", error);
4289
+ };
4290
+ process.on("SIGINT", async () => {
4291
+ logger2.info("\u6536\u5230\u5173\u95ED\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED\u670D\u52A1\u5668...");
4292
+ await this.server.close();
4293
+ process.exit(0);
4294
+ });
4295
+ process.on("SIGTERM", async () => {
4296
+ logger2.info("\u6536\u5230\u7EC8\u6B62\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED\u670D\u52A1\u5668...");
4297
+ await this.server.close();
4298
+ process.exit(0);
4299
+ });
4300
+ process.on("uncaughtException", (error) => {
4301
+ logger2.error("\u672A\u6355\u83B7\u7684\u5F02\u5E38:", error);
4302
+ process.exit(1);
4303
+ });
4304
+ process.on("unhandledRejection", (reason, promise) => {
4305
+ logger2.error("\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD:", reason);
4306
+ process.exit(1);
4307
+ });
4308
+ }
4309
+ setupToolHandlers() {
4310
+ this.server.setRequestHandler(import_types16.ListToolsRequestSchema, async () => ({
4311
+ tools: [
4312
+ {
4313
+ name: "analyze_project",
4314
+ description: "\u5206\u6790\u9879\u76EE\u7684\u6280\u672F\u6808\u3001\u6846\u67B6\u3001\u5DE5\u5177\u548C\u7279\u5F81\u3002\u81EA\u52A8\u68C0\u6D4B Vue\u3001React\u3001TypeScript \u7B49\u6280\u672F\u3002\u8DEF\u5F84\u53EF\u9009\uFF0C\u4E0D\u586B\u5219\u81EA\u52A8\u68C0\u6D4B\u5F53\u524D\u5DE5\u4F5C\u533A\u3002",
4315
+ inputSchema: {
4316
+ type: "object",
4317
+ properties: {
4318
+ projectPath: {
4319
+ type: "string",
4320
+ description: "\u9879\u76EE\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u53EF\u9009\uFF0C\u4E0D\u586B\u5219\u4F7F\u7528\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\uFF09\uFF0C\u4F8B\u5982: /Users/username/projects/my-app"
4321
+ }
4322
+ }
4323
+ }
4324
+ },
4325
+ {
4326
+ name: "auto_setup",
4327
+ description: "\u{1F3AF} \u4E00\u952E\u81EA\u52A8\u914D\u7F6E MCP \u670D\u52A1\u5668\u548C\u9879\u76EE\u89C4\u8303\u3002\u81EA\u52A8\u521B\u5EFA .vscode/mcp.json\u3001settings.json\u3001extensions.json\uFF0C\u5E76\u5206\u6790\u9879\u76EE\u751F\u6210 .github/copilot-instructions.md \u914D\u7F6E\u6587\u4EF6\u3002",
4328
+ inputSchema: {
4329
+ type: "object",
4330
+ properties: {
4331
+ workspacePath: {
4332
+ type: "string",
4333
+ description: "\u5DE5\u4F5C\u533A\u8DEF\u5F84\uFF08\u53EF\u9009\uFF0C\u4E0D\u586B\u5219\u4F7F\u7528\u5F53\u524D\u76EE\u5F55\uFF09"
4334
+ },
4335
+ generateInstructions: {
4336
+ type: "boolean",
4337
+ description: "\u662F\u5426\u81EA\u52A8\u751F\u6210 copilot-instructions.md\uFF08\u9ED8\u8BA4 true\uFF09",
4338
+ default: true
4339
+ }
4340
+ }
4341
+ }
4342
+ },
4343
+ {
4344
+ name: "health_check",
4345
+ description: "\u{1F3E5} \u68C0\u67E5 MCP \u670D\u52A1\u5668\u5065\u5EB7\u72B6\u6001\uFF0C\u8BCA\u65AD\u914D\u7F6E\u95EE\u9898\u3002\u8FD4\u56DE\u8BE6\u7EC6\u7684\u5065\u5EB7\u62A5\u544A\u548C\u4FEE\u590D\u5EFA\u8BAE\u3002",
4346
+ inputSchema: {
4347
+ type: "object",
4348
+ properties: {
4349
+ workspacePath: {
4350
+ type: "string",
4351
+ description: "\u5DE5\u4F5C\u533A\u8DEF\u5F84\uFF08\u53EF\u9009\uFF09"
4352
+ },
4353
+ verbose: {
4354
+ type: "boolean",
4355
+ description: "\u662F\u5426\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F\uFF08\u9ED8\u8BA4 false\uFF09"
4356
+ }
4357
+ }
4358
+ }
4359
+ },
4360
+ {
4361
+ name: "get_smart_standards",
4362
+ description: "\u{1F9E0} \u96F6\u53C2\u6570\u667A\u80FD\u89C4\u8303\u63A8\u8350\u3002\u81EA\u52A8\u68C0\u6D4B\u5F53\u524D\u6587\u4EF6\u7C7B\u578B\u3001\u5BFC\u5165\u3001\u573A\u666F\uFF0C\u63A8\u8350\u6700\u76F8\u5173\u7684\u7F16\u7801\u89C4\u8303\u3002\u6BD4\u624B\u52A8\u6307\u5B9A\u53C2\u6570\u66F4\u7B80\u5355\u3002",
4363
+ inputSchema: {
4364
+ type: "object",
4365
+ properties: {
4366
+ currentFile: {
4367
+ type: "string",
4368
+ description: "\u5F53\u524D\u7F16\u8F91\u7684\u6587\u4EF6\u8DEF\u5F84\uFF08\u53EF\u9009\uFF09"
4369
+ },
4370
+ fileContent: {
4371
+ type: "string",
4372
+ description: "\u6587\u4EF6\u5185\u5BB9\uFF08\u53EF\u9009\uFF0C\u7528\u4E8E\u5206\u6790\u5BFC\u5165\u548C\u573A\u666F\uFF09"
4373
+ }
4374
+ }
4375
+ }
4376
+ },
4377
+ {
4378
+ name: "use_preset",
4379
+ description: "\u26A1 \u4F7F\u7528\u9884\u8BBE\u573A\u666F\u5FEB\u6377\u83B7\u53D6\u89C4\u8303\u3002\u652F\u6301 vue3-component\u3001vue3-form\u3001pinia-store\u3001api-call \u7B49\u5E38\u89C1\u573A\u666F\uFF0C\u4E00\u952E\u83B7\u53D6\u3002",
4380
+ inputSchema: {
4381
+ type: "object",
4382
+ properties: {
4383
+ preset: {
4384
+ type: "string",
4385
+ enum: ["vue3-component", "vue3-form", "vue3-table", "pinia-store", "api-call", "typescript-strict", "i18n", "composable"],
4386
+ description: "\u9884\u8BBE\u573A\u666F ID"
4387
+ },
4388
+ customImports: {
4389
+ type: "array",
4390
+ items: { type: "string" },
4391
+ description: "\u989D\u5916\u7684\u5BFC\u5165\uFF08\u53EF\u9009\uFF09"
4392
+ }
4393
+ },
4394
+ required: ["preset"]
4395
+ }
4396
+ },
4397
+ {
4398
+ name: "list_presets",
4399
+ description: "\u{1F4CB} \u5217\u51FA\u6240\u6709\u53EF\u7528\u7684\u9884\u8BBE\u573A\u666F\u53CA\u5176\u8BF4\u660E\u3002",
4400
+ inputSchema: {
4401
+ type: "object",
4402
+ properties: {}
4403
+ }
4404
+ },
4405
+ {
4406
+ name: "match_agents",
4407
+ description: "\u6839\u636E\u9879\u76EE\u7279\u5F81\u667A\u80FD\u5339\u914D\u6700\u5408\u9002\u7684 Copilot Agents\u3002\u4F7F\u7528\u52A0\u6743\u8BC4\u5206\u7B97\u6CD5\u3002",
4408
+ inputSchema: {
4409
+ type: "object",
4410
+ properties: {
4411
+ projectFeatures: {
4412
+ type: "object",
4413
+ description: "\u9879\u76EE\u7279\u5F81\u5BF9\u8C61\uFF08\u4ECE analyze_project \u83B7\u53D6\uFF09",
4414
+ properties: {
4415
+ frameworks: { type: "array", items: { type: "string" } },
4416
+ languages: { type: "array", items: { type: "string" } },
4417
+ tools: { type: "array", items: { type: "string" } },
4418
+ keywords: { type: "array", items: { type: "string" } },
4419
+ projectType: { type: "string" }
4420
+ },
4421
+ required: ["frameworks", "languages", "tools", "keywords", "projectType"]
4422
+ },
4423
+ limit: {
4424
+ type: "number",
4425
+ description: "\u8FD4\u56DE\u7684\u6700\u5927 Agent \u6570\u91CF\uFF08\u9ED8\u8BA4 10\uFF09",
4426
+ default: 10
4427
+ }
4428
+ },
4429
+ required: ["projectFeatures"]
4430
+ }
4431
+ },
4432
+ {
4433
+ name: "list_available_agents",
4434
+ description: "\u83B7\u53D6\u6240\u6709\u53EF\u7528\u7684 Copilot Agents \u5217\u8868\uFF0C\u5305\u62EC\u540D\u79F0\u3001\u63CF\u8FF0\u3001\u8DEF\u5F84\u7B49\u4FE1\u606F\u3002",
4435
+ inputSchema: {
4436
+ type: "object",
4437
+ properties: {}
4438
+ }
4439
+ },
4440
+ {
4441
+ name: "generate_config",
4442
+ description: "\u4E3A\u9879\u76EE\u751F\u6210 Copilot \u914D\u7F6E\u6587\u4EF6\uFF08.github/copilot-instructions.md\uFF09\u3002\u53EF\u4EE5\u81EA\u52A8\u5339\u914D\u6216\u624B\u52A8\u6307\u5B9A Agents\u3002",
4443
+ inputSchema: {
4444
+ type: "object",
4445
+ properties: {
4446
+ projectPath: {
4447
+ type: "string",
4448
+ description: "\u9879\u76EE\u7684\u7EDD\u5BF9\u8DEF\u5F84"
4449
+ },
4450
+ agentIds: {
4451
+ type: "array",
4452
+ items: { type: "string" },
4453
+ description: "\u8981\u5E94\u7528\u7684 Agent ID \u5217\u8868\uFF08\u53EF\u9009\uFF0C\u5982\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u5339\u914D\uFF09"
4454
+ },
4455
+ autoMatch: {
4456
+ type: "boolean",
4457
+ description: "\u662F\u5426\u81EA\u52A8\u5339\u914D Agents\uFF08\u9ED8\u8BA4 true\uFF09",
4458
+ default: true
4459
+ },
4460
+ updateMode: {
4461
+ type: "string",
4462
+ enum: ["merge", "overwrite"],
4463
+ description: "\u66F4\u65B0\u6A21\u5F0F\uFF1Amerge-\u4FDD\u7559\u81EA\u5B9A\u4E49\u5185\u5BB9\uFF08\u9ED8\u8BA4\uFF09\uFF0Coverwrite-\u5B8C\u5168\u8986\u76D6",
4464
+ default: "merge"
4465
+ },
4466
+ configId: {
4467
+ type: "string",
4468
+ description: "\u914D\u7F6E\u65B9\u6848ID\uFF08\u5982 strict\uFF09\uFF0C\u4F1A\u52A0\u8F7D\u5BF9\u5E94\u7684\u8BE6\u7EC6\u89C4\u5219"
4469
+ }
4470
+ },
4471
+ required: ["projectPath"]
4472
+ }
4473
+ },
4474
+ {
4475
+ name: "get_compact_standards",
4476
+ description: "\u{1F680} Token \u4F18\u5316\u7248\u89C4\u8303\u83B7\u53D6\u3002\u652F\u6301\u4E09\u79CD\u6A21\u5F0F\uFF1Asummary(~500 tokens)\u4EC5\u8FD4\u56DE\u89C4\u8303\u5217\u8868\u3001key-rules(~2000 tokens)\u8FD4\u56DE\u5173\u952E\u89C4\u5219\u6458\u8981\u3001full(\u5B8C\u6574\u5185\u5BB9)\u3002\u9ED8\u8BA4 key-rules \u6A21\u5F0F\uFF0C\u6BD4\u5B8C\u6574\u52A0\u8F7D\u8282\u7701 80%+ token\u3002",
4477
+ inputSchema: {
4478
+ type: "object",
4479
+ properties: {
4480
+ currentFile: {
4481
+ type: "string",
4482
+ description: "\u5F53\u524D\u6587\u4EF6\u8DEF\u5F84\uFF08\u53EF\u9009\uFF09"
4483
+ },
4484
+ fileContent: {
4485
+ type: "string",
4486
+ description: "\u6587\u4EF6\u5185\u5BB9\uFF08\u53EF\u9009\uFF0C\u7528\u4E8E\u5206\u6790\uFF09"
4487
+ },
4488
+ scenario: {
4489
+ type: "string",
4490
+ description: "\u5F00\u53D1\u573A\u666F\uFF08\u53EF\u9009\uFF09"
4491
+ },
4492
+ mode: {
4493
+ type: "string",
4494
+ enum: ["summary", "key-rules", "full"],
4495
+ description: "\u8FD4\u56DE\u6A21\u5F0F\uFF1Asummary(~500 tokens)\u3001key-rules(~2000 tokens\uFF0C\u9ED8\u8BA4)\u3001full(\u5B8C\u6574\u5185\u5BB9)",
4496
+ default: "key-rules"
4497
+ }
4498
+ }
4499
+ }
4500
+ },
4501
+ {
4502
+ name: "get_relevant_standards",
4503
+ description: "\u6839\u636E\u5F53\u524D\u5F00\u53D1\u4E0A\u4E0B\u6587\uFF0C\u83B7\u53D6\u76F8\u5173\u7684\u7F16\u7801\u89C4\u8303\uFF08\u5B8C\u6574\u5185\u5BB9\uFF09\u3002\u5982\u9700\u8282\u7701 token\uFF0C\u8BF7\u4F7F\u7528 get_compact_standards\u3002",
4504
+ inputSchema: {
4505
+ type: "object",
4506
+ properties: {
4507
+ fileType: {
4508
+ type: "string",
4509
+ description: "\u6587\u4EF6\u7C7B\u578B\uFF08\u5982 vue, ts, tsx, js\uFF09"
4510
+ },
4511
+ imports: {
4512
+ type: "array",
4513
+ items: { type: "string" },
4514
+ description: '\u6587\u4EF6\u4E2D\u7684 import \u8BED\u53E5\uFF08\u5982 ["vue", "pinia", "element-plus"]\uFF09\u3002\u5982\u679C\u672A\u63D0\u4F9B\u4E14\u63D0\u4F9B\u4E86 fileContent\uFF0C\u5C06\u81EA\u52A8\u68C0\u6D4B\u3002'
4515
+ },
4516
+ scenario: {
4517
+ type: "string",
4518
+ description: '\u5F00\u53D1\u573A\u666F\u63CF\u8FF0\uFF08\u5982 "\u521B\u5EFA\u8868\u5355\u7EC4\u4EF6", "API \u8C03\u7528", "\u72B6\u6001\u7BA1\u7406"\uFF09'
4519
+ },
4520
+ fileContent: {
4521
+ type: "string",
4522
+ description: "\u6587\u4EF6\u5185\u5BB9\uFF08\u53EF\u9009\uFF09\u3002\u63D0\u4F9B\u540E\u53EF\u81EA\u52A8\u68C0\u6D4B imports \u5E76\u6839\u636E\u5173\u952E\u8BCD\u667A\u80FD\u5339\u914D\u89C4\u8303\u3002"
4523
+ }
4524
+ }
4525
+ }
4526
+ },
4527
+ {
4528
+ name: "get_standards_stats",
4529
+ description: "\u83B7\u53D6\u89C4\u8303\u7CFB\u7EDF\u7684\u4F7F\u7528\u7EDF\u8BA1\u548C\u6027\u80FD\u6307\u6807\u3002\u7528\u4E8E\u4E86\u89E3\u6700\u5E38\u7528\u7684\u89C4\u8303\u7EC4\u5408\u3001\u7F13\u5B58\u547D\u4E2D\u7387\u3001Token \u8282\u7701\u60C5\u51B5\u7B49\u3002",
4530
+ inputSchema: {
4531
+ type: "object",
4532
+ properties: {
4533
+ includeCache: {
4534
+ type: "boolean",
4535
+ description: "\u662F\u5426\u5305\u542B\u7F13\u5B58\u8BE6\u7EC6\u4FE1\u606F\uFF08\u9ED8\u8BA4 false\uFF09"
4536
+ }
4537
+ }
4538
+ }
4539
+ },
4540
+ {
4541
+ name: "get_standard_by_id",
4542
+ description: "\u{1F4D6} \u6309 ID \u76F4\u63A5\u83B7\u53D6\u89C4\u8303\u3002AI \u77E5\u9053\u9700\u8981\u4EC0\u4E48\u89C4\u8303\u65F6\uFF0C\u76F4\u63A5\u6309 ID \u83B7\u53D6\uFF0C\u6700\u7B80\u6D01\u9AD8\u6548\u3002\u652F\u6301\u4E09\u79CD\u6A21\u5F0F\uFF1Asummary(\u6458\u8981)\u3001key-rules(\u5173\u952E\u89C4\u5219\uFF0C\u9ED8\u8BA4)\u3001full(\u5B8C\u6574\u5185\u5BB9)\u3002",
4543
+ inputSchema: {
4544
+ type: "object",
4545
+ properties: {
4546
+ id: {
4547
+ type: "string",
4548
+ description: "\u89C4\u8303 ID\uFF08\u5982 vue3-composition, element-plus, pinia\uFF09"
4549
+ },
4550
+ ids: {
4551
+ type: "array",
4552
+ items: { type: "string" },
4553
+ description: "\u591A\u4E2A\u89C4\u8303 ID\uFF0C\u6279\u91CF\u83B7\u53D6"
4554
+ },
4555
+ mode: {
4556
+ type: "string",
4557
+ enum: ["summary", "key-rules", "full"],
4558
+ description: "\u52A0\u8F7D\u6A21\u5F0F\uFF1Asummary(\u6458\u8981)\u3001key-rules(\u5173\u952E\u89C4\u5219\uFF0C\u9ED8\u8BA4)\u3001full(\u5B8C\u6574\u5185\u5BB9)",
4559
+ default: "key-rules"
4560
+ }
4561
+ }
4562
+ }
4563
+ },
4564
+ {
4565
+ name: "query_mappings",
4566
+ description: '\u{1F5FA}\uFE0F \u67E5\u8BE2\u573A\u666F-\u89C4\u8303\u6620\u5C04\u5173\u7CFB\u3002\u63D0\u4F9B\u6620\u5C04\u4FE1\u606F\u7ED9 AI \u53C2\u8003\uFF0CAI \u81EA\u5DF1\u51B3\u5B9A\u4F7F\u7528\u54EA\u4E9B\u89C4\u8303\u3002\u4E0D\u505A"\u667A\u80FD\u63A8\u8350"\uFF0C\u53EA\u63D0\u4F9B\u6570\u636E\u67E5\u8BE2\u3002',
4567
+ inputSchema: {
4568
+ type: "object",
4569
+ properties: {
4570
+ scenario: {
4571
+ type: "string",
4572
+ description: "\u573A\u666F\u540D\u79F0\uFF08\u5982 vue3-form, api-call, pinia-store\uFF09"
4573
+ },
4574
+ fileType: {
4575
+ type: "string",
4576
+ description: "\u6587\u4EF6\u7C7B\u578B\uFF08\u5982 vue, ts, tsx\uFF09"
4577
+ },
4578
+ imports: {
4579
+ type: "array",
4580
+ items: { type: "string" },
4581
+ description: "\u5BFC\u5165\u7684\u5305\uFF08\u5982 element-plus, pinia\uFF09"
4582
+ },
4583
+ listAll: {
4584
+ type: "boolean",
4585
+ description: "\u5217\u51FA\u6240\u6709\u6620\u5C04\u5173\u7CFB"
4586
+ }
4587
+ }
4588
+ }
4589
+ },
4590
+ {
4591
+ name: "list_scenarios",
4592
+ description: "\u{1F4CB} \u5217\u51FA\u6240\u6709\u53EF\u7528\u7684\u573A\u666F\u540D\u79F0\u3002AI \u53EF\u4F7F\u7528\u8FD9\u4E9B\u573A\u666F\u540D\u79F0\u8C03\u7528 use_preset \u6216 query_mappings\u3002",
4593
+ inputSchema: {
4594
+ type: "object",
4595
+ properties: {}
4596
+ }
4597
+ },
4598
+ {
4599
+ name: "list_templates",
4600
+ description: "\u{1F4E6} \u5217\u51FA\u53EF\u7528\u7684\u4EE3\u7801\u6A21\u677F\u3002\u6A21\u677F\u662F\u53EF\u590D\u7528\u7684\u4EE3\u7801\u7247\u6BB5\uFF0CAI \u53EF\u6839\u636E\u9700\u8981\u9009\u62E9\u5E76\u5E94\u7528\u5230\u76EE\u6807\u9879\u76EE\u3002",
4601
+ inputSchema: {
4602
+ type: "object",
4603
+ properties: {
4604
+ type: {
4605
+ type: "string",
4606
+ enum: ["api-layer", "component", "store", "composable", "config", "types", "other"],
4607
+ description: "\u6309\u7C7B\u578B\u7B5B\u9009"
4608
+ },
4609
+ framework: {
4610
+ type: "string",
4611
+ description: "\u6309\u6846\u67B6\u7B5B\u9009\uFF08\u5982 vue, react\uFF09"
4612
+ },
4613
+ search: {
4614
+ type: "string",
4615
+ description: "\u641C\u7D22\u5173\u952E\u8BCD"
4616
+ }
4617
+ }
4618
+ }
4619
+ },
4620
+ {
4621
+ name: "get_template",
4622
+ description: "\u{1F4C4} \u83B7\u53D6\u6A21\u677F\u8BE6\u60C5\u548C\u6587\u4EF6\u5185\u5BB9\u3002AI \u53EF\u6839\u636E\u914D\u7F6E\u8BF4\u660E\u81EA\u884C\u4FEE\u6539\u5E76\u5E94\u7528\u6A21\u677F\u3002",
4623
+ inputSchema: {
4624
+ type: "object",
4625
+ properties: {
4626
+ id: {
4627
+ type: "string",
4628
+ description: "\u6A21\u677F ID\uFF08\u5982 vue/api-layer\uFF09"
4629
+ },
4630
+ includeFiles: {
4631
+ type: "boolean",
4632
+ description: "\u662F\u5426\u5305\u542B\u6587\u4EF6\u5185\u5BB9\uFF08\u9ED8\u8BA4 false\uFF0C\u53EA\u8FD4\u56DE\u914D\u7F6E\u8BF4\u660E\uFF09",
4633
+ default: false
4634
+ },
4635
+ files: {
4636
+ type: "array",
4637
+ items: { type: "string" },
4638
+ description: "\u6307\u5B9A\u8981\u83B7\u53D6\u7684\u6587\u4EF6\u5217\u8868\uFF08\u53EF\u9009\uFF09"
4639
+ }
4640
+ },
4641
+ required: ["id"]
4642
+ }
4643
+ }
4644
+ ]
4645
+ }));
4646
+ this.server.setRequestHandler(import_types16.CallToolRequestSchema, async (request) => {
4647
+ try {
4648
+ const { name, arguments: args } = request.params;
4649
+ logger2.debug(`\u8C03\u7528\u5DE5\u5177: ${name}`);
4650
+ logger2.debug(`\u53C2\u6570:`, args);
4651
+ switch (name) {
4652
+ case "analyze_project":
4653
+ return await analyzeProject(args);
4654
+ case "auto_setup":
4655
+ return await autoSetup(args);
4656
+ case "health_check":
4657
+ return await healthCheck(args);
4658
+ case "get_smart_standards":
4659
+ return await getSmartStandards(args);
4660
+ case "use_preset":
4661
+ return await usePreset(args);
4662
+ case "list_presets":
4663
+ return await listPresets();
4664
+ case "match_agents":
4665
+ return await matchAgents(args);
4666
+ case "list_available_agents":
4667
+ return await listAvailableAgents();
4668
+ case "generate_config":
4669
+ return await generateConfig(args);
4670
+ case "get_compact_standards":
4671
+ return await getCompactStandards(args);
4672
+ case "get_relevant_standards":
4673
+ return this.getRelevantStandards(args);
4674
+ case "get_standards_stats":
4675
+ return this.getStandardsStats(args);
4676
+ case "get_standard_by_id":
4677
+ return await getStandardById(args);
4678
+ case "query_mappings":
4679
+ return await queryMappings(args);
4680
+ case "list_scenarios":
4681
+ return await listScenarios();
4682
+ case "list_templates":
4683
+ return await listTemplates(args);
4684
+ case "get_template":
4685
+ return await getTemplate(args);
4686
+ default:
4687
+ throw new Error(`\u672A\u77E5\u5DE5\u5177: ${name}`);
4688
+ }
4689
+ } catch (error) {
4690
+ logger2.error(`\u5DE5\u5177\u6267\u884C\u5931\u8D25:`, error);
4691
+ return errorResponse(error);
4692
+ }
4693
+ });
4694
+ }
4695
+ /**
4696
+ * 设置资源处理器
4697
+ */
4698
+ setupResourceHandlers() {
4699
+ this.server.setRequestHandler(import_types16.ListResourcesRequestSchema, async () => {
4700
+ const standards = this.standardsManager.getAvailableStandards();
4701
+ return {
4702
+ resources: standards.map((std) => ({
4703
+ uri: std.uri,
4704
+ name: std.name,
4705
+ description: std.description,
4706
+ mimeType: "text/markdown"
4707
+ }))
4708
+ };
4709
+ });
4710
+ this.server.setRequestHandler(import_types16.ReadResourceRequestSchema, async (request) => {
4711
+ const { uri } = request.params;
4712
+ try {
4713
+ const content = this.standardsManager.readStandard(uri);
4714
+ return {
4715
+ contents: [{
4716
+ uri,
4717
+ mimeType: "text/markdown",
4718
+ text: content
4719
+ }]
4720
+ };
4721
+ } catch (error) {
4722
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u89C4\u8303 ${uri}: ${error}`);
4723
+ }
4724
+ });
4725
+ }
4726
+ /**
4727
+ * 获取相关编码规范
4728
+ */
4729
+ getRelevantStandards(args) {
4730
+ const standardUris = this.standardsManager.getRelevantStandards(args);
4731
+ const content = this.standardsManager.combineStandards(standardUris);
4732
+ return {
4733
+ content: [{
4734
+ type: "text",
4735
+ text: JSON.stringify({
4736
+ success: true,
4737
+ standards: standardUris,
4738
+ content,
4739
+ tokenEstimate: Math.ceil(content.length / 4),
4740
+ // 粗略估算 token 数
4741
+ message: `\u5DF2\u52A0\u8F7D ${standardUris.length} \u4E2A\u76F8\u5173\u89C4\u8303`
4742
+ }, null, 2)
4743
+ }]
4744
+ };
4745
+ }
4746
+ /**
4747
+ * 获取规范系统统计信息(Phase 3)
4748
+ */
4749
+ getStandardsStats(args) {
4750
+ const usageStats = this.standardsManager.getUsageStats();
4751
+ const performanceMetrics = this.standardsManager.getPerformanceMetrics();
4752
+ const result = {
4753
+ success: true,
4754
+ usage: usageStats,
4755
+ performance: performanceMetrics,
4756
+ summary: {
4757
+ totalCalls: usageStats.totalCalls,
4758
+ cacheHitRate: performanceMetrics.cacheHitRate,
4759
+ totalTokensSaved: performanceMetrics.totalTokensSaved,
4760
+ averageResponseTime: `${performanceMetrics.averageResponseTime.toFixed(2)}ms`
4761
+ }
4762
+ };
4763
+ if (args.includeCache) {
4764
+ result.cache = this.standardsManager.getCacheStats();
4765
+ }
4766
+ return {
4767
+ content: [{
4768
+ type: "text",
4769
+ text: JSON.stringify(result, null, 2)
4770
+ }]
4771
+ };
4772
+ }
4773
+ async run() {
4774
+ const transport = new import_stdio.StdioServerTransport();
4775
+ await this.server.connect(transport);
4776
+ logger2.info(`Copilot Prompts MCP Server v${SERVER_VERSION} \u5DF2\u542F\u52A8`);
4777
+ }
4778
+ };
4779
+ var server = new CopilotPromptsMCPServer();
4780
+ server.run().catch((error) => {
4781
+ logger2.error("\u670D\u52A1\u5668\u542F\u52A8\u5931\u8D25:", error);
4782
+ process.exit(1);
4783
+ });
4784
+ //# sourceMappingURL=index.cjs.map