px2cc 1.0.7

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.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # Px2CC
2
+
3
+ **PromptX to Claude Code** - 一个简洁的CLI工具,快速将PromptX角色安装到Claude Code中。
4
+
5
+ ## 功能特性
6
+
7
+ - 🚀 快速安装PromptX角色到Claude Code
8
+ - 🎭 动态获取所有可用的系统角色和用户角色
9
+ - 🤖 支持安装为Claude Code Subagents (通过自然语言提及调用)
10
+ - ⚙️ 支持安装为Claude Code Commands (通过 `/command` 调用)
11
+ - 🎨 友好的交互式界面
12
+ - 📁 自动创建和管理 `.claude` 目录结构
13
+
14
+ ## 安装
15
+
16
+ ### 方式一:全局安装
17
+ ```bash
18
+ npm install -g px2cc
19
+ px2cc
20
+ ```
21
+
22
+ ### 方式二:npx 直接运行(推荐)
23
+ ```bash
24
+ npx px2cc
25
+ ```
26
+
27
+ 无需安装,一条命令直接运行!
28
+
29
+ 然后按照交互式提示:
30
+ 1. 选择要安装的PromptX角色
31
+ 2. 选择安装类型(Agent 或 Command)
32
+ 3. 确认安装
33
+
34
+ ## 安装类型
35
+
36
+ ### Subagent 模式
37
+ - 安装到 `.claude/agents/` 目录
38
+ - 通过自然语言提及调用: `Use the <角色名>-agent subagent to [任务]`
39
+
40
+ ### Command 模式
41
+ - 安装到 `.claude/commands/` 目录
42
+ - 通过 `/<角色名>` 在Claude Code中调用
43
+
44
+ ## 角色类型
45
+
46
+ - **系统角色** 📦 - PromptX内置的专业角色
47
+ - **用户角色** 👤 - 用户自定义创建的角色
48
+
49
+ ## 系统要求
50
+
51
+ - Node.js >= 16.0.0
52
+ - Claude Code
53
+ - PromptX账户(包含可用角色)
54
+
55
+ ## 示例
56
+
57
+ ```bash
58
+ $ px2cc
59
+
60
+ 🚀 PromptX CLI - Claude Code 角色安装器
61
+ 快速将PromptX角色集成到Claude Code中
62
+
63
+ 🔍 正在从PromptX系统加载角色...
64
+
65
+ ✅ 加载完成!
66
+ 📊 发现 5 个系统角色,9 个用户角色
67
+
68
+ ? 请选择要安装的PromptX角色: assistant (系统角色)
69
+ ? 安装 assistant 为: Agent - 通过提及"assistant-agent subagent"调用
70
+ ? 确认安装到Claude Code? Yes
71
+
72
+ 📖 加载 assistant 角色定义...
73
+ 🔧 生成 assistant agent文件...
74
+
75
+ ✅ 角色安装完成!
76
+
77
+ 📄 生成的文件:
78
+ - .claude/agents/assistant-agent.md
79
+
80
+ 🎉 现在你可以在Claude Code中使用:
81
+ Use the assistant-agent subagent to help with my task
82
+ Have the assistant-agent subagent review my code
83
+
84
+ 💡 提示: 重启Claude Code以确保新配置生效
85
+ ```
86
+
87
+ ## 许可证
88
+
89
+ MIT
90
+
91
+ ## 作者
92
+
93
+ PromptX Bridge Team
package/bin.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Px2CC 启动器 - 通用版本
5
+ * 直接导入cli.js,跨平台兼容
6
+ */
7
+
8
+ // 设置环境变量来抑制PromptX内部日志
9
+ process.env.LOG_LEVEL = 'silent';
10
+
11
+ // 修改process.argv让cli.js以为自己是主模块
12
+ import { fileURLToPath } from 'url';
13
+ const cliJsPath = fileURLToPath(new URL('cli.js', import.meta.url));
14
+ process.argv[1] = cliJsPath;
15
+
16
+ // 导入并执行cli.js
17
+ import('./cli.js');
package/cli.js ADDED
@@ -0,0 +1,382 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * PromptX CLI - 使用 @promptx/core 动态获取角色信息
5
+ * 注意:此文件应通过 promptx-cli wrapper 脚本运行以过滤内部日志
6
+ */
7
+
8
+ import { resource } from '@promptx/core';
9
+ import { ClaudeCodeBuilder } from 'claude-code-builder';
10
+ import { PromptXActionProcessor } from './src/PromptXActionProcessor.js';
11
+ import inquirer from 'inquirer';
12
+ import chalk from 'chalk';
13
+ import path from 'path';
14
+ import fs from 'fs';
15
+ import { execSync } from 'child_process';
16
+
17
+ // 注意:原有的parsePromptXRole函数已被PromptXActionProcessor替代
18
+ // 新的处理器实现完整的PromptX Action流程,包括:
19
+ // 1. RoleLoader - 加载角色定义
20
+ // 2. DependencyAnalyzer - 分析资源依赖
21
+ // 3. CognitionLoader - 加载认知网络
22
+ // 4. LayerAssembler - 三层内容组装
23
+
24
+ // 发现MCP服务器
25
+ async function discoverMCPServers() {
26
+ const servers = {
27
+ defaultTools: ['Read', 'Write', 'Edit', 'Bash'],
28
+ mcpServers: []
29
+ };
30
+
31
+ try {
32
+ console.log(chalk.gray(' 检查MCP服务器状态(可能需要一些时间)...'));
33
+ // 使用claude mcp list获取所有MCP服务器(增加超时时间到60秒)
34
+ const mcpOutput = execSync('claude mcp list', {
35
+ encoding: 'utf8',
36
+ timeout: 60000, // 增加到60秒
37
+ stdio: 'pipe' // 确保错误输出被捕获
38
+ });
39
+
40
+ // 解析输出,提取服务器信息
41
+ const lines = mcpOutput.split('\n');
42
+
43
+ for (const line of lines) {
44
+ const trimmedLine = line.trim();
45
+ // 匹配服务器名称(格式:serverName: command - status)
46
+ const match = trimmedLine.match(/^([^:]+):\s+(.+)\s+-\s+(✓|✗)\s+(.*)$/);
47
+ if (match && !trimmedLine.includes('Checking MCP server health')) {
48
+ const [, name, command, status, statusText] = match;
49
+ servers.mcpServers.push({
50
+ name: name.trim(),
51
+ command: command.trim(),
52
+ connected: status === '✓',
53
+ status: statusText.trim()
54
+ });
55
+ }
56
+ }
57
+
58
+ console.log(chalk.green(`✅ 发现 ${servers.mcpServers.length} 个MCP服务器`));
59
+
60
+ } catch (error) {
61
+ if (error.code === 'ETIMEDOUT') {
62
+ console.error(chalk.yellow('⚠️ MCP服务器检查超时,将继续安装(只使用默认工具)'));
63
+ console.error(chalk.gray(' 如需使用MCP工具,请检查网络连接或使用 --skip-mcp 参数'));
64
+ } else {
65
+ console.error(chalk.yellow('⚠️ 无法获取MCP服务器列表,将继续安装(只使用默认工具)'));
66
+ console.error(chalk.gray(` 原因: ${error.message}`));
67
+ }
68
+ // 不再抛出错误,而是继续执行,不使用MCP服务器
69
+ console.log(chalk.gray(' 将继承所有可用工具(Claude Code默认行为)'));
70
+ return servers;
71
+ }
72
+
73
+ return servers;
74
+ }
75
+
76
+ // 显示MCP服务器选择界面
77
+ async function selectMCPServers(roleName, availableServers) {
78
+ // 如果没有MCP服务器,直接返回undefined(继承所有工具)
79
+ if (availableServers.mcpServers.length === 0) {
80
+ console.log(chalk.gray(' 没有发现MCP服务器,将继承所有可用工具'));
81
+ return undefined;
82
+ }
83
+
84
+ // 只显示MCP服务器选择
85
+ const choices = [];
86
+
87
+ for (const server of availableServers.mcpServers) {
88
+ const statusIcon = server.connected ? '✓' : '✗';
89
+ const statusColor = server.connected ? chalk.green : chalk.red;
90
+ choices.push({
91
+ name: `${statusColor(statusIcon)} ${server.name} ${chalk.gray(`(${server.status})`)}`,
92
+ value: server.name,
93
+ checked: false, // 默认不选中任何MCP服务器
94
+ disabled: !server.connected ? '(未连接)' : false
95
+ });
96
+ }
97
+
98
+ console.log(chalk.blue('\n🔧 默认工具(自动包含):'), availableServers.defaultTools.join(', '));
99
+
100
+ const answer = await inquirer.prompt([{
101
+ type: 'checkbox',
102
+ name: 'selectedServers',
103
+ message: `为 ${roleName} 选择额外的MCP服务器(可选):`,
104
+ choices: choices
105
+ }]);
106
+
107
+ // 处理选中的MCP服务器
108
+ const selectedMCPServers = answer.selectedServers || [];
109
+
110
+ if (selectedMCPServers.length === 0) {
111
+ console.log(chalk.gray(' 将继承所有可用工具(Claude Code默认行为)'));
112
+ return undefined; // Claude Code会继承所有工具
113
+ }
114
+
115
+ // 如果选择了特定服务器,只包含默认工具+选中服务器的工具
116
+ const selectedTools = availableServers.defaultTools.slice();
117
+ for (const serverName of selectedMCPServers) {
118
+ // 添加该服务器的所有工具(使用通配符或具体工具名)
119
+ selectedTools.push(`mcp__${serverName}__*`);
120
+ }
121
+
122
+ console.log(chalk.blue(` 已选择 ${selectedMCPServers.length} 个MCP服务器: ${selectedMCPServers.join(', ')}`));
123
+ return selectedTools;
124
+ }
125
+
126
+ // 获取PromptX角色
127
+ async function getAllRoles() {
128
+ try {
129
+ const manager = resource.getGlobalResourceManager();
130
+ await manager.initializeWithNewArchitecture();
131
+
132
+ const roleResources = manager.registryData.getResourcesByProtocol('role');
133
+ const systemRoles = roleResources.filter(r => r.source === 'package');
134
+ const userRoles = roleResources.filter(r => r.source === 'user');
135
+
136
+ return { systemRoles, userRoles, manager };
137
+ } catch (error) {
138
+ throw new Error(`获取PromptX角色失败: ${error.message}`);
139
+ }
140
+ }
141
+
142
+ // 显示欢迎界面
143
+ function showWelcome() {
144
+ console.clear();
145
+ console.log(chalk.blue.bold('🚀 PromptX CLI - Claude Code 角色安装器'));
146
+ console.log(chalk.gray(' 快速将PromptX角色集成到Claude Code中\n'));
147
+ }
148
+
149
+ // 显示角色选择菜单
150
+ async function showRoleMenu(systemRoles, userRoles, availableServers) {
151
+ const choices = [
152
+ ...systemRoles.map(role => ({
153
+ name: `📦 ${role.id} ${chalk.gray('(系统角色)')}`,
154
+ value: { role: role.id, source: 'package' },
155
+ short: role.id
156
+ })),
157
+ new inquirer.Separator(chalk.gray('─── 用户角色 ───')),
158
+ ...userRoles.map(role => ({
159
+ name: `👤 ${role.id} ${chalk.gray('(用户角色)')}`,
160
+ value: { role: role.id, source: 'user' },
161
+ short: role.id
162
+ }))
163
+ ];
164
+
165
+ const roleAnswer = await inquirer.prompt([
166
+ {
167
+ type: 'list',
168
+ name: 'selectedRole',
169
+ message: '请选择要安装的PromptX角色:',
170
+ choices: choices,
171
+ pageSize: 15
172
+ }
173
+ ]);
174
+
175
+ // 选择安装类型
176
+ const typeAnswer = await inquirer.prompt([
177
+ {
178
+ type: 'list',
179
+ name: 'installType',
180
+ message: `安装 ${roleAnswer.selectedRole.role} 为:`,
181
+ choices: [
182
+ {
183
+ name: `🤖 Agent - 通过提及"${roleAnswer.selectedRole.role}-agent subagent"调用`,
184
+ value: 'agents',
185
+ short: 'Agent'
186
+ },
187
+ {
188
+ name: `⚙️ Command - 通过 /${roleAnswer.selectedRole.role} 调用`,
189
+ value: 'commands',
190
+ short: 'Command'
191
+ }
192
+ ]
193
+ },
194
+ {
195
+ type: 'confirm',
196
+ name: 'confirm',
197
+ message: '确认安装到Claude Code?',
198
+ default: true
199
+ }
200
+ ]);
201
+
202
+ let selectedTools = [];
203
+ if (typeAnswer.confirm) {
204
+ // 选择MCP服务器和工具
205
+ selectedTools = await selectMCPServers(roleAnswer.selectedRole.role, availableServers);
206
+ }
207
+
208
+ return {
209
+ selectedRole: roleAnswer.selectedRole,
210
+ installType: typeAnswer.installType,
211
+ confirm: typeAnswer.confirm,
212
+ selectedTools: selectedTools
213
+ };
214
+ }
215
+
216
+ // 检查当前目录
217
+ function checkDirectory() {
218
+ const currentDir = process.cwd();
219
+ const claudeDir = path.join(currentDir, '.claude');
220
+
221
+ if (!fs.existsSync(claudeDir)) {
222
+ console.log(chalk.yellow('📁 创建 .claude 目录...'));
223
+ fs.mkdirSync(claudeDir, { recursive: true });
224
+ fs.mkdirSync(path.join(claudeDir, 'agents'), { recursive: true });
225
+ fs.mkdirSync(path.join(claudeDir, 'commands'), { recursive: true });
226
+ }
227
+
228
+ return claudeDir;
229
+ }
230
+
231
+ // 安装角色
232
+ async function installRole(selectedRole, installType, claudeDir, manager, selectedTools) {
233
+ const roleName = selectedRole.role;
234
+ const results = {};
235
+
236
+ try {
237
+ // 使用新的PromptXActionProcessor执行完整的action流程
238
+ const processor = new PromptXActionProcessor();
239
+ const mode = installType === 'agents' ? 'subagent' : 'command';
240
+ const processedContent = await processor.processRole(roleName, mode);
241
+
242
+ // 根据安装模式创建相应文件
243
+ if (installType === 'agents') {
244
+ console.log(chalk.cyan(`🔧 生成 ${roleName} subagent文件...`));
245
+ const agentConfig = {
246
+ name: `${roleName}-agent`,
247
+ description: `基于PromptX ${roleName}角色的专业AI助手 - 完整action实现`,
248
+ content: processedContent,
249
+ targetDir: claudeDir
250
+ };
251
+
252
+ // 设置工具配置 - 如果用户没有选择特定工具,则继承所有可用工具
253
+ if (selectedTools) {
254
+ agentConfig.tools = selectedTools;
255
+ }
256
+ // 如果没有选择特定工具,Claude Code会自动继承所有可用工具
257
+
258
+ const subagentResult = await ClaudeCodeBuilder.createSubagent(agentConfig);
259
+
260
+ if (!subagentResult.success) {
261
+ throw new Error(`创建Subagent失败: ${subagentResult.error}`);
262
+ }
263
+ results.agentFile = `${roleName}-agent.md`;
264
+ results.usage = `Use the ${roleName}-agent subagent to [任务描述]`;
265
+ }
266
+
267
+ if (installType === 'commands') {
268
+ console.log(chalk.cyan(`📋 生成 ${roleName} command文件...`));
269
+
270
+ const commandConfig = {
271
+ name: roleName,
272
+ description: `基于PromptX ${roleName}角色的专业助手 - 完整action实现`,
273
+ content: processedContent,
274
+ targetDir: claudeDir
275
+ };
276
+
277
+ // 设置工具配置 - 如果用户没有选择特定工具,则继承所有可用工具
278
+ if (selectedTools) {
279
+ commandConfig.allowedTools = selectedTools;
280
+ }
281
+ // 如果没有选择特定工具,Claude Code会自动继承所有可用工具
282
+
283
+ const commandResult = await ClaudeCodeBuilder.createCommand(commandConfig);
284
+
285
+ if (!commandResult.success) {
286
+ throw new Error(`创建Command失败: ${commandResult.error}`);
287
+ }
288
+ results.commandFile = `${roleName}.md`;
289
+ results.usage = `/${roleName}`;
290
+ }
291
+
292
+ results.roleName = roleName;
293
+ results.installType = installType;
294
+ return results;
295
+
296
+ } catch (error) {
297
+ throw new Error(`安装角色失败: ${error.message}`);
298
+ }
299
+ }
300
+
301
+ // 主程序入口
302
+ async function main() {
303
+ try {
304
+ showWelcome();
305
+
306
+ // 检查是否跳过MCP发现(用于快速测试)
307
+ const skipMCP = process.argv.includes('--skip-mcp');
308
+
309
+ let availableServers;
310
+ if (skipMCP) {
311
+ console.log(chalk.yellow('⚠️ 跳过MCP发现(测试模式)'));
312
+ availableServers = {
313
+ defaultTools: ['Read', 'Write', 'Edit', 'Bash'],
314
+ mcpServers: []
315
+ };
316
+ } else {
317
+ // 发现MCP服务器
318
+ console.log(chalk.cyan('🔍 正在发现MCP服务器...\n'));
319
+ try {
320
+ availableServers = await discoverMCPServers();
321
+ } catch (error) {
322
+ console.error(chalk.yellow('⚠️ MCP服务器发现失败,使用默认配置'));
323
+ availableServers = {
324
+ defaultTools: ['Read', 'Write', 'Edit', 'Bash'],
325
+ mcpServers: []
326
+ };
327
+ }
328
+ }
329
+
330
+ // 加载角色
331
+ console.log(chalk.cyan('🔍 正在从PromptX系统加载角色...\n'));
332
+ const { systemRoles, userRoles, manager } = await getAllRoles();
333
+
334
+ console.log(chalk.green('✅ 加载完成!'));
335
+ console.log(`📊 发现 ${chalk.bold(systemRoles.length)} 个系统角色,${chalk.bold(userRoles.length)} 个用户角色\n`);
336
+
337
+ // 显示角色选择
338
+ const { selectedRole, installType, confirm, selectedTools } = await showRoleMenu(systemRoles, userRoles, availableServers);
339
+
340
+ if (!confirm) {
341
+ console.log(chalk.yellow('\n👋 安装已取消'));
342
+ return;
343
+ }
344
+
345
+ // 检查目录
346
+ const claudeDir = checkDirectory();
347
+
348
+ console.log(chalk.blue(`\n🎭 开始安装角色: ${selectedRole.role} (${installType})`));
349
+
350
+ // 安装角色
351
+ const result = await installRole(selectedRole, installType, claudeDir, manager, selectedTools);
352
+
353
+ console.log(chalk.green.bold('\n✅ 角色安装完成!'));
354
+ console.log(`\n📄 生成的文件:`);
355
+
356
+ if (result.agentFile) {
357
+ console.log(` - ${chalk.gray('.claude/agents/')}${chalk.white(result.agentFile)}`);
358
+ }
359
+ if (result.commandFile) {
360
+ console.log(` - ${chalk.gray('.claude/commands/')}${chalk.white(result.commandFile)}`);
361
+ }
362
+
363
+ console.log(chalk.magenta(`\n🎉 现在你可以在Claude Code中使用:`));
364
+ if (result.usage) {
365
+ console.log(chalk.yellow(` ${result.usage}`));
366
+ }
367
+
368
+ console.log(chalk.gray(`\n💡 提示: 重启Claude Code以确保新配置生效`));
369
+
370
+ } catch (error) {
371
+ console.error(chalk.red('❌ 安装失败:'), error.message);
372
+ process.exit(1);
373
+ }
374
+ }
375
+
376
+ // 运行主程序
377
+ if (import.meta.url === new URL(process.argv[1], 'file:').href) {
378
+ main().catch(error => {
379
+ console.error(chalk.red('❌ 程序异常:'), error.message);
380
+ process.exit(1);
381
+ });
382
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "px2cc",
3
+ "version": "1.0.7",
4
+ "description": "CLI tool that implements complete PromptX Action flow in Claude Code - role activation, dependency loading, cognition networks & memory systems",
5
+ "main": "cli.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "px2cc": "./bin.js"
9
+ },
10
+ "scripts": {
11
+ "start": "./promptx-cli",
12
+ "test": "node test.js"
13
+ },
14
+ "dependencies": {
15
+ "@promptx/core": "^1.13.0",
16
+ "@promptx/logger": "^1.13.0",
17
+ "@promptx/resource": "^1.13.0",
18
+ "claude-code-builder": "^1.0.0",
19
+ "inquirer": "^9.2.0",
20
+ "chalk": "^5.3.0"
21
+ },
22
+ "files": [
23
+ "cli.js",
24
+ "bin.js",
25
+ "src/",
26
+ "README.md",
27
+ "package.json"
28
+ ],
29
+ "keywords": [
30
+ "promptx",
31
+ "claude-code",
32
+ "cli",
33
+ "ai",
34
+ "roles",
35
+ "agents",
36
+ "commands"
37
+ ],
38
+ "author": "PromptX Bridge Team",
39
+ "license": "MIT",
40
+ "engines": {
41
+ "node": ">=16.0.0"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/promptx/px2cc"
46
+ },
47
+ "homepage": "https://github.com/promptx/px2cc#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/promptx/px2cc/issues"
50
+ }
51
+ }
@@ -0,0 +1,432 @@
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
+ }
432
+ }