import { harnessContext } from './harness-context.js'; import { spawnSync } from 'node:child_process'; import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, } from 'node:fs'; import { createHash, randomUUID } from 'node:crypto'; import { homedir } from 'node:os'; import { dirname, join, relative, resolve } from 'node:path'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; const require = createRequire(import.meta.url); /** Read a skill name from SKILL.md frontmatter without loading its instructions. */ export function readSkillName(dir: string): string | null { const path = join(dir, 'SKILL.md'); if (!existsSync(path)) return null; const content = readFileSync(path, 'utf8'); const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/); if (!frontmatter) return null; for (const line of frontmatter[1].split(/\r?\n/)) { const field = line.match(/^\s*name\s*:\s*(.+)\s*$/i); if (field) return field[1].trim().replace(/^["']|["']$/g, ''); } return null; } /** Resolve a ZIP that contains either SKILL.md at root or one wrapping directory. */ export function findSkillRoot(path: string): string { if (existsSync(join(path, 'SKILL.md'))) return path; let entries: string[]; try { entries = readdirSync(path).filter((entry) => { try { return !entry.startsWith('.') && statSync(join(path, entry)).isDirectory(); } catch { return false; } }); } catch { return path; } if (entries.length === 1 && existsSync(join(path, entries[0], 'SKILL.md'))) { return join(path, entries[0]); } return path; } function skillsCli(): string { try { return require.resolve('skills/bin/cli.mjs'); } catch { return ''; } } export interface SkillHostMutationResult { ok: boolean; error?: string; unavailablePath?: string; stdout?: string; stderr?: string; } function runSkillsCli(args: string[]): SkillHostMutationResult { const binary = skillsCli(); if (!binary) return { ok: false, error: 'skills CLI not found' }; const result = spawnSync(process.execPath, [binary, ...args], { stdio: 'pipe', timeout: 30_000, encoding: 'utf8', }); if (result.error) return { ok: false, error: result.error.message }; return { ok: result.status === 0, ...(result.status === 0 ? {} : { error: `skills CLI exited with code ${result.status}` }), ...(result.stdout ? { stdout: result.stdout } : {}), ...(result.stderr ? { stderr: result.stderr } : {}), }; } export function registerAgentSkill(path: string): SkillHostMutationResult { return runSkillsCli(['add', findSkillRoot(path), '-g', '-y']); } function openClawSkillsDir(homeDir: string): string { for (const directory of ['.openclaw', '.clawdbot', '.moltbot']) { if (existsSync(join(homeDir, directory))) return join(homeDir, directory, 'skills'); } return join(homeDir, '.openclaw', 'skills'); } function skillHostHomes(): Record { const homeDir = homedir(); return { '.agents': join(homeDir, '.agents'), 'Claude Code': process.env.CLAUDE_CONFIG_DIR?.trim() || join(homeDir, '.claude'), Codex: process.env.CODEX_HOME?.trim() || join(homeDir, '.codex'), OpenClaw: dirname(openClawSkillsDir(homeDir)), }; } export function agentSkillTargets(name: string): string[] { if (harnessContext()) return []; return Object.values(skillHostHomes()).map(home => join(home, 'skills', name)); } export function resolveBundledClawclawSkill(): string { const dev = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills', 'clawclaw'); if (existsSync(join(dev, 'SKILL.md'))) return dev; const packageRoot = dirname(require.resolve('@myclaw163/clawclaw-cli/package.json')); return join(packageRoot, 'skills', 'clawclaw'); } export function hashAgentSkillDirectory(path: string): string | undefined { if (!existsSync(path) || !statSync(path).isDirectory()) return undefined; const root = resolve(path); const files: string[] = []; const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const child = join(directory, entry.name); if (entry.isDirectory()) visit(child); else if (entry.isFile()) files.push(child); } }; visit(root); files.sort((left, right) => left.localeCompare(right)); const hash = createHash('sha256'); for (const file of files) { hash.update(file.slice(root.length + 1).replaceAll('\\', '/')); hash.update('\0'); hash.update(readFileSync(file)); hash.update('\0'); } return hash.digest('hex'); } /** Atomically replace one host copy after its caller proves the copy is an old Hub baseline. */ export function overwriteAgentSkillTarget(sourcePath: string, targetPath: string): SkillHostMutationResult { const source = resolve(findSkillRoot(sourcePath)); const target = resolve(targetPath); const stage = `${target}.ccl-stage-${randomUUID()}`; const displaced = `${target}.ccl-old-${randomUUID()}`; let moved = false; try { mkdirSync(dirname(target), { recursive: true }); cpSync(source, stage, { recursive: true, dereference: true, errorOnExist: true }); if (existsSync(target)) { renameSync(target, displaced); moved = true; } renameSync(stage, target); if (moved) rmSync(displaced, { recursive: true, force: true }); return { ok: true }; } catch (error) { rmSync(stage, { recursive: true, force: true }); if (moved && !existsSync(target) && existsSync(displaced)) { try { renameSync(displaced, target); } catch { /* retain displaced recovery copy */ } } return { ok: false, error: error instanceof Error ? error.message : String(error) }; } } /** Point one host at the account's canonical Skill without consuming legacy real directories. */ export function linkAgentSkillTarget(sourcePath: string, targetPath: string): SkillHostMutationResult { const source = resolve(findSkillRoot(sourcePath)); const target = resolve(targetPath); const stage = `${target}.ccl-link-${randomUUID()}`; const displaced = `${target}.ccl-old-link-${randomUUID()}`; let moved = false; try { if (!existsSync(join(source, 'SKILL.md'))) return { ok: false, error: 'canonical skill is invalid' }; const parent = dirname(target); if (!existsSync(parent)) { // Only create skills/ in a configured host; its home may have disappeared since inspection. const hostParent = Object.values(skillHostHomes()).some(home => relative(join(home, 'skills'), parent) === ''); try { mkdirSync(parent, { recursive: !hostParent }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; } } if (existsSync(target)) { if (!lstatSync(target).isSymbolicLink()) { return { ok: false, unavailablePath: target, error: 'Host-owned Skill path was preserved' }; } try { if (resolve(realpathSync(target)) === source) { return { ok: true }; } } catch {} } symlinkSync(source, stage, process.platform === 'win32' ? 'junction' : 'dir'); if (existsSync(target)) { renameSync(target, displaced); moved = true; } renameSync(stage, target); if (moved) unlinkSync(displaced); return { ok: true }; } catch (error) { if (existsSync(stage)) unlinkSync(stage); if (moved && !existsSync(target) && existsSync(displaced)) { try { renameSync(displaced, target); moved = false; } catch { /* keep the recovery link */ } } const code = (error as NodeJS.ErrnoException).code; return { ok: false, error: error instanceof Error ? error.message : String(error), ...(!moved && code ? { unavailablePath: dirname(target) } : {}) }; } } export function unlinkAgentSkillTarget(targetPath: string): SkillHostMutationResult { const target = resolve(targetPath); try { if (!existsSync(target)) return { ok: true }; if (!lstatSync(target).isSymbolicLink()) { return { ok: false, error: 'legacy real skill directory is unsupported and was preserved' }; } unlinkSync(target); return { ok: true }; } catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error) }; } } /** An unequip must not remove another resource's link at the same Skill name. */ export function agentSkillLinkPointsTo(targetPath: string, sourcePath: string): boolean { try { return lstatSync(targetPath).isSymbolicLink() && realpathSync(targetPath) === realpathSync(sourcePath); } catch { return false; } } export function unregisterAgentSkill(name: string): SkillHostMutationResult { return runSkillsCli(['remove', name, '-g', '-y']); } export interface SkillHostSkip { name: string; reason: 'local_skill_directory_exists' | 'skill_host_directory_unavailable'; paths: string[]; host?: string; blocked_path?: string; blocking: false; message: string; } function skillHostSkip(name: string, paths: string[]): SkillHostSkip { return { name, reason: 'local_skill_directory_exists', paths, blocking: false, message: 'Same-name local Skill paths were preserved. CCL Skill link changes were skipped only at the listed paths; other host paths are handled independently. Gameplay may continue. The affected Agent hosts may still load their local Skill.', }; } function inspectSkillTarget(target: string, home?: string): SkillHostMutationResult | 'host-owned' | undefined { const parent = dirname(target); try { if (home && !statSync(home, { throwIfNoEntry: false })?.isDirectory()) { return { ok: false, unavailablePath: home }; } const directory = statSync(parent, { throwIfNoEntry: false }); if (directory && !directory.isDirectory()) return { ok: false, unavailablePath: parent }; const leaf = lstatSync(target, { throwIfNoEntry: false }); if (leaf && !leaf.isSymbolicLink()) { return leaf.isDirectory() ? 'host-owned' : { ok: false, unavailablePath: target }; } } catch (error) { return { ok: false, unavailablePath: (error as NodeJS.ErrnoException).path ?? parent }; } } /** Visit independent host links, preserving host-owned files and unavailable host directories. */ export function runSkillHostOperations( name: string, targets: readonly string[], mutate?: (target: string) => SkillHostMutationResult | undefined, onFailure: 'continue' | 'stop' = 'continue', ) { const applied: string[] = []; const failed: SkillHostMutationResult[] = []; const skipped: SkillHostSkip[] = []; const realTargets: string[] = []; const homes = targets.length ? Object.entries(skillHostHomes()) : []; for (const target of new Set(targets)) { const parent = dirname(target); const hosts = homes.filter(([, home]) => relative(join(home, 'skills'), parent) === ''); const obstacle = inspectSkillTarget(target, hosts[0]?.[1]); if (obstacle === 'host-owned') { realTargets.push(target); continue; } let result: SkillHostMutationResult | undefined; try { result = obstacle ?? mutate?.(target); } catch (error) { result = { ok: false, error: String(error) }; } if (!result) continue; if (result.ok) applied.push(target); else if (result.unavailablePath) { const host = hosts.map(([label]) => label).join(' / ') || parent; skipped.push({ name, host, reason: 'skill_host_directory_unavailable', paths: [target], blocked_path: result.unavailablePath, blocking: false, message: `${host} 未装配「${name}」,宿主路径不可用(${result.unavailablePath})。`, }); } else { failed.push(result); if (onFailure === 'stop') break; } } if (realTargets.length) skipped.push(skillHostSkip(name, realTargets)); return { applied, failed, skipped }; }