install.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const os = require('os');
  4. const path = require('path');
  5. const { spawnSync } = require('child_process');
  6. const ROOT = __dirname;
  7. const EXCLUDED_ROOTS = new Set(['.claude', '.git', '.github', '.playwright-cli', '.vscode', 'coverage', 'dist', 'node_modules', 'output', 'outputs']);
  8. const EXCLUDED_FILES = new Set(['.env', '.env.local', '.npmrc', 'poll_reply.log', 'poll_state.json']);
  9. function usage() {
  10. return [
  11. '企业微信 Claude Code 技能包安装器',
  12. '',
  13. '用法:',
  14. ' fmode-qiwei --check',
  15. ' fmode-qiwei workspace [客户项目目录]',
  16. ' fmode-qiwei workspace [客户项目目录] --smoke',
  17. ' fmode-qiwei preview [客户项目目录] [--no-open] [--port 4320]',
  18. '',
  19. 'workspace 模式会写入 .claude/plugins、.claude/skills 和项目级 .mcp.json。',
  20. 'preview 模式会启动工作台、检查当前状态并打开浏览器。',
  21. ].join('\n');
  22. }
  23. function readJson(filePath, fallback = {}) {
  24. try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); }
  25. catch { return fallback; }
  26. }
  27. function writeJson(filePath, value) {
  28. fs.mkdirSync(path.dirname(filePath), { recursive: true });
  29. fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
  30. }
  31. function assertRequiredFiles() {
  32. const required = [
  33. 'package.json',
  34. '.claude-plugin/plugin.json',
  35. 'skill-package-manifest.json',
  36. 'mcp/src/server.js',
  37. 'runtime/callback-service/src/index.mjs',
  38. 'qiwei.runtime.config.example.mjs',
  39. 'skills/qiwei-dashboard/SKILL.md',
  40. 'skills/qiwei-goal-management/SKILL.md',
  41. 'skills/qiwei-real-estate-auto-reply/SKILL.md',
  42. ];
  43. for (const relative of required) {
  44. if (!fs.existsSync(path.join(ROOT, relative))) throw new Error(`缺少安装文件:${relative}`);
  45. }
  46. const [major, minor] = process.versions.node.split('.').map(Number);
  47. if (!Number.isFinite(major) || major < 22 || (major === 22 && minor < 5)) {
  48. throw new Error(`需要 Node.js 22.5+(使用内置 node:sqlite),当前版本 ${process.version}`);
  49. }
  50. }
  51. function assertInside(target, parent) {
  52. const resolvedTarget = path.resolve(target);
  53. const resolvedParent = path.resolve(parent);
  54. const relative = path.relative(resolvedParent, resolvedTarget);
  55. if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
  56. throw new Error(`拒绝操作不安全路径:${resolvedTarget}`);
  57. }
  58. }
  59. function copyFilter(source) {
  60. const relative = path.relative(ROOT, source);
  61. if (!relative) return true;
  62. const parts = relative.split(path.sep);
  63. if (EXCLUDED_ROOTS.has(parts[0])) return false;
  64. if (EXCLUDED_FILES.has(path.basename(source))) return false;
  65. if (/\.(?:tgz|zip)$/i.test(source)) return false;
  66. if (/^\.env\..+/i.test(path.basename(source)) && path.basename(source) !== '.env.example') return false;
  67. return true;
  68. }
  69. function copyTree(source, destination, filter = () => true) {
  70. if (!filter(source)) return;
  71. const stat = fs.statSync(source);
  72. if (stat.isDirectory()) {
  73. fs.mkdirSync(destination, { recursive: true });
  74. for (const entry of fs.readdirSync(source)) {
  75. copyTree(path.join(source, entry), path.join(destination, entry), filter);
  76. }
  77. return;
  78. }
  79. fs.mkdirSync(path.dirname(destination), { recursive: true });
  80. fs.copyFileSync(source, destination);
  81. }
  82. function run(command, args, cwd, options = {}) {
  83. const useCmd = process.platform === 'win32' && command === 'npm';
  84. const result = spawnSync(useCmd ? 'cmd.exe' : command, useCmd ? ['/d', '/s', '/c', 'npm', ...args] : args, {
  85. cwd,
  86. env: { ...process.env, ...(options.env || {}) },
  87. stdio: 'inherit',
  88. encoding: 'utf8',
  89. windowsHide: true,
  90. });
  91. if (result.status !== 0) throw new Error(`${command} ${args.join(' ')} 执行失败`);
  92. }
  93. function installWorkspace(targetInput, options = {}) {
  94. const target = path.resolve(targetInput || process.cwd());
  95. fs.mkdirSync(target, { recursive: true });
  96. const pluginsRoot = path.join(target, '.claude', 'plugins');
  97. const skillsRoot = path.join(target, '.claude', 'skills');
  98. const pluginDir = path.join(pluginsRoot, 'qiwei-assistant');
  99. assertInside(pluginDir, pluginsRoot);
  100. fs.rmSync(pluginDir, { recursive: true, force: true });
  101. fs.mkdirSync(pluginDir, { recursive: true });
  102. copyTree(ROOT, pluginDir, copyFilter);
  103. for (const entry of fs.readdirSync(path.join(ROOT, 'skills'), { withFileTypes: true })) {
  104. if (!entry.isDirectory() || !fs.existsSync(path.join(ROOT, 'skills', entry.name, 'SKILL.md'))) continue;
  105. const destination = path.join(skillsRoot, entry.name);
  106. assertInside(destination, skillsRoot);
  107. fs.rmSync(destination, { recursive: true, force: true });
  108. fs.mkdirSync(path.dirname(destination), { recursive: true });
  109. copyTree(path.join(ROOT, 'skills', entry.name), destination);
  110. }
  111. const mcpPath = path.join(target, '.mcp.json');
  112. const runtimeConfigPath = path.join(target, 'qiwei.runtime.config.mjs');
  113. if (!fs.existsSync(runtimeConfigPath)) {
  114. fs.copyFileSync(path.join(ROOT, 'qiwei.runtime.config.example.mjs'), runtimeConfigPath);
  115. }
  116. const mcp = readJson(mcpPath, { mcpServers: {} });
  117. mcp.mcpServers ||= {};
  118. mcp.mcpServers['qiwei-assistant'] = {
  119. command: process.execPath,
  120. args: [path.join(pluginDir, 'mcp', 'src', 'server.js')],
  121. cwd: target,
  122. env: {
  123. QIWEI_WORKSPACE_ROOT: target,
  124. QIWEI_OUTPUTS_DIR: path.join(target, 'outputs'),
  125. CLAUDE_CODE_WORKDIR: target,
  126. QIWEI_RUNTIME_CONFIG: runtimeConfigPath,
  127. },
  128. };
  129. writeJson(mcpPath, mcp);
  130. if (!options.skipInstall) run('npm', ['install', '--omit=dev', '--ignore-scripts'], pluginDir);
  131. if (options.smoke) {
  132. const smokeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-install-smoke-'));
  133. const smokeOutputs = path.join(smokeRoot, 'outputs');
  134. const smokeEnv = {
  135. QIWEI_OUTPUTS_DIR: smokeOutputs,
  136. QIWEI_AGENT_DB_PATH: path.join(smokeOutputs, 'messages', 'agent-workbench.db'),
  137. };
  138. try {
  139. run('npm', ['run', 'check'], pluginDir, { env: smokeEnv });
  140. run('npm', ['run', 'agent:smoke'], pluginDir, { env: smokeEnv });
  141. run('npm', ['run', 'goal:smoke'], pluginDir, { env: smokeEnv });
  142. } finally {
  143. fs.rmSync(smokeRoot, { recursive: true, force: true });
  144. }
  145. }
  146. process.stdout.write([
  147. '',
  148. '企业微信技能包已安装到客户项目:',
  149. ` ${target}`,
  150. '',
  151. '下一步:',
  152. ' 1. 在 Fmode Studio 中打开该项目。',
  153. ' 2. 在 Claude Code 中说“启动并预览企微助手”。',
  154. ` 3. 也可以在项目终端运行:node "${path.join(pluginDir, 'install.js')}" preview "${target}"`,
  155. ' 4. 页面会依次提示登录、席位、企微在线、白名单和监听状态。',
  156. ' 5. 需要审阅客户会话时,在项目终端运行 npm --prefix ".claude/plugins/qiwei-assistant" run agent:session:list。',
  157. '',
  158. ].join('\n'));
  159. }
  160. function previewWorkspace(targetInput, args = []) {
  161. const target = path.resolve(targetInput || process.cwd());
  162. const installedRoot = path.join(target, '.claude', 'plugins', 'qiwei-assistant');
  163. const runtimeRoot = fs.existsSync(path.join(installedRoot, 'scripts', 'preview-dashboard.js')) ? installedRoot : ROOT;
  164. const previewScript = path.join(runtimeRoot, 'scripts', 'preview-dashboard.js');
  165. if (!fs.existsSync(previewScript)) throw new Error('技能包缺少启动预览脚本,请重新安装或升级技能包');
  166. run(process.execPath, [previewScript, ...args], target, {
  167. env: {
  168. QIWEI_WORKSPACE_ROOT: target,
  169. QIWEI_OUTPUTS_DIR: path.join(target, 'outputs'),
  170. CLAUDE_CODE_WORKDIR: target,
  171. },
  172. });
  173. }
  174. function main() {
  175. const args = process.argv.slice(2);
  176. if (args.includes('--help') || args.includes('-h')) {
  177. process.stdout.write(`${usage()}\n`);
  178. return;
  179. }
  180. assertRequiredFiles();
  181. if (args.includes('--check') || !args.length) {
  182. process.stdout.write('技能包结构检查通过。\n');
  183. if (!args.length) process.stdout.write(`${usage()}\n`);
  184. return;
  185. }
  186. if (args[0] === 'preview') {
  187. const target = args[1] && !args[1].startsWith('--') ? args[1] : process.cwd();
  188. const previewArgs = args.slice(args[1] && !args[1].startsWith('--') ? 2 : 1);
  189. previewWorkspace(target, previewArgs);
  190. return;
  191. }
  192. if (args[0] !== 'workspace') throw new Error('支持 workspace 安装或 preview 启动预览模式');
  193. const target = args[1] && !args[1].startsWith('--') ? args[1] : process.cwd();
  194. installWorkspace(target, {
  195. smoke: args.includes('--smoke'),
  196. skipInstall: args.includes('--skip-install'),
  197. });
  198. }
  199. try { main(); }
  200. catch (error) {
  201. process.stderr.write(`安装失败:${error.message}\n`);
  202. process.exit(1);
  203. }