install.js 9.6 KB

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