| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207 |
- #!/usr/bin/env node
- /**
- * 按 container-skill-manifest.json 刷新 R730 上容器的技能(2026-12-03)。
- *
- * 与开通链路共用同一份清单:provision.sh 给新容器装技能,本脚本给存量容器补/替换。
- * 新增或替换技能只改清单,不改这里。
- *
- * 用法:
- * node scripts/refresh-container-skills.mjs --list # 只列清单与计划
- * node scripts/refresh-container-skills.mjs --dry-run # 对全部容器演算
- * node scripts/refresh-container-skills.mjs --containers a,b # 指定容器
- * node scripts/refresh-container-skills.mjs --all --apply # 真正下发(需显式 --apply)
- * node scripts/refresh-container-skills.mjs --containers x --apply --restart-gateway
- * node scripts/refresh-container-skills.mjs --all --from-repo --apply # 让容器自己从仓库拉
- *
- * 两种下发方式:
- * (默认)从宿主仓库推送 —— 技能内容随本仓库走,容器不需要外网
- * --from-repo —— 只发一条拉取指令,容器自己 git clone skills-storage
- * (2026-12-03 实测容器可访问 git.fmode.cn,不可访问 github.com)
- *
- * 约束(容器扩展铁律):只往 /opt/data/skills/<scope>/<name>/ 写文件,不碰 /opt/hermes 源码。
- */
- import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
- import { execFileSync } from 'node:child_process';
- import { resolve, basename } from 'node:path';
- const ROOT = resolve(new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
- const MANIFEST = resolve(ROOT, 'cloud/skills/container-skill-manifest.json');
- const R730 = resolve(ROOT, '.local-backup/skill-lock-20261201/r730.py');
- const argv = process.argv.slice(2);
- const has = (f) => argv.includes(f);
- const val = (f) => {
- const i = argv.indexOf(f);
- return i >= 0 ? argv[i + 1] : undefined;
- };
- const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
- const enabled = (manifest.skills ?? []).filter((s) => !s.disabled);
- if (enabled.length === 0) {
- console.error('清单里没有可下发的技能');
- process.exit(1);
- }
- /** 读取技能文件内容(base64,避免 shell 转义问题) */
- function readSkillFiles(skill) {
- /* source 既可以是字符串路径,也可以是 {type:'repo', fallback:'...'}(2026-12-03 v2 清单) */
- const spec = skill.source;
- const rel = typeof spec === 'string' ? spec : spec?.fallback;
- if (!rel) throw new Error(`技能 ${skill.name} 只声明了远程源,没有 fallback;请用 --from-repo`);
- const srcDir = resolve(ROOT, rel);
- const out = {};
- for (const f of skill.files) {
- const p = resolve(srcDir, f);
- try {
- out[f] = readFileSync(p).toString('base64');
- } catch {
- throw new Error(`技能 ${skill.name} 缺少文件: ${p}`);
- }
- }
- return out;
- }
- /** 生成在 R730 上执行的 shell:把技能写进指定容器 */
- /** 容器内自己从 skills-storage 拉技能(2026-12-03 v2) */
- function buildRepoScript(containers, opts) {
- const repo = Object.values(manifest.repos ?? {})[0];
- if (!repo) throw new Error('清单里没有 repos 定义,无法 --from-repo');
- const lines = ['set -e'];
- for (const c of containers) {
- lines.push(`echo "[CONTAINER] ${c}"`);
- 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'`);
- 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'`);
- lines.push(`echo "[REPO] ${c} 已从 ${repo.url} 拉取技能"`);
- if (opts.restartGateway) {
- lines.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || echo "[WARN] 重启网关失败"`);
- lines.push(`echo "[RESTART] ${c} 网关已重启"`);
- }
- }
- return lines.join('\n');
- }
- function buildScript(containers, opts) {
- const lines = ['set -e'];
- for (const c of containers) {
- lines.push(`echo "[CONTAINER] ${c}"`);
- for (const skill of enabled) {
- const files = readSkillFiles(skill);
- /*
- * scope=org → 落到 _org/<org_id>/,属主 root、755/644,
- * 用户改不了(见规范 §0b)。custom → 落 custom/,属主 hermes。
- */
- const isOrg = (skill.scope || 'custom') === 'org';
- const orgId = manifest.org?.id || 'fmode';
- const dir = isOrg
- ? `/opt/data/skills/_org/${orgId}/${skill.name}`
- : `/opt/data/skills/${skill.scope || 'custom'}/${skill.name}`;
- lines.push(`docker exec ${c} mkdir -p ${dir}`);
- for (const [name, b64] of Object.entries(files)) {
- lines.push(
- `echo "${b64}" | base64 -d | docker exec -i ${c} sh -c "cat > ${dir}/${name}"`,
- );
- }
- if (isOrg) {
- lines.push(`docker exec ${c} sh -c 'printf "%s" ${orgId} > /opt/data/skills/_org/.active_org'`);
- lines.push(`docker exec ${c} chown -R 0:0 /opt/data/skills/_org`);
- 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 {} \\;'`);
- } else {
- lines.push(`docker exec ${c} chmod 0755 ${dir}/*.py 2>/dev/null || true`);
- lines.push(`docker exec ${c} chown -R 10000:10000 ${dir} 2>/dev/null || true`);
- }
- lines.push(`echo "[SKILL] ${skill.name} -> ${dir}${isOrg ? ' (org, root 属主)' : ''}"`);
- }
- if (opts.restartGateway) {
- lines.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || echo "[WARN] 重启网关失败"`);
- lines.push(`echo "[RESTART] ${c} 网关已重启"`);
- }
- }
- return lines.join('\n');
- }
- function listContainers() {
- const script = `docker ps --format '{{.Names}}' | grep '^agent-node-app-' || true`;
- const out = execFileSync('python', [R730, writeTmp(script), '60'], {
- encoding: 'utf8',
- cwd: ROOT,
- });
- return out.split('\n').map((s) => s.trim()).filter((s) => /^agent-node-app-/.test(s));
- }
- function writeTmp(content) {
- const dir = resolve(ROOT, '.local-backup/tmp-wecom');
- const f = resolve(dir, `refresh-${Date.now()}.sh`);
- // 目录在仓库内,r730.py 只接受仓库内路径
- mkdirSync(dir, { recursive: true });
- writeFileSync(f, content, 'utf8');
- return f;
- }
- // ---------- 入口 ----------
- if (has('--list')) {
- console.log(`清单: ${basename(MANIFEST)}(${enabled.length} 个启用)`);
- for (const s of enabled) {
- const orgId = manifest.org?.id || 'fmode';
- const shown = (s.scope || 'custom') === 'org'
- ? `/opt/data/skills/_org/${orgId}/${s.name}/`
- : `/opt/data/skills/${s.scope || 'custom'}/${s.name}/`;
- console.log(` · ${s.name} → ${shown} ${s.required ? '[必需]' : '[可选]'}`);
- }
- const off = (manifest.skills ?? []).filter((s) => s.disabled);
- if (off.length) {
- console.log('已禁用:');
- for (const s of off) console.log(` ✗ ${s.name} — ${s.reason ?? ''}`);
- }
- process.exit(0);
- }
- let targets = [];
- if (val('--containers')) {
- targets = val('--containers').split(',').map((s) => s.trim()).filter(Boolean);
- } else if (has('--all') || has('--dry-run')) {
- targets = listContainers();
- }
- if (targets.length === 0) {
- console.error('没有目标容器。用 --containers a,b 或 --all');
- process.exit(1);
- }
- console.log(`目标容器 ${targets.length} 个: ${targets.join(', ')}`);
- console.log(`技能 ${enabled.length} 个: ${enabled.map((s) => s.name).join(', ')}`);
- if (has('--dry-run') || !has('--apply')) {
- console.log('\n[DRY-RUN] 未加 --apply,不执行任何写入。');
- for (const c of targets) {
- for (const s of enabled) {
- const orgId = manifest.org?.id || 'fmode';
- const shown = (s.scope || 'custom') === 'org'
- ? `/opt/data/skills/_org/${orgId}/${s.name}/`
- : `/opt/data/skills/${s.scope || 'custom'}/${s.name}/`;
- console.log(` 将写入 ${c}:${shown}`);
- }
- }
- process.exit(0);
- }
- if (has('--from-repo')) {
- const repo = Object.values(manifest.repos ?? {})[0];
- console.log(`
- [FROM-REPO] 容器将从 ${repo?.url ?? '(未配置)'} 自行拉取`);
- const script = buildRepoScript(targets, { restartGateway: has('--restart-gateway') });
- const scriptPath = writeTmp(script);
- console.log('执行中...');
- const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
- console.log(out);
- console.log('完成(容器内已是仓库最新版)。');
- process.exit(0);
- }
- const script = buildScript(targets, { restartGateway: has('--restart-gateway') });
- const scriptPath = writeTmp(script);
- console.log('\n执行中...');
- const out = execFileSync('python', [R730, scriptPath, '600'], { encoding: 'utf8', cwd: ROOT });
- console.log(out);
- console.log('完成。若改了网关相关配置,记得加 --restart-gateway。');
|