refresh-container-skills.mjs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env node
  2. /**
  3. * 按 container-skill-manifest.json 刷新 R730 上容器的技能(2026-12-03)。
  4. *
  5. * 与开通链路共用同一份清单:provision.sh 给新容器装技能,本脚本给存量容器补/替换。
  6. * 新增或替换技能只改清单,不改这里。
  7. *
  8. * 用法:
  9. * node scripts/refresh-container-skills.mjs --list # 只列清单与计划
  10. * node scripts/refresh-container-skills.mjs --dry-run # 对全部容器演算
  11. * node scripts/refresh-container-skills.mjs --containers a,b # 指定容器
  12. * node scripts/refresh-container-skills.mjs --all --apply # 真正下发(需显式 --apply)
  13. * node scripts/refresh-container-skills.mjs --containers x --apply --restart-gateway
  14. * node scripts/refresh-container-skills.mjs --all --from-repo --apply # 让容器自己从仓库拉
  15. *
  16. * 两种下发方式:
  17. * (默认)从宿主仓库推送 —— 技能内容随本仓库走,容器不需要外网
  18. * --from-repo —— 只发一条拉取指令,容器自己 git clone skills-storage
  19. * (2026-12-03 实测容器可访问 git.fmode.cn,不可访问 github.com)
  20. *
  21. * 约束(容器扩展铁律):只往 /opt/data/skills/<scope>/<name>/ 写文件,不碰 /opt/hermes 源码。
  22. */
  23. import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
  24. import { execFileSync } from 'node:child_process';
  25. import { resolve, basename } from 'node:path';
  26. const ROOT = resolve(new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
  27. const MANIFEST = resolve(ROOT, 'cloud/skills/container-skill-manifest.json');
  28. const R730 = resolve(ROOT, '.local-backup/skill-lock-20261201/r730.py');
  29. const argv = process.argv.slice(2);
  30. const has = (f) => argv.includes(f);
  31. const val = (f) => {
  32. const i = argv.indexOf(f);
  33. return i >= 0 ? argv[i + 1] : undefined;
  34. };
  35. const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
  36. const enabled = (manifest.skills ?? []).filter((s) => !s.disabled);
  37. if (enabled.length === 0) {
  38. console.error('清单里没有可下发的技能');
  39. process.exit(1);
  40. }
  41. /** 读取技能文件内容(base64,避免 shell 转义问题) */
  42. function readSkillFiles(skill) {
  43. /* source 既可以是字符串路径,也可以是 {type:'repo', fallback:'...'}(2026-12-03 v2 清单) */
  44. const spec = skill.source;
  45. const rel = typeof spec === 'string' ? spec : spec?.fallback;
  46. if (!rel) throw new Error(`技能 ${skill.name} 只声明了远程源,没有 fallback;请用 --from-repo`);
  47. const srcDir = resolve(ROOT, rel);
  48. const out = {};
  49. for (const f of skill.files) {
  50. const p = resolve(srcDir, f);
  51. try {
  52. out[f] = readFileSync(p).toString('base64');
  53. } catch {
  54. throw new Error(`技能 ${skill.name} 缺少文件: ${p}`);
  55. }
  56. }
  57. return out;
  58. }
  59. /** 生成在 R730 上执行的 shell:把技能写进指定容器 */
  60. /** 容器内自己从 skills-storage 拉技能(2026-12-03 v2) */
  61. function buildRepoScript(containers, opts) {
  62. const repo = Object.values(manifest.repos ?? {})[0];
  63. if (!repo) throw new Error('清单里没有 repos 定义,无法 --from-repo');
  64. const lines = ['set -e'];
  65. for (const c of containers) {
  66. lines.push(`echo "[CONTAINER] ${c}"`);
  67. lines.push(`docker exec ${c} sh -c 'rm -rf /tmp/skills-storage && git clone --depth 1 ${repo.url} /tmp/skills-storage 2>&1 | tail -3'`);
  68. lines.push(`docker exec ${c} sh -c 'mkdir -p ${repo.containerPath} && cp -r /tmp/skills-storage/${repo.repoSubdir}/* ${repo.containerPath}/ && chown -R 10000:10000 ${repo.containerPath} && chmod 0755 ${repo.containerPath}/*/*.py 2>/dev/null; rm -rf /tmp/skills-storage'`);
  69. lines.push(`echo "[REPO] ${c} 已从 ${repo.url} 拉取技能"`);
  70. if (opts.restartGateway) {
  71. lines.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || echo "[WARN] 重启网关失败"`);
  72. lines.push(`echo "[RESTART] ${c} 网关已重启"`);
  73. }
  74. }
  75. return lines.join('\n');
  76. }
  77. function buildScript(containers, opts) {
  78. const lines = ['set -e'];
  79. for (const c of containers) {
  80. lines.push(`echo "[CONTAINER] ${c}"`);
  81. for (const skill of enabled) {
  82. const files = readSkillFiles(skill);
  83. const dir = `/opt/data/skills/${skill.scope || 'custom'}/${skill.name}`;
  84. lines.push(`docker exec ${c} mkdir -p ${dir}`);
  85. for (const [name, b64] of Object.entries(files)) {
  86. // base64 -d 写入后 chown 回 hermes(容器内 uid 10000)
  87. lines.push(
  88. `echo "${b64}" | base64 -d | docker exec -i ${c} sh -c "cat > ${dir}/${name}"`,
  89. );
  90. }
  91. lines.push(`docker exec ${c} chmod 0755 ${dir}/*.py 2>/dev/null || true`);
  92. lines.push(`docker exec ${c} chown -R 10000:10000 ${dir} 2>/dev/null || true`);
  93. lines.push(`echo "[SKILL] ${skill.name} -> ${dir}"`);
  94. }
  95. if (opts.restartGateway) {
  96. lines.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || echo "[WARN] 重启网关失败"`);
  97. lines.push(`echo "[RESTART] ${c} 网关已重启"`);
  98. }
  99. }
  100. return lines.join('\n');
  101. }
  102. function listContainers() {
  103. const script = `docker ps --format '{{.Names}}' | grep '^agent-node-app-' || true`;
  104. const out = execFileSync('python', [R730, writeTmp(script), '60'], {
  105. encoding: 'utf8',
  106. cwd: ROOT,
  107. });
  108. return out.split('\n').map((s) => s.trim()).filter((s) => /^agent-node-app-/.test(s));
  109. }
  110. function writeTmp(content) {
  111. const dir = resolve(ROOT, '.local-backup/tmp-wecom');
  112. const f = resolve(dir, `refresh-${Date.now()}.sh`);
  113. // 目录在仓库内,r730.py 只接受仓库内路径
  114. mkdirSync(dir, { recursive: true });
  115. writeFileSync(f, content, 'utf8');
  116. return f;
  117. }
  118. // ---------- 入口 ----------
  119. if (has('--list')) {
  120. console.log(`清单: ${basename(MANIFEST)}(${enabled.length} 个启用)`);
  121. for (const s of enabled) {
  122. console.log(` · ${s.name} → /opt/data/skills/${s.scope || 'custom'}/${s.name}/ ${s.required ? '[必需]' : '[可选]'}`);
  123. }
  124. const off = (manifest.skills ?? []).filter((s) => s.disabled);
  125. if (off.length) {
  126. console.log('已禁用:');
  127. for (const s of off) console.log(` ✗ ${s.name} — ${s.reason ?? ''}`);
  128. }
  129. process.exit(0);
  130. }
  131. let targets = [];
  132. if (val('--containers')) {
  133. targets = val('--containers').split(',').map((s) => s.trim()).filter(Boolean);
  134. } else if (has('--all') || has('--dry-run')) {
  135. targets = listContainers();
  136. }
  137. if (targets.length === 0) {
  138. console.error('没有目标容器。用 --containers a,b 或 --all');
  139. process.exit(1);
  140. }
  141. console.log(`目标容器 ${targets.length} 个: ${targets.join(', ')}`);
  142. console.log(`技能 ${enabled.length} 个: ${enabled.map((s) => s.name).join(', ')}`);
  143. if (has('--dry-run') || !has('--apply')) {
  144. console.log('\n[DRY-RUN] 未加 --apply,不执行任何写入。');
  145. for (const c of targets) {
  146. for (const s of enabled) {
  147. console.log(` 将写入 ${c}:/opt/data/skills/${s.scope || 'custom'}/${s.name}/`);
  148. }
  149. }
  150. process.exit(0);
  151. }
  152. if (has('--from-repo')) {
  153. const repo = Object.values(manifest.repos ?? {})[0];
  154. console.log(`
  155. [FROM-REPO] 容器将从 ${repo?.url ?? '(未配置)'} 自行拉取`);
  156. const script = buildRepoScript(targets, { restartGateway: has('--restart-gateway') });
  157. const scriptPath = writeTmp(script);
  158. console.log('执行中...');
  159. const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
  160. console.log(out);
  161. console.log('完成(容器内已是仓库最新版)。');
  162. process.exit(0);
  163. }
  164. const script = buildScript(targets, { restartGateway: has('--restart-gateway') });
  165. const scriptPath = writeTmp(script);
  166. console.log('\n执行中...');
  167. const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
  168. console.log(out);
  169. console.log('完成。若改了网关相关配置,记得加 --restart-gateway。');