px2cc 2.2.2 → 2.2.4

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.
@@ -1,432 +1,499 @@
1
- /**
2
- * PromptXActionProcessor - 实现完整的PromptX Action流程
3
- *
4
- * 替代简单的parsePromptXRole函数,实现:
5
- * 1. 角色加载器 (RoleLoader)
6
- * 2. 依赖分析器 (DependencyAnalyzer)
7
- * 3. 认知网络加载器 (CognitionLoader)
8
- * 4. 三层组装器 (LayerAssembler)
9
- */
10
-
11
- import { resource } from '@promptx/core';
12
- import fs from 'fs/promises';
13
- import path from 'path';
14
- import os from 'os';
15
- import chalk from 'chalk';
16
-
17
- /**
18
- * 角色加载器 - 替代PromptX的ResourceManager
19
- */
20
- class RoleLoader {
21
- constructor(resourceManager) {
22
- this.resourceManager = resourceManager;
23
- }
24
-
25
- /**
26
- * 加载角色定义
27
- * @param {string} roleId - 角色ID
28
- * @returns {Object} 角色信息
29
- */
30
- async loadRole(roleId) {
31
- console.log(chalk.cyan(`📖 加载角色定义: ${roleId}`));
32
-
33
- try {
34
- // 确保ResourceManager已初始化
35
- if (!this.resourceManager.initialized) {
36
- await this.resourceManager.initializeWithNewArchitecture();
37
- }
38
-
39
- // 加载角色资源
40
- const result = await this.resourceManager.loadResource(`@role://${roleId}`);
41
-
42
- if (!result || !result.success || !result.content) {
43
- throw new Error(`无法加载角色 ${roleId} 的内容`);
44
- }
45
-
46
- // 解析DPML内容
47
- const parsedContent = this.parseDPMLContent(result.content);
48
-
49
- return {
50
- id: roleId,
51
- raw: result.content,
52
- sections: parsedContent,
53
- metadata: result.metadata || {}
54
- };
55
-
56
- } catch (error) {
57
- console.error(chalk.red(`❌ 角色加载失败: ${error.message}`));
58
- throw error;
59
- }
60
- }
61
-
62
- /**
63
- * 解析DPML角色文档
64
- * @param {string} content - 原始内容
65
- * @returns {Object} 解析后的sections
66
- */
67
- parseDPMLContent(content) {
68
- const sections = {};
69
-
70
- // 解析 <role> 标签
71
- const roleMatch = content.match(/<role>([\s\S]*?)<\/role>/);
72
- if (roleMatch) {
73
- const roleContent = roleMatch[1];
74
-
75
- // 提取各个部分
76
- sections.personality = this.extractSection(roleContent, 'personality');
77
- sections.principle = this.extractSection(roleContent, 'principle');
78
- sections.knowledge = this.extractSection(roleContent, 'knowledge');
79
- }
80
-
81
- return sections;
82
- }
83
-
84
- /**
85
- * 提取XML标签内容
86
- * @param {string} content - 内容
87
- * @param {string} tagName - 标签名
88
- * @returns {string|null} 提取的内容
89
- */
90
- extractSection(content, tagName) {
91
- const regex = new RegExp(`<${tagName}>([\\s\\S]*?)<\\/${tagName}>`, 'i');
92
- const match = content.match(regex);
93
- return match ? match[1].trim() : null;
94
- }
95
- }
96
-
97
- /**
98
- * 依赖分析器 - 分析和加载资源依赖
99
- */
100
- class DependencyAnalyzer {
101
- constructor(resourceManager) {
102
- this.resourceManager = resourceManager;
103
- }
104
-
105
- /**
106
- * 分析角色依赖
107
- * @param {Object} roleInfo - 角色信息
108
- * @returns {Object} 依赖资源
109
- */
110
- async analyzeDependencies(roleInfo) {
111
- console.log(chalk.cyan(`🔍 分析资源依赖...`));
112
-
113
- const dependencies = {
114
- thoughts: [],
115
- executions: [],
116
- knowledges: []
117
- };
118
-
119
- if (!roleInfo.sections) {
120
- return dependencies;
121
- }
122
-
123
- // 收集所有资源引用
124
- const allRefs = this.extractResourceReferences(roleInfo.sections);
125
-
126
- console.log(chalk.gray(` 发现 ${allRefs.length} 个资源引用`));
127
-
128
- // 并发加载所有依赖
129
- const loadPromises = allRefs.map(ref => this.loadDependency(ref));
130
- const results = await Promise.allSettled(loadPromises);
131
-
132
- // 分类处理结果
133
- results.forEach((result, index) => {
134
- if (result.status === 'fulfilled' && result.value) {
135
- const ref = allRefs[index];
136
- const content = result.value;
137
-
138
- switch (ref.protocol) {
139
- case 'thought':
140
- dependencies.thoughts.push({ id: ref.resource, content });
141
- break;
142
- case 'execution':
143
- dependencies.executions.push({ id: ref.resource, content });
144
- break;
145
- case 'knowledge':
146
- dependencies.knowledges.push({ id: ref.resource, content });
147
- break;
148
- }
149
- }
150
- });
151
-
152
- console.log(chalk.green(`✅ 依赖分析完成: thoughts=${dependencies.thoughts.length}, executions=${dependencies.executions.length}, knowledges=${dependencies.knowledges.length}`));
153
-
154
- return dependencies;
155
- }
156
-
157
- /**
158
- * 提取资源引用
159
- * @param {Object} sections - 角色sections
160
- * @returns {Array} 引用列表
161
- */
162
- extractResourceReferences(sections) {
163
- const refs = [];
164
-
165
- const extractFromText = (text) => {
166
- if (!text) return [];
167
- // 匹配 @!protocol://resource 或 @protocol://resource 格式
168
- const matches = text.matchAll(/@!?([^:]+):\/\/([^\s\>\<\n]+)/g);
169
- return Array.from(matches).map(match => ({
170
- protocol: match[1],
171
- resource: match[2]
172
- }));
173
- };
174
-
175
- // 从所有sections中提取引用
176
- Object.values(sections).forEach(section => {
177
- refs.push(...extractFromText(section));
178
- });
179
-
180
- return refs;
181
- }
182
-
183
- /**
184
- * 加载单个依赖
185
- * @param {Object} ref - 引用对象
186
- * @returns {Promise<string>} 内容
187
- */
188
- async loadDependency(ref) {
189
- try {
190
- const resourceUrl = `@${ref.protocol}://${ref.resource}`;
191
- const result = await this.resourceManager.loadResource(resourceUrl);
192
-
193
- if (result && result.success && result.content) {
194
- return result.content;
195
- }
196
-
197
- console.warn(chalk.yellow(`⚠️ 无法加载依赖: ${resourceUrl}`));
198
- return null;
199
- } catch (error) {
200
- console.warn(chalk.yellow(`⚠️ 依赖加载失败: @${ref.protocol}://${ref.resource} - ${error.message}`));
201
- return null;
202
- }
203
- }
204
- }
205
-
206
- /**
207
- * 认知网络加载器 - 加载PromptX认知数据
208
- */
209
- class CognitionLoader {
210
- constructor() {
211
- this.basePath = path.join(os.homedir(), '.promptx', 'cognition');
212
- }
213
-
214
- /**
215
- * 检查认知网络是否存在(不加载具体内容)
216
- * @param {string} roleId - 角色ID
217
- * @returns {Object} 认知网络存在状态
218
- */
219
- async checkNetworkExists(roleId) {
220
- console.log(chalk.cyan(`🧠 检查认知网络状态: ${roleId}`));
221
-
222
- try {
223
- const networkFilePath = path.join(this.basePath, roleId, 'network.json');
224
-
225
- // 仅检查文件是否存在
226
- try {
227
- await fs.access(networkFilePath);
228
- console.log(chalk.green(`✅ 发现认知网络文件: ${roleId}`));
229
- return {
230
- hasNetwork: true,
231
- networkPath: networkFilePath
232
- };
233
- } catch (error) {
234
- console.log(chalk.gray(` 未找到认知网络文件: ${roleId}`));
235
- return {
236
- hasNetwork: false,
237
- networkPath: networkFilePath
238
- };
239
- }
240
-
241
- } catch (error) {
242
- console.warn(chalk.yellow(`⚠️ 认知网络检查失败: ${error.message}`));
243
- return {
244
- hasNetwork: false,
245
- networkPath: null,
246
- error: error.message
247
- };
248
- }
249
- }
250
-
251
- }
252
-
253
- /**
254
- * 三层组装器 - 组装最终输出内容
255
- */
256
- class LayerAssembler {
257
- /**
258
- * 组装完整内容
259
- * @param {Object} roleInfo - 角色信息
260
- * @param {Object} dependencies - 依赖资源
261
- * @param {Object} cognitionData - 认知数据
262
- * @param {string} mode - 模式 (command|subagent)
263
- * @returns {string} 组装后的内容
264
- */
265
- assembleContent(roleInfo, dependencies, cognitionData, mode = 'command') {
266
- const parts = [];
267
-
268
- // 标题部分
269
- parts.push(`# 🧠 [Consciousness Prime] ${roleInfo.id}${mode === 'subagent' ? '专业助手' : '角色已激活'}`);
270
- parts.push('');
271
-
272
- // CognitionLayer - PromptX认知增强
273
- parts.push('## 💭 PromptX认知增强');
274
-
275
- if (cognitionData.hasNetwork) {
276
- parts.push('🧠 **状态**: 该角色已建立经验网络');
277
- parts.push('');
278
- parts.push('🔧 **激活方式** (需要PromptX MCP服务器):');
279
- parts.push(`- \`recall ${roleInfo.id}\` - 激活该角色的完整经验网络`);
280
- parts.push(`- \`recall ${roleInfo.id} "具体问题"\` - 检索相关历史经验`);
281
- parts.push(`- \`remember ${roleInfo.id} "新知识"\` - 将新经验加入角色记忆`);
282
- parts.push('');
283
- parts.push('💡 **说明**: 认知网络包含该角色的历史使用经验,通过recall工具动态激活');
284
-
285
- } else {
286
- parts.push('🌱 **状态**: 该角色尚未建立经验网络');
287
- parts.push('');
288
- parts.push('🚀 **开始使用**:');
289
- parts.push('- 安装并配置PromptX MCP服务器');
290
- parts.push(`- 使用 \`recall ${roleInfo.id}\` 开始建立认知网络`);
291
- parts.push('- 随着使用逐步积累该角色的专业经验');
292
- }
293
-
294
- parts.push('');
295
-
296
- // RoleLayer - 角色定义
297
- if (roleInfo.sections.personality) {
298
- parts.push('## 🎭 角色人格');
299
- parts.push(this.cleanContent(roleInfo.sections.personality));
300
- parts.push('');
301
- }
302
-
303
- if (roleInfo.sections.principle) {
304
- parts.push('## 🔧 工作原则');
305
- parts.push(this.cleanContent(roleInfo.sections.principle));
306
- parts.push('');
307
- }
308
-
309
- if (roleInfo.sections.knowledge) {
310
- parts.push('## 📚 专业知识');
311
- parts.push(this.cleanContent(roleInfo.sections.knowledge));
312
- parts.push('');
313
- }
314
-
315
- // 依赖资源
316
- if (dependencies.thoughts.length > 0) {
317
- parts.push('## 💡 思维模式');
318
- dependencies.thoughts.forEach(thought => {
319
- parts.push(`### ${thought.id}`);
320
- parts.push(this.cleanContent(thought.content));
321
- parts.push('');
322
- });
323
- }
324
-
325
- if (dependencies.executions.length > 0) {
326
- parts.push('## ⚡ 执行技能');
327
- dependencies.executions.forEach(execution => {
328
- parts.push(`### ${execution.id}`);
329
- parts.push(this.cleanContent(execution.content));
330
- parts.push('');
331
- });
332
- }
333
-
334
- // StateLayer - 状态信息
335
- parts.push('---');
336
- parts.push('');
337
-
338
- if (mode === 'command') {
339
- parts.push(`🎉 ${roleInfo.id}角色激活完成!我现在以该角色身份为你服务。`);
340
- } else {
341
- parts.push('## 🤖 助手说明');
342
- parts.push(`我是基于PromptX ${roleInfo.id}角色的专业AI助手。我会:`);
343
- parts.push(`- 始终保持${roleInfo.id}的专业身份和思维模式`);
344
- parts.push('- 利用完整的PromptX工具生态提供专业服务');
345
- parts.push('- 在我们的对话过程中持续学习和记忆');
346
- parts.push('');
347
- parts.push('请告诉我你需要什么帮助?');
348
- }
349
-
350
- parts.push('');
351
- parts.push('---');
352
- parts.push('');
353
- parts.push('💡 **可用的PromptX工具生态**:');
354
- parts.push(`- \`recall ${roleInfo.id}\` - 激活该角色的历史经验网络`);
355
- parts.push(`- \`remember ${roleInfo.id} "新体验"\` - 将新体验编织到角色记忆`);
356
- parts.push('- `learn` - 学习新的资源和知识');
357
- parts.push('- `toolx` - 执行专业工具');
358
- parts.push('- 具体工具可用性取决于PromptX MCP服务器配置');
359
- parts.push('');
360
-
361
- if (mode === 'command') {
362
- parts.push('现在开始处理用户需求。');
363
- }
364
-
365
- return parts.join('\n');
366
- }
367
-
368
- /**
369
- * 清理内容格式
370
- * @param {string} content - 原始内容
371
- * @returns {string} 清理后的内容
372
- */
373
- cleanContent(content) {
374
- if (!content) return '';
375
-
376
- return content
377
- // 移除PromptX资源引用标签(但保留引用内容的展开结果)
378
- .replace(/<reference[^>]*>/g, '')
379
- .replace(/<\/reference>/g, '')
380
- // 移除@!protocol://resource引用行(因为依赖内容会单独展示)
381
- .replace(/\s*@!?[^:]+:\/\/[^\s\>\<\n]+\s*/g, '')
382
- // 清理多余空行
383
- .replace(/\n\s*\n\s*\n/g, '\n\n')
384
- // 移除开头结尾空白
385
- .trim();
386
- }
387
- }
388
-
389
- /**
390
- * PromptX Action处理器主类
391
- */
392
- export class PromptXActionProcessor {
393
- constructor() {
394
- this.resourceManager = resource.getGlobalResourceManager();
395
- this.roleLoader = new RoleLoader(this.resourceManager);
396
- this.dependencyAnalyzer = new DependencyAnalyzer(this.resourceManager);
397
- this.cognitionLoader = new CognitionLoader();
398
- this.layerAssembler = new LayerAssembler();
399
- }
400
-
401
- /**
402
- * 执行完整的PromptX Action流程
403
- * @param {string} roleId - 角色ID
404
- * @param {string} mode - 模式 (command|subagent)
405
- * @returns {string} 处理后的内容
406
- */
407
- async processRole(roleId, mode = 'command') {
408
- try {
409
- console.log(chalk.blue(`\n🎭 开始执行 ${roleId} 的 PromptX Action 流程 (${mode} 模式)`));
410
-
411
- // 1. 加载角色定义
412
- const roleInfo = await this.roleLoader.loadRole(roleId);
413
-
414
- // 2. 分析依赖资源
415
- const dependencies = await this.dependencyAnalyzer.analyzeDependencies(roleInfo);
416
-
417
- // 3. 检查认知网络存在性
418
- const cognitionData = await this.cognitionLoader.checkNetworkExists(roleId);
419
-
420
- // 4. 三层组装
421
- const content = this.layerAssembler.assembleContent(roleInfo, dependencies, cognitionData, mode);
422
-
423
- console.log(chalk.green(`✅ PromptX Action 流程完成!`));
424
-
425
- return content;
426
-
427
- } catch (error) {
428
- console.error(chalk.red(`❌ PromptX Action 流程失败: ${error.message}`));
429
- throw error;
430
- }
431
- }
1
+ /**
2
+ * PromptXActionProcessor - 实现完整的PromptX Action流程
3
+ *
4
+ * 替代简单的parsePromptXRole函数,实现:
5
+ * 1. 角色加载器 (RoleLoader)
6
+ * 2. 依赖分析器 (DependencyAnalyzer)
7
+ * 3. 认知网络加载器 (CognitionLoader)
8
+ * 4. 三层组装器 (LayerAssembler)
9
+ */
10
+
11
+ import { resource } from '@promptx/core';
12
+ import fs from 'fs/promises';
13
+ import path from 'path';
14
+ import os from 'os';
15
+ import chalk from 'chalk';
16
+
17
+ /**
18
+ * 角色加载器 - 替代PromptX的ResourceManager
19
+ */
20
+ class RoleLoader {
21
+ constructor(resourceManager) {
22
+ this.resourceManager = resourceManager;
23
+ }
24
+
25
+ /**
26
+ * 加载角色定义
27
+ * @param {string} roleId - 角色ID
28
+ * @returns {Object} 角色信息
29
+ */
30
+ async loadRole(roleId) {
31
+ console.log(chalk.cyan(`📖 加载角色定义: ${roleId}`));
32
+
33
+ try {
34
+ // 确保ResourceManager已初始化
35
+ if (!this.resourceManager.initialized) {
36
+ await this.resourceManager.initializeWithNewArchitecture();
37
+ }
38
+
39
+ // 加载角色资源
40
+ const result = await this.resourceManager.loadResource(`@role://${roleId}`);
41
+
42
+ if (!result || !result.success || !result.content) {
43
+ throw new Error(`无法加载角色 ${roleId} 的内容`);
44
+ }
45
+
46
+ // 解析DPML内容
47
+ const parsedContent = this.parseDPMLContent(result.content);
48
+
49
+ return {
50
+ id: roleId,
51
+ raw: result.content,
52
+ sections: parsedContent,
53
+ metadata: result.metadata || {}
54
+ };
55
+
56
+ } catch (error) {
57
+ console.error(chalk.red(`❌ 角色加载失败: ${error.message}`));
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * 解析DPML角色文档(支持新旧两种格式)
64
+ * @param {string} content - 原始内容
65
+ * @returns {Object} 解析后的sections
66
+ */
67
+ parseDPMLContent(content) {
68
+ const sections = {};
69
+
70
+ // 尝试旧格式:<role>...</role> 包裹的 XML 格式
71
+ const roleMatch = content.match(/<role>([\s\S]*?)<\/role>/);
72
+ if (roleMatch) {
73
+ const roleContent = roleMatch[1];
74
+
75
+ // 提取各个部分
76
+ sections.personality = this.extractXMLSection(roleContent, 'personality');
77
+ sections.principle = this.extractXMLSection(roleContent, 'principle');
78
+ sections.knowledge = this.extractXMLSection(roleContent, 'knowledge');
79
+
80
+ // 如果成功提取到内容,返回
81
+ if (sections.personality || sections.principle || sections.knowledge) {
82
+ return sections;
83
+ }
84
+ }
85
+
86
+ // 尝试新格式:<role id="..."> 开头的 Markdown 格式
87
+ const newRoleMatch = content.match(/<role\s+id="[^"]*">/);
88
+ if (newRoleMatch || !roleMatch) {
89
+ // 新格式:直接使用整个内容作为角色定义
90
+ // 移除 <role id="..."> 和 </role> 标签
91
+ let cleanContent = content
92
+ .replace(/<role\s+id="[^"]*">\s*/g, '')
93
+ .replace(/<\/role>\s*$/g, '')
94
+ .trim();
95
+
96
+ // 将整个 Markdown 内容作为角色定义
97
+ sections.fullContent = cleanContent;
98
+
99
+ // 尝试从 Markdown 中提取结构化内容
100
+ sections.personality = this.extractMarkdownSection(cleanContent, ['核心定位', '角色定位', '人格', '身份']);
101
+ sections.principle = this.extractMarkdownSection(cleanContent, ['核心能力', '工作原则', '原则', '方法论']);
102
+ sections.knowledge = this.extractMarkdownSection(cleanContent, ['专业知识', '知识体系', '领域知识']);
103
+ }
104
+
105
+ return sections;
106
+ }
107
+
108
+ /**
109
+ * 提取XML标签内容(旧格式)
110
+ * @param {string} content - 内容
111
+ * @param {string} tagName - 标签名
112
+ * @returns {string|null} 提取的内容
113
+ */
114
+ extractXMLSection(content, tagName) {
115
+ const regex = new RegExp(`<${tagName}>([\\s\\S]*?)<\\/${tagName}>`, 'i');
116
+ const match = content.match(regex);
117
+ return match ? match[1].trim() : null;
118
+ }
119
+
120
+ /**
121
+ * 从 Markdown 内容中提取指定标题下的内容(新格式)
122
+ * @param {string} content - Markdown 内容
123
+ * @param {Array<string>} headingKeywords - 可能的标题关键词
124
+ * @returns {string|null} 提取的内容
125
+ */
126
+ extractMarkdownSection(content, headingKeywords) {
127
+ for (const keyword of headingKeywords) {
128
+ // 匹配 ## 或 ### 开头的标题
129
+ const regex = new RegExp(`^##\\s*${keyword}[^\\n]*\\n([\\s\\S]*?)(?=^##\\s|$)`, 'im');
130
+ const match = content.match(regex);
131
+ if (match) {
132
+ return match[1].trim();
133
+ }
134
+ }
135
+ return null;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * 依赖分析器 - 分析和加载资源依赖
141
+ */
142
+ class DependencyAnalyzer {
143
+ constructor(resourceManager) {
144
+ this.resourceManager = resourceManager;
145
+ }
146
+
147
+ /**
148
+ * 分析角色依赖
149
+ * @param {Object} roleInfo - 角色信息
150
+ * @returns {Object} 依赖资源
151
+ */
152
+ async analyzeDependencies(roleInfo) {
153
+ console.log(chalk.cyan(`🔍 分析资源依赖...`));
154
+
155
+ const dependencies = {
156
+ thoughts: [],
157
+ executions: [],
158
+ knowledges: []
159
+ };
160
+
161
+ if (!roleInfo.sections && !roleInfo.raw) {
162
+ return dependencies;
163
+ }
164
+
165
+ // 收集所有资源引用(从 sections 和原始内容中提取)
166
+ const allRefs = this.extractResourceReferences(roleInfo.sections, roleInfo.raw);
167
+
168
+ console.log(chalk.gray(` 发现 ${allRefs.length} 个资源引用`));
169
+
170
+ // 并发加载所有依赖
171
+ const loadPromises = allRefs.map(ref => this.loadDependency(ref));
172
+ const results = await Promise.allSettled(loadPromises);
173
+
174
+ // 分类处理结果
175
+ results.forEach((result, index) => {
176
+ if (result.status === 'fulfilled' && result.value) {
177
+ const ref = allRefs[index];
178
+ const content = result.value;
179
+
180
+ switch (ref.protocol) {
181
+ case 'thought':
182
+ dependencies.thoughts.push({ id: ref.resource, content });
183
+ break;
184
+ case 'execution':
185
+ dependencies.executions.push({ id: ref.resource, content });
186
+ break;
187
+ case 'knowledge':
188
+ dependencies.knowledges.push({ id: ref.resource, content });
189
+ break;
190
+ }
191
+ }
192
+ });
193
+
194
+ console.log(chalk.green(`✅ 依赖分析完成: thoughts=${dependencies.thoughts.length}, executions=${dependencies.executions.length}, knowledges=${dependencies.knowledges.length}`));
195
+
196
+ return dependencies;
197
+ }
198
+
199
+ /**
200
+ * 提取资源引用
201
+ * @param {Object} sections - 角色sections
202
+ * @param {string} rawContent - 原始内容
203
+ * @returns {Array} 引用列表
204
+ */
205
+ extractResourceReferences(sections, rawContent) {
206
+ const refs = [];
207
+ const seenRefs = new Set(); // 用于去重
208
+
209
+ const extractFromText = (text) => {
210
+ if (!text) return [];
211
+ // 匹配 @!protocol://resource @protocol://resource 格式
212
+ const matches = text.matchAll(/@!?([^:]+):\/\/([^\s\>\<\n]+)/g);
213
+ return Array.from(matches).map(match => ({
214
+ protocol: match[1],
215
+ resource: match[2]
216
+ }));
217
+ };
218
+
219
+ const addRef = (ref) => {
220
+ const key = `${ref.protocol}://${ref.resource}`;
221
+ if (!seenRefs.has(key)) {
222
+ seenRefs.add(key);
223
+ refs.push(ref);
224
+ }
225
+ };
226
+
227
+ // 从所有sections中提取引用
228
+ if (sections) {
229
+ Object.values(sections).forEach(section => {
230
+ extractFromText(section).forEach(addRef);
231
+ });
232
+ }
233
+
234
+ // 从原始内容中提取引用(确保不遗漏)
235
+ if (rawContent) {
236
+ extractFromText(rawContent).forEach(addRef);
237
+ }
238
+
239
+ return refs;
240
+ }
241
+
242
+ /**
243
+ * 加载单个依赖
244
+ * @param {Object} ref - 引用对象
245
+ * @returns {Promise<string>} 内容
246
+ */
247
+ async loadDependency(ref) {
248
+ try {
249
+ const resourceUrl = `@${ref.protocol}://${ref.resource}`;
250
+ const result = await this.resourceManager.loadResource(resourceUrl);
251
+
252
+ if (result && result.success && result.content) {
253
+ return result.content;
254
+ }
255
+
256
+ console.warn(chalk.yellow(`⚠️ 无法加载依赖: ${resourceUrl}`));
257
+ return null;
258
+ } catch (error) {
259
+ console.warn(chalk.yellow(`⚠️ 依赖加载失败: @${ref.protocol}://${ref.resource} - ${error.message}`));
260
+ return null;
261
+ }
262
+ }
263
+ }
264
+
265
+ /**
266
+ * 认知网络加载器 - 加载PromptX认知数据
267
+ */
268
+ class CognitionLoader {
269
+ constructor() {
270
+ this.basePath = path.join(os.homedir(), '.promptx', 'cognition');
271
+ }
272
+
273
+ /**
274
+ * 检查认知网络是否存在(不加载具体内容)
275
+ * @param {string} roleId - 角色ID
276
+ * @returns {Object} 认知网络存在状态
277
+ */
278
+ async checkNetworkExists(roleId) {
279
+ console.log(chalk.cyan(`🧠 检查认知网络状态: ${roleId}`));
280
+
281
+ try {
282
+ const networkFilePath = path.join(this.basePath, roleId, 'network.json');
283
+
284
+ // 仅检查文件是否存在
285
+ try {
286
+ await fs.access(networkFilePath);
287
+ console.log(chalk.green(`✅ 发现认知网络文件: ${roleId}`));
288
+ return {
289
+ hasNetwork: true,
290
+ networkPath: networkFilePath
291
+ };
292
+ } catch (error) {
293
+ console.log(chalk.gray(` 未找到认知网络文件: ${roleId}`));
294
+ return {
295
+ hasNetwork: false,
296
+ networkPath: networkFilePath
297
+ };
298
+ }
299
+
300
+ } catch (error) {
301
+ console.warn(chalk.yellow(`⚠️ 认知网络检查失败: ${error.message}`));
302
+ return {
303
+ hasNetwork: false,
304
+ networkPath: null,
305
+ error: error.message
306
+ };
307
+ }
308
+ }
309
+
310
+ }
311
+
312
+ /**
313
+ * 三层组装器 - 组装最终输出内容
314
+ */
315
+ class LayerAssembler {
316
+ /**
317
+ * 组装完整内容
318
+ * @param {Object} roleInfo - 角色信息
319
+ * @param {Object} dependencies - 依赖资源
320
+ * @param {Object} cognitionData - 认知数据
321
+ * @param {string} mode - 模式 (command|subagent)
322
+ * @returns {string} 组装后的内容
323
+ */
324
+ assembleContent(roleInfo, dependencies, cognitionData, mode = 'command') {
325
+ const parts = [];
326
+
327
+ // 标题部分
328
+ parts.push(`# 🧠 [Consciousness Prime] ${roleInfo.id}${mode === 'subagent' ? '专业助手' : '角色已激活'}`);
329
+ parts.push('');
330
+
331
+ // CognitionLayer - PromptX认知增强
332
+ parts.push('## 💭 PromptX认知增强');
333
+
334
+ if (cognitionData.hasNetwork) {
335
+ parts.push('🧠 **状态**: 该角色已建立经验网络');
336
+ parts.push('');
337
+ parts.push('🔧 **激活方式** (需要PromptX MCP服务器):');
338
+ parts.push(`- \`recall ${roleInfo.id}\` - 激活该角色的完整经验网络`);
339
+ parts.push(`- \`recall ${roleInfo.id} "具体问题"\` - 检索相关历史经验`);
340
+ parts.push(`- \`remember ${roleInfo.id} "新知识"\` - 将新经验加入角色记忆`);
341
+ parts.push('');
342
+ parts.push('💡 **说明**: 认知网络包含该角色的历史使用经验,通过recall工具动态激活');
343
+
344
+ } else {
345
+ parts.push('🌱 **状态**: 该角色尚未建立经验网络');
346
+ parts.push('');
347
+ parts.push('🚀 **开始使用**:');
348
+ parts.push('- 安装并配置PromptX MCP服务器');
349
+ parts.push(`- 使用 \`recall ${roleInfo.id}\` 开始建立认知网络`);
350
+ parts.push('- 随着使用逐步积累该角色的专业经验');
351
+ }
352
+
353
+ parts.push('');
354
+
355
+ // RoleLayer - 角色定义
356
+ // 如果有完整的 Markdown 内容(新格式),直接使用
357
+ if (roleInfo.sections.fullContent) {
358
+ parts.push('## 🎭 角色定义');
359
+ parts.push(this.cleanContent(roleInfo.sections.fullContent));
360
+ parts.push('');
361
+ } else {
362
+ // 旧格式:分别展示各个部分
363
+ if (roleInfo.sections.personality) {
364
+ parts.push('## 🎭 角色人格');
365
+ parts.push(this.cleanContent(roleInfo.sections.personality));
366
+ parts.push('');
367
+ }
368
+
369
+ if (roleInfo.sections.principle) {
370
+ parts.push('## 🔧 工作原则');
371
+ parts.push(this.cleanContent(roleInfo.sections.principle));
372
+ parts.push('');
373
+ }
374
+
375
+ if (roleInfo.sections.knowledge) {
376
+ parts.push('## 📚 专业知识');
377
+ parts.push(this.cleanContent(roleInfo.sections.knowledge));
378
+ parts.push('');
379
+ }
380
+ }
381
+
382
+ // 依赖资源
383
+ if (dependencies.thoughts.length > 0) {
384
+ parts.push('## 💡 思维模式');
385
+ dependencies.thoughts.forEach(thought => {
386
+ parts.push(`### ${thought.id}`);
387
+ parts.push(this.cleanContent(thought.content));
388
+ parts.push('');
389
+ });
390
+ }
391
+
392
+ if (dependencies.executions.length > 0) {
393
+ parts.push('## ⚡ 执行技能');
394
+ dependencies.executions.forEach(execution => {
395
+ parts.push(`### ${execution.id}`);
396
+ parts.push(this.cleanContent(execution.content));
397
+ parts.push('');
398
+ });
399
+ }
400
+
401
+ // StateLayer - 状态信息
402
+ parts.push('---');
403
+ parts.push('');
404
+
405
+ if (mode === 'command') {
406
+ parts.push(`🎉 ${roleInfo.id}角色激活完成!我现在以该角色身份为你服务。`);
407
+ } else {
408
+ parts.push('## 🤖 助手说明');
409
+ parts.push(`我是基于PromptX ${roleInfo.id}角色的专业AI助手。我会:`);
410
+ parts.push(`- 始终保持${roleInfo.id}的专业身份和思维模式`);
411
+ parts.push('- 利用完整的PromptX工具生态提供专业服务');
412
+ parts.push('- 在我们的对话过程中持续学习和记忆');
413
+ parts.push('');
414
+ parts.push('请告诉我你需要什么帮助?');
415
+ }
416
+
417
+ parts.push('');
418
+ parts.push('---');
419
+ parts.push('');
420
+ parts.push('💡 **可用的PromptX工具生态**:');
421
+ parts.push(`- \`recall ${roleInfo.id}\` - 激活该角色的历史经验网络`);
422
+ parts.push(`- \`remember ${roleInfo.id} "新体验"\` - 将新体验编织到角色记忆`);
423
+ parts.push('- `learn` - 学习新的资源和知识');
424
+ parts.push('- `toolx` - 执行专业工具');
425
+ parts.push('- 具体工具可用性取决于PromptX MCP服务器配置');
426
+ parts.push('');
427
+
428
+ if (mode === 'command') {
429
+ parts.push('现在开始处理用户需求。');
430
+ }
431
+
432
+ return parts.join('\n');
433
+ }
434
+
435
+ /**
436
+ * 清理内容格式
437
+ * @param {string} content - 原始内容
438
+ * @returns {string} 清理后的内容
439
+ */
440
+ cleanContent(content) {
441
+ if (!content) return '';
442
+
443
+ return content
444
+ // 移除PromptX资源引用标签(但保留引用内容的展开结果)
445
+ .replace(/<reference[^>]*>/g, '')
446
+ .replace(/<\/reference>/g, '')
447
+ // 移除@!protocol://resource引用行(因为依赖内容会单独展示)
448
+ .replace(/\s*@!?[^:]+:\/\/[^\s\>\<\n]+\s*/g, '')
449
+ // 清理多余空行
450
+ .replace(/\n\s*\n\s*\n/g, '\n\n')
451
+ // 移除开头结尾空白
452
+ .trim();
453
+ }
454
+ }
455
+
456
+ /**
457
+ * PromptX Action处理器主类
458
+ */
459
+ export class PromptXActionProcessor {
460
+ constructor() {
461
+ this.resourceManager = resource.getGlobalResourceManager();
462
+ this.roleLoader = new RoleLoader(this.resourceManager);
463
+ this.dependencyAnalyzer = new DependencyAnalyzer(this.resourceManager);
464
+ this.cognitionLoader = new CognitionLoader();
465
+ this.layerAssembler = new LayerAssembler();
466
+ }
467
+
468
+ /**
469
+ * 执行完整的PromptX Action流程
470
+ * @param {string} roleId - 角色ID
471
+ * @param {string} mode - 模式 (command|subagent)
472
+ * @returns {string} 处理后的内容
473
+ */
474
+ async processRole(roleId, mode = 'command') {
475
+ try {
476
+ console.log(chalk.blue(`\n🎭 开始执行 ${roleId} 的 PromptX Action 流程 (${mode} 模式)`));
477
+
478
+ // 1. 加载角色定义
479
+ const roleInfo = await this.roleLoader.loadRole(roleId);
480
+
481
+ // 2. 分析依赖资源
482
+ const dependencies = await this.dependencyAnalyzer.analyzeDependencies(roleInfo);
483
+
484
+ // 3. 检查认知网络存在性
485
+ const cognitionData = await this.cognitionLoader.checkNetworkExists(roleId);
486
+
487
+ // 4. 三层组装
488
+ const content = this.layerAssembler.assembleContent(roleInfo, dependencies, cognitionData, mode);
489
+
490
+ console.log(chalk.green(`✅ PromptX Action 流程完成!`));
491
+
492
+ return content;
493
+
494
+ } catch (error) {
495
+ console.error(chalk.red(`❌ PromptX Action 流程失败: ${error.message}`));
496
+ throw error;
497
+ }
498
+ }
432
499
  }