refresh-container-skills.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. /*
  84. * scope=org → 落到 _org/<org_id>/,属主 root、755/644,
  85. * 用户改不了(见规范 §0b)。custom → 落 custom/,属主 hermes。
  86. */
  87. const isOrg = (skill.scope || 'custom') === 'org';
  88. const orgId = manifest.org?.id || 'fmode';
  89. const dir = isOrg
  90. ? `/opt/data/skills/_org/${orgId}/${skill.name}`
  91. : `/opt/data/skills/${skill.scope || 'custom'}/${skill.name}`;
  92. lines.push(`docker exec ${c} mkdir -p ${dir}`);
  93. for (const [name, b64] of Object.entries(files)) {
  94. lines.push(
  95. `echo "${b64}" | base64 -d | docker exec -i ${c} sh -c "cat > ${dir}/${name}"`,
  96. );
  97. }
  98. if (isOrg) {
  99. lines.push(`docker exec ${c} sh -c 'printf "%s" ${orgId} > /opt/data/skills/_org/.active_org'`);
  100. lines.push(`docker exec ${c} chown -R 0:0 /opt/data/skills/_org`);
  101. lines.push(`docker exec ${c} sh -c 'find /opt/data/skills/_org -type d -exec chmod 755 {} \\; && find /opt/data/skills/_org -type f -exec chmod 644 {} \\;'`);
  102. } else {
  103. lines.push(`docker exec ${c} chmod 0755 ${dir}/*.py 2>/dev/null || true`);
  104. lines.push(`docker exec ${c} chown -R 10000:10000 ${dir} 2>/dev/null || true`);
  105. }
  106. lines.push(`echo "[SKILL] ${skill.name} -> ${dir}${isOrg ? ' (org, root 属主)' : ''}"`);
  107. }
  108. if (opts.restartGateway) {
  109. lines.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || echo "[WARN] 重启网关失败"`);
  110. lines.push(`echo "[RESTART] ${c} 网关已重启"`);
  111. }
  112. }
  113. return lines.join('\n');
  114. }
  115. function listContainers() {
  116. const script = `docker ps --format '{{.Names}}' | grep '^agent-node-app-' || true`;
  117. const out = execFileSync('python', [R730, writeTmp(script), '60'], {
  118. encoding: 'utf8',
  119. cwd: ROOT,
  120. });
  121. return out.split('\n').map((s) => s.trim()).filter((s) => /^agent-node-app-/.test(s));
  122. }
  123. function writeTmp(content) {
  124. const dir = resolve(ROOT, '.local-backup/tmp-wecom');
  125. const f = resolve(dir, `refresh-${Date.now()}.sh`);
  126. // 目录在仓库内,r730.py 只接受仓库内路径
  127. mkdirSync(dir, { recursive: true });
  128. writeFileSync(f, content, 'utf8');
  129. return f;
  130. }
  131. // ---------- 入口 ----------
  132. if (has('--list')) {
  133. console.log(`清单: ${basename(MANIFEST)}(${enabled.length} 个启用)`);
  134. for (const s of enabled) {
  135. const orgId = manifest.org?.id || 'fmode';
  136. const shown = (s.scope || 'custom') === 'org'
  137. ? `/opt/data/skills/_org/${orgId}/${s.name}/`
  138. : `/opt/data/skills/${s.scope || 'custom'}/${s.name}/`;
  139. console.log(` · ${s.name} → ${shown} ${s.required ? '[必需]' : '[可选]'}`);
  140. }
  141. const off = (manifest.skills ?? []).filter((s) => s.disabled);
  142. if (off.length) {
  143. console.log('已禁用:');
  144. for (const s of off) console.log(` ✗ ${s.name} — ${s.reason ?? ''}`);
  145. }
  146. process.exit(0);
  147. }
  148. let targets = [];
  149. if (val('--containers')) {
  150. targets = val('--containers').split(',').map((s) => s.trim()).filter(Boolean);
  151. } else if (has('--all') || has('--dry-run')) {
  152. targets = listContainers();
  153. }
  154. if (targets.length === 0) {
  155. console.error('没有目标容器。用 --containers a,b 或 --all');
  156. process.exit(1);
  157. }
  158. console.log(`目标容器 ${targets.length} 个: ${targets.join(', ')}`);
  159. console.log(`技能 ${enabled.length} 个: ${enabled.map((s) => s.name).join(', ')}`);
  160. if (has('--dry-run') || !has('--apply')) {
  161. console.log('\n[DRY-RUN] 未加 --apply,不执行任何写入。');
  162. for (const c of targets) {
  163. for (const s of enabled) {
  164. const orgId = manifest.org?.id || 'fmode';
  165. const shown = (s.scope || 'custom') === 'org'
  166. ? `/opt/data/skills/_org/${orgId}/${s.name}/`
  167. : `/opt/data/skills/${s.scope || 'custom'}/${s.name}/`;
  168. console.log(` 将写入 ${c}:${shown}`);
  169. }
  170. }
  171. process.exit(0);
  172. }
  173. if (has('--from-repo')) {
  174. const repo = Object.values(manifest.repos ?? {})[0];
  175. console.log(`
  176. [FROM-REPO] 容器将从 ${repo?.url ?? '(未配置)'} 自行拉取`);
  177. const script = buildRepoScript(targets, { restartGateway: has('--restart-gateway') });
  178. const scriptPath = writeTmp(script);
  179. console.log('执行中...');
  180. const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
  181. console.log(out);
  182. console.log('完成(容器内已是仓库最新版)。');
  183. process.exit(0);
  184. }
  185. const script = buildScript(targets, { restartGateway: has('--restart-gateway') });
  186. const scriptPath = writeTmp(script);
  187. console.log('\n执行中...');
  188. const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
  189. console.log(out);
  190. console.log('完成。若改了网关相关配置,记得加 --restart-gateway。');