import { harnessContext } from './harness-context.js'; import { isPackageManagedSkill, reservedSkillName } from './package-skills.js'; import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, readdirSync, renameSync, writeFileSync, } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { createHash, randomUUID } from 'node:crypto'; import type { AuthProfile } from './auth.js'; import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js'; import { resolveLocalAgentWorkspacePath, type LocalAgentWorkspaceItem, type LocalAgentWorkspaceSnapshot, } from './agent-workspace-sync.js'; import { capabilityWorkspacePath, capabilityEntryForHubResource, readCapabilityWorkspaceRegistry, registerDiscoveredCapability, } from './capability-workspace.js'; import { getUserDataAccountCapabilitiesDir, getUserDataAccountSkillsDir, } from './user-data.js'; import { agentSkillTargets, runSkillHostOperations, type SkillHostSkip, hashAgentSkillDirectory, linkAgentSkillTarget, overwriteAgentSkillTarget, readSkillName, unlinkAgentSkillTarget, type SkillHostMutationResult, } from './skill-host.js'; import { zipContentDigest } from './zip-store.js'; import { selectedSkillNameConflicts, skillConflictNames, skillNameKey, sameSkill, type SkillNameConflict } from './skill-name-conflicts.js'; interface ActiveSkillEntry { name: string; kind: 'hub' | 'local'; canonicalPath: string; /** Last accepted remote directory hash. */ sourceDigest?: string; /** Latest observed remote directory hash. */ remoteDigest?: string; /** Upload-compatible digest for the last accepted remote content. */ sourceCloudDigest?: string; /** Upload-compatible digest for the latest observed remote content. */ remoteCloudDigest?: string; knownSourceDigests?: string[]; knownCloudDigests?: string[]; resourceId?: string; versionId?: string; } interface ActiveSkillManifest { format: 2; entries: Record; } export interface AgentWorkspaceSkillChanges { added: string[]; updated: string[]; removed: string[]; unchanged: string[]; preservedModified: string[]; failed: Array<{ name: string; action: 'add' | 'update' | 'remove'; error: string }>; conflicts?: SkillNameConflict[]; skipped?: SkillHostSkip[]; requiresUserConfirmation: boolean; prompt?: string; } export interface AgentWorkspaceSkillDependencies { targets?: (name: string) => readonly string[]; hashDirectory?: (path: string) => string | undefined; overwriteTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult; linkTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult; unlinkTarget?: (targetPath: string) => SkillHostMutationResult; cloudDigest?: (path: string) => string | undefined; } export interface AccountSkillLinkSwitchResult { removed: string[]; linked: string[]; } function manifestPath( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'skill-links.json'); } function readManifest( workspaceDir: string, profile: Pick, ): ActiveSkillManifest { const path = manifestPath(workspaceDir, profile); if (!existsSync(path)) return { format: 2, entries: {} }; try { const value = JSON.parse(readFileSync(path, 'utf8')) as ActiveSkillManifest; return value.format === 2 && value.entries ? value : { format: 2, entries: {} }; } catch { return { format: 2, entries: {} }; } } function writeManifest( workspaceDir: string, profile: Pick, value: ActiveSkillManifest, ): void { const target = manifestPath(workspaceDir, profile); mkdirSync(dirname(target), { recursive: true }); const temporary = `${target}.${randomUUID()}.tmp`; writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8'); renameSync(temporary, target); } function resultError(result: SkillHostMutationResult): string { return result.error ?? result.stderr?.trim() ?? 'skill host mutation failed'; } function skillCloudDigest(path: string): string | undefined { if (!existsSync(path)) return undefined; const root = resolve(path); const files: Array<{ path: string; content: Buffer }> = []; const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const child = join(directory, entry.name); const stat = lstatSync(child); if (stat.isSymbolicLink()) throw new Error('skill_source_symlink_unsupported'); if (stat.isDirectory()) visit(child); else if (stat.isFile()) files.push({ path: relative(root, child).replaceAll('\\', '/'), content: readFileSync(child), }); } }; try { visit(root); return files.length > 0 ? zipContentDigest(files) : undefined; } catch { return undefined; } } function unique(values: Array): string[] { return [...new Set(values.filter((value): value is string => !!value))]; } function hubSkillWorkingCopyPath( workspaceDir: string, profile: Pick, name: string, resourceId: string, ): string { const registered = capabilityEntryForHubResource(workspaceDir, profile, 'skill', resourceId); if (registered) return capabilityWorkspacePath(workspaceDir, profile, registered); const root = getUserDataAccountSkillsDir(workspaceDir, profile); const preferred = join(root, name); const pathKey = (path: string) => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path); const occupied = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .some(entry => entry.type === 'skill' && pathKey(capabilityWorkspacePath(workspaceDir, profile, entry)) === pathKey(preferred)); // The previous resource may be unequipped but its source must survive a // same-name replacement. Only the private directory differs, never SKILL.md. return occupied ? join(root, `${name}-${createHash('sha256').update(resourceId).digest('hex')}`) : preferred; } /** Report collisions without displacing the resource already exposed to hosts. */ export function inspectSkillNameConflicts( workspaceDir: string, profile: Pick, snapshot?: LocalAgentWorkspaceSnapshot, targets: (name: string) => readonly string[] = agentSkillTargets, ): SkillNameConflict[] { const manifest = readManifest(workspaceDir, profile); const samePath = (left: string, right: string): boolean => { try { return realpathSync(left) === realpathSync(right); } catch { return false; } }; return selectedSkillNameConflicts(workspaceDir, profile, snapshot).map(conflict => { const paths = [...new Set(conflict.candidates.flatMap(candidate => [...new Set([candidate.name, ...(candidate.id ? [candidate.id] : [])])].flatMap(name => [...targets(name)])))]; const linked = paths.flatMap(target => { try { if (!lstatSync(target).isSymbolicLink()) return []; const candidate = conflict.candidates.find(item => samePath(target, item.working_copy_path) || Object.values(manifest.entries).some(entry => ( item.resource_id ? entry.resourceId === item.resource_id : !entry.resourceId && samePath(entry.canonicalPath, item.working_copy_path) ) && samePath(target, entry.canonicalPath))); return [candidate]; } catch { return []; } }); const first = linked[0]; const active = first && linked.every(item => item && sameSkill(first, item)) ? first : undefined; return { ...conflict, blocking: false, ...(active ? { active } : {}), unavailable: conflict.candidates.filter(item => !active || !sameSkill(active, item)), hint: active ? 'The already linked Skill remains usable. Other same-name resources are unavailable; existing files and links are preserved. Continue using the active Skill. Unequip it before explicitly switching to another resource.' : 'No single active Skill could be confirmed for this name. These resources are unavailable; existing files and links are preserved. Other capabilities remain usable. Choose one resource before using this Skill.', }; }); } export function accountManagedSkillSources( workspaceDir: string, profile: Pick, includeInactive = false, ): Map { const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile); const sources = new Map(); const conflicts = includeInactive ? [] : selectedSkillNameConflicts(workspaceDir, profile); const conflictingNames = skillConflictNames(conflicts); for (const [name, manifestEntry] of Object.entries(readManifest(workspaceDir, profile).entries)) { if (isPackageManagedSkill(name)) continue; const entry = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .find(entry => entry.type === 'skill' && (manifestEntry.resourceId ? entry.hub?.resourceId === manifestEntry.resourceId : capabilityWorkspacePath(workspaceDir, profile, entry) === manifestEntry.canonicalPath)); if (conflictingNames.has(skillNameKey(name)) && entry?.selection !== 'equipped') continue; const path = manifestEntry.canonicalPath ?? join(skillsRoot, name); if (!includeInactive && (reservedSkillName(readSkillName(path), path) || (entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)))) continue; sources.set(name, path); } for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) { if ( entry.type !== 'skill' || isPackageManagedSkill(entry.runtimeId) || entry.origin !== 'local' || entry.selection !== 'equipped' || conflictingNames.has(skillNameKey(entry.runtimeId)) ) continue; const path = capabilityWorkspacePath(workspaceDir, profile, entry); if (!includeInactive && reservedSkillName(readSkillName(path), path)) continue; sources.set(entry.runtimeId, path); } return sources; } /** * Move the device-wide account-managed Skill links before AuthStore commits an * account switch. Package-owned skills are deliberately untouched. */ export function switchActiveAccountSkillLinks( workspaceDir: string, previousProfile: Pick | null, nextProfile: Pick | null, dependencies: Pick = {}, ): AccountSkillLinkSwitchResult { if (harnessContext() || previousProfile?.apiKey === nextProfile?.apiKey) return { removed: [], linked: [] }; const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir); if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.'); guard.release(); const targets = dependencies.targets ?? agentSkillTargets; const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget; const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget; const previous = previousProfile ? accountManagedSkillSources(workspaceDir, previousProfile, true) : new Map(); const next = nextProfile ? accountManagedSkillSources(workspaceDir, nextProfile) : new Map(); for (const [name, source] of next) { if (!existsSync(source) || readSkillName(source) !== name) { throw new Error(`account_skill_source_unavailable:${name}`); } } const removedTargets: Array<{ name: string; target: string }> = []; const linkedTargets: Array<{ name: string; target: string }> = []; try { for (const [name] of previous) { const result = runSkillHostOperations(name, targets(name), unlinkTarget, 'stop'); for (const target of result.applied) removedTargets.push({ name, target }); if (result.failed.length) throw new Error(`account_skill_unlink_failed:${name}:${resultError(result.failed[0])}`); } for (const [name, source] of next) { const result = runSkillHostOperations(name, targets(name), target => linkTarget(source, target), 'stop'); for (const target of result.applied) linkedTargets.push({ name, target }); if (result.failed.length) throw new Error(`account_skill_link_failed:${name}:${resultError(result.failed[0])}`); } } catch (error) { for (const { target } of linkedTargets.reverse()) unlinkTarget(target); for (const { name, target } of removedTargets.reverse()) { const source = previous.get(name); if (source && existsSync(source)) linkTarget(source, target); } throw error; } return { removed: [...previous.keys()], linked: [...next.keys()], }; } export function syncAgentWorkspaceSkills( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, dependencies: AgentWorkspaceSkillDependencies = {}, ): AgentWorkspaceSkillChanges { const current = readManifest(workspaceDir, profile); const next: ActiveSkillManifest = { format: 2, entries: {} }; const failed: AgentWorkspaceSkillChanges['failed'] = []; const skipped: SkillHostSkip[] = []; const conflicts = inspectSkillNameConflicts(workspaceDir, profile, snapshot, dependencies.targets); const blockedNames = skillConflictNames(conflicts); const hashDirectory = dependencies.hashDirectory ?? hashAgentSkillDirectory; const overwriteTarget = dependencies.overwriteTarget ?? overwriteAgentSkillTarget; const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget; const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget; const targets = dependencies.targets ?? agentSkillTargets; const cloudDigest = dependencies.cloudDigest ?? skillCloudDigest; const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile); mkdirSync(skillsRoot, { recursive: true }); const desired = new Map(); for (const item of snapshot.items.skill) { if (!item.skillRootPath) continue; const path = resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot, item.skillRootPath); const name = readSkillName(path); if (name && blockedNames.has(skillNameKey(name))) continue; if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name) || isPackageManagedSkill(name)) { failed.push({ name: name ?? item.resourceId, action: current.entries[name ?? ''] ? 'update' : 'add', error: isPackageManagedSkill(name) ? `Hub resource cannot replace the official ${name} Skill` : 'SKILL.md name is missing or unsafe', }); continue; } if (desired.has(name)) { failed.push({ name, action: 'add', error: 'duplicate selected skill name' }); continue; } desired.set(name, { kind: 'hub', sourcePath: path, resourceId: item.resourceId, versionId: item.versionId, remoteDigest: hashDirectory(path), remoteCloudDigest: cloudDigest(path), publisher: item.hub?.publisher ?? 'community', remoteItem: item, }); } for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) { if (entry.type !== 'skill' || entry.origin !== 'local' || entry.selection !== 'equipped') continue; if (entry.hub?.cloudStatus) continue; if (entry.hub && !snapshot.items.skill.some(item => item.resourceId === entry.hub!.resourceId)) continue; const path = capabilityWorkspacePath(workspaceDir, profile, entry); const name = readSkillName(path) ?? entry.runtimeId; if (blockedNames.has(skillNameKey(name))) continue; const reserved = reservedSkillName(entry.runtimeId) ?? reservedSkillName(name, path); if (reserved) { failed.push({ name: reserved, action: 'add', error: `The official ${reserved} Skill is managed by the installed CCL package`, }); continue; } if (desired.has(entry.runtimeId)) { if (entry.hub?.resourceId && entry.hub.resourceId === desired.get(entry.runtimeId)?.resourceId) continue; failed.push({ name: entry.runtimeId, action: 'add', error: 'local and Hub Skill names conflict' }); continue; } desired.set(entry.runtimeId, { kind: 'local', sourcePath: path }); } const added: string[] = []; const updated: string[] = []; const removed: string[] = []; const unchanged: string[] = []; const preservedModified: string[] = []; for (const [name, item] of desired) { // A local Skill already has its own working copy. Do not manufacture a // second name-based copy/registry entry when the folder name differs. const canonical = item.kind === 'local' ? item.sourcePath : hubSkillWorkingCopyPath(workspaceDir, profile, name, item.resourceId!); const previous = current.entries[name]; const sourceDigest = hashDirectory(item.sourcePath); const sourceCloudDigest = item.remoteCloudDigest ?? cloudDigest(item.sourcePath); if (!sourceDigest || !sourceCloudDigest) { failed.push({ name, action: previous ? 'update' : 'add', error: 'Skill source is unreadable' }); continue; } const canonicalDigest = hashDirectory(canonical); const canonicalCloudDigest = cloudDigest(canonical); const registered = item.kind === 'hub' && item.resourceId ? capabilityEntryForHubResource(workspaceDir, profile, 'skill', item.resourceId) : undefined; const knownSourceDigests = unique([ ...(previous?.knownSourceDigests ?? []), previous?.sourceDigest, previous?.remoteDigest, sourceDigest, ]); const knownCloudDigests = unique([ ...(previous?.knownCloudDigests ?? []), previous?.sourceCloudDigest, previous?.remoteCloudDigest, registered?.hub?.baseSha256, registered?.hub?.lastUploadedSha256, sourceCloudDigest, ]); let applied = false; let preserved = false; let resolution: LocalAgentWorkspaceItem['resolution'] = 'hub'; if (item.kind === 'local' && resolve(item.sourcePath) === resolve(canonical)) { applied = true; } else if (canonicalDigest === sourceDigest) { applied = true; } else if (canonicalDigest === undefined) { const result = overwriteTarget(item.sourcePath, canonical); if (!result.ok) { failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) }); continue; } applied = true; } else if (item.kind === 'hub') { const originRecognized = registered?.hub?.localOriginUnrecognized !== true && (!!registered?.hub || !!previous?.sourceDigest); const localMatchesKnownVersion = knownSourceDigests.includes(canonicalDigest) || (!!canonicalCloudDigest && knownCloudDigests.includes(canonicalCloudDigest)); const remoteAdvanced = registered?.hub ? registered.hub.versionId !== item.versionId : !!previous?.sourceDigest && previous.sourceDigest !== sourceDigest; if (localMatchesKnownVersion) { const result = overwriteTarget(item.sourcePath, canonical); if (!result.ok) { failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) }); continue; } applied = true; resolution = 'known_online_old'; } else { preserved = true; resolution = !originRecognized ? 'local_origin_unrecognized' : remoteAdvanced ? 'concurrent_difference' : 'local_modified'; preservedModified.push(name); } } else { preserved = true; preservedModified.push(name); } const effectiveDigest = hashDirectory(canonical); if (!effectiveDigest) { failed.push({ name, action: previous ? 'update' : 'add', error: 'Canonical Skill is unavailable' }); continue; } const links = runSkillHostOperations(name, targets(name), target => linkTarget(canonical, target)); skipped.push(...links.skipped); for (const result of links.failed) failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) }); if (links.failed.length) continue; const effectiveCloudDigest = cloudDigest(canonical); if (!effectiveCloudDigest) { failed.push({ name, action: previous ? 'update' : 'add', error: 'Canonical Skill is unreadable' }); continue; } if (item.remoteItem) { item.remoteItem.resolution = resolution; if (resolution === 'hub' || resolution === 'known_online_old') { delete item.remoteItem.localContentDigest; delete item.remoteItem.localModifiedAtMs; } else { item.remoteItem.localContentDigest = effectiveCloudDigest; } } const acceptedVersionId = preserved ? registered?.hub?.versionId ?? item.versionId : item.versionId; const acceptedCloudDigest = preserved ? registered?.hub?.baseSha256 ?? previous?.sourceCloudDigest ?? (registered?.hub?.versionId === item.versionId ? sourceCloudDigest : undefined) : sourceCloudDigest; registerDiscoveredCapability(workspaceDir, profile, { type: 'skill', path: canonical, runtimeId: name, title: item.remoteItem?.title ?? name, description: item.remoteItem?.description, initialDescription: `Skill ${name}`, selectedByHub: item.kind !== 'local', ...(item.kind === 'hub' && item.resourceId && item.versionId ? { hub: { resourceId: item.resourceId, versionId: acceptedVersionId!, workspaceItemId: item.remoteItem?.workspaceItemId, publisher: item.publisher ?? 'community', baseSha256: acceptedCloudDigest, observedCloudVersionId: resolution === 'concurrent_difference' ? item.versionId : undefined, localOriginUnrecognized: resolution === 'local_origin_unrecognized' ? true : undefined, }, } : {}), }); next.entries[name] = { name, kind: item.kind, canonicalPath: canonical, sourceDigest: preserved ? previous?.sourceDigest ?? (registered?.hub?.versionId === item.versionId ? sourceDigest : undefined) : sourceDigest, remoteDigest: sourceDigest, sourceCloudDigest: acceptedCloudDigest, remoteCloudDigest: sourceCloudDigest, knownSourceDigests, knownCloudDigests, resourceId: item.resourceId, versionId: item.versionId, }; if (!previous) added.push(name); else if (applied && previous.sourceDigest !== sourceDigest) updated.push(name); else unchanged.push(name); } for (const [name] of Object.entries(current.entries)) { if (blockedNames.has(skillNameKey(name))) { next.entries[name] = current.entries[name]!; continue; } if (isPackageManagedSkill(name) || desired.has(name)) continue; const links = runSkillHostOperations(name, targets(name), unlinkTarget); skipped.push(...links.skipped); for (const result of links.failed) failed.push({ name, action: 'remove', error: resultError(result) }); if (links.failed.length) next.entries[name] = current.entries[name]!; else removed.push(name); } // Unequipping may happen before a first successful load created a manifest. // Keep reporting host-owned paths even in that case, without reopening selection. for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) { if (entry.type !== 'skill' || isPackageManagedSkill(entry.runtimeId) || blockedNames.has(skillNameKey(entry.runtimeId)) || desired.has(entry.runtimeId) || current.entries[entry.runtimeId]) continue; const inspection = runSkillHostOperations(entry.runtimeId, targets(entry.runtimeId)); skipped.push(...inspection.skipped.filter(item => item.reason === 'local_skill_directory_exists')); } writeManifest(workspaceDir, profile, next); return { added, updated, removed, unchanged, preservedModified, failed, ...(conflicts.length ? { conflicts } : {}), skipped, requiresUserConfirmation: false, }; }