import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import { createHash, randomUUID } from 'node:crypto'; import { tmpdir } from 'node:os'; import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'; import type { AuthProfile } from './auth.js'; import { capabilityWorkspacePath, readCapabilityWorkspaceRegistry, updateCapabilityHubIdentity, updateCapabilityDisplayMetadata, type CapabilityWorkspaceEntry, type CapabilityWorkspaceType, } from './capability-workspace.js'; import type { LocalAgentWorkspaceSnapshot } from './agent-workspace-sync.js'; import { HubClient, type ResourceType } from './hub-client.js'; import { findSkillRoot, overwriteAgentSkillTarget } from './skill-host.js'; import { unzip } from './hub-unzip.js'; import { zipContentDigest } from './zip-store.js'; import { selectedSkillNameConflicts, skillNameCandidate, skillNameKey } from './skill-name-conflicts.js'; export interface CapabilityCloudDownload { type: CapabilityWorkspaceType; id: string; resource_id: string; version_id: string; result: 'updated' | 'converged'; } export interface CapabilityCloudRefreshConflict { type: CapabilityWorkspaceType; id: string; resource_id: string; reason: 'local_and_cloud_changed'; } export interface CapabilityCloudRefreshFailure { type: CapabilityWorkspaceType; id: string; action: 'download'; error: string; } export interface CapabilityCloudRefreshResult { downloaded: CapabilityCloudDownload[]; conflicts: CapabilityCloudRefreshConflict[]; failed: CapabilityCloudRefreshFailure[]; unchanged: Array<{ type: CapabilityWorkspaceType; id: string }>; } interface CapabilityCloudRefreshClient { getResource(type: ResourceType, id: string, workspaceItemId?: string): ReturnType; downloadArtifact(type: ResourceType, id: string, workspaceItemId?: string): ReturnType; findWorkspaceItem(type: ResourceType, resourceId: string): ReturnType; syncWorkspaceItem(workspaceItemId: string): ReturnType; listWorkspace(opts?: Parameters[0]): ReturnType; } export interface CapabilityCloudRefreshDependencies { client?: CapabilityCloudRefreshClient; } export interface InstalledCapabilityUpdateResult { updated: Array<{ type: ResourceType; resource_id: string; workspace_item_id: string; version_id: string; }>; failed: Array<{ type: ResourceType; resource_id: string; workspace_item_id: string; error: string; }>; inventory: Awaited>['items']; inventoryComplete: boolean; } export async function syncInstalledCapabilityUpdates( profile: Pick, dependencies: CapabilityCloudRefreshDependencies = {}, ): Promise { const client = dependencies.client ?? HubClient.fromProfile(profile); const result: InstalledCapabilityUpdateResult = { updated: [], failed: [], inventory: [], inventoryComplete: false, }; let cursor: string | undefined; do { const page = await client.listWorkspace({ cursor, limit: 100 }); result.inventory.push(...page.items); cursor = page.hasMore && page.nextCursor ? page.nextCursor : undefined; } while (cursor); for (const item of result.inventory.filter((candidate) => candidate.hasUpdate)) { try { const synced = await client.syncWorkspaceItem(item.workspaceItemId); item.versionId = synced.versionId; item.hasUpdate = false; result.updated.push({ type: item.resourceType, resource_id: item.resourceId, workspace_item_id: item.workspaceItemId, version_id: synced.versionId, }); } catch (error) { result.failed.push({ type: item.resourceType, resource_id: item.resourceId, workspace_item_id: item.workspaceItemId, error: error instanceof Error ? error.message : String(error), }); } } result.inventoryComplete = true; return result; } function resourceType(type: CapabilityWorkspaceType): ResourceType { return type === 'behavior' ? 'strategy' : type; } function sha256(bytes: Buffer): string { return createHash('sha256').update(bytes).digest('hex'); } function collectSkill(root: string): Array<{ path: string; content: Buffer }> { const files: Array<{ path: string; content: Buffer }> = []; const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const path = join(directory, entry.name); const stat = lstatSync(path); if (stat.isSymbolicLink()) throw new Error('skill_source_symlink_unsupported'); if (stat.isDirectory()) visit(path); else if (stat.isFile()) files.push({ path: relative(root, path).replaceAll('\\', '/'), content: readFileSync(path), }); } }; visit(root); if (files.length === 0) throw new Error('skill_source_empty'); return files; } function localDigest(entry: CapabilityWorkspaceEntry, path: string): string { return entry.type === 'skill' ? zipContentDigest(collectSkill(path)) : sha256(readFileSync(path)); } function pathInside(root: string, candidate: string): boolean { const child = relative(resolve(root), resolve(candidate)); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function prepareCloudArtifact(entry: CapabilityWorkspaceEntry, bytes: Buffer): { digest: string; apply(target: string): void; cleanup(): void; } { if (entry.type !== 'skill') { return { digest: sha256(bytes), apply(target: string) { const stage = `${target}.ccl-cloud-${randomUUID()}.tmp`; const displaced = `${target}.ccl-old-${randomUUID()}.tmp`; let moved = false; writeFileSync(stage, bytes); try { renameSync(target, displaced); moved = true; renameSync(stage, target); if (sha256(readFileSync(target)) !== sha256(bytes)) { throw new Error('capability_cloud_write_verification_failed'); } rmSync(displaced, { force: true }); } catch (error) { rmSync(stage, { force: true }); if (moved && existsSync(displaced)) { rmSync(target, { force: true }); try { renameSync(displaced, target); } catch { /* retain displaced recovery copy */ } } throw error; } }, cleanup() {}, }; } const stage = mkdtempSync(join(tmpdir(), 'ccl-capability-refresh-')); try { for (const file of unzip(bytes)) { const target = resolve(stage, ...file.path.split('/')); if (!pathInside(stage, target) || target === resolve(stage)) { throw new Error('capability_cloud_skill_path_invalid'); } mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, file.content); } const root = findSkillRoot(stage); if (!existsSync(join(root, 'SKILL.md'))) throw new Error('capability_cloud_skill_invalid'); return { digest: zipContentDigest(collectSkill(root)), apply(target: string) { const replaced = overwriteAgentSkillTarget(root, target); if (!replaced.ok) throw new Error(replaced.error ?? 'capability_cloud_restore_failed'); }, cleanup() { rmSync(stage, { recursive: true, force: true }); }, }; } catch (error) { rmSync(stage, { recursive: true, force: true }); throw error; } } function activeResourceIds(snapshot: LocalAgentWorkspaceSnapshot | undefined): Set { if (!snapshot) return new Set(); return new Set(Object.values(snapshot.items).flat().map((item) => item.resourceId)); } export async function refreshCapabilitiesFromCloud( workspaceDir: string, profile: Pick, activeWorkspace?: LocalAgentWorkspaceSnapshot, dependencies: CapabilityCloudRefreshDependencies = {}, ): Promise { const client = dependencies.client ?? HubClient.fromProfile(profile); const result: CapabilityCloudRefreshResult = { downloaded: [], conflicts: [], failed: [], unchanged: [] }; const active = activeResourceIds(activeWorkspace); const blockedSkillNames = new Set(selectedSkillNameConflicts(workspaceDir, profile, activeWorkspace).map(item => item.name)); const unresolvedParents = new Set(Object.values(activeWorkspace?.items ?? {}).flat().flatMap(item => item.forkReconciliation?.status === 'unresolved' ? [item.forkReconciliation.parentResourceId] : [])); const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .filter((entry) => ( entry.runtimeId !== 'clawclaw' && entry.hub && !entry.hub.cloudStatus && !entry.hub.forkRelationshipUnresolved && !active.has(entry.hub.resourceId) && !unresolvedParents.has(entry.hub.resourceId) )); for (const entry of entries) { if (entry.type === 'skill' && blockedSkillNames.has(skillNameKey(skillNameCandidate(workspaceDir, profile, entry).name))) continue; const hub = entry.hub!; const type = resourceType(entry.type); const path = capabilityWorkspacePath(workspaceDir, profile, entry); try { const before = localDigest(entry, path); let workspaceItemId = hub.publisher === 'self' ? undefined : hub.workspaceItemId; if (hub.publisher !== 'self') { const workspaceItem = await client.findWorkspaceItem(type, hub.resourceId); if (!workspaceItem) throw new Error('capability_cloud_workspace_item_missing'); workspaceItemId = workspaceItem.workspaceItemId; if (workspaceItem.hasUpdate) await client.syncWorkspaceItem(workspaceItem.workspaceItemId); } const detail = await client.getResource(type, hub.resourceId, workspaceItemId); if (detail.versionId === hub.versionId) { updateCapabilityDisplayMetadata(workspaceDir, profile, entry.key, detail); if ( hub.observedCloudVersionId || (hub.pendingForkConflict && before === hub.baseSha256) || (hub.localOriginUnrecognized && ( before === hub.baseSha256 || before === hub.lastUploadedSha256 )) ) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, { ...hub, observedCloudVersionId: undefined, pendingForkConflict: before === hub.baseSha256 ? undefined : hub.pendingForkConflict, localOriginUnrecognized: before === hub.baseSha256 || before === hub.lastUploadedSha256 ? undefined : hub.localOriginUnrecognized, }); result.unchanged.push({ type: entry.type, id: entry.runtimeId }); continue; } const artifact = prepareCloudArtifact( entry, await client.downloadArtifact(type, hub.resourceId, workspaceItemId), ); try { const afterDownload = localDigest(entry, path); if (afterDownload !== before) { updateCapabilityHubIdentity(workspaceDir, profile, entry.key, { ...hub, ...(workspaceItemId ? { workspaceItemId } : {}), observedCloudVersionId: detail.versionId, }); if (entry.conflictChoice !== 'local') result.conflicts.push({ type: entry.type, id: entry.runtimeId, resource_id: hub.resourceId, reason: 'local_and_cloud_changed', }); continue; } const localUnmodified = before === hub.baseSha256 || before === hub.lastUploadedSha256; if (before !== artifact.digest && !localUnmodified) { updateCapabilityHubIdentity(workspaceDir, profile, entry.key, { ...hub, ...(workspaceItemId ? { workspaceItemId } : {}), observedCloudVersionId: detail.versionId, }); if (entry.conflictChoice !== 'local') result.conflicts.push({ type: entry.type, id: entry.runtimeId, resource_id: hub.resourceId, reason: 'local_and_cloud_changed', }); continue; } const convergence = before === artifact.digest; if (!convergence) artifact.apply(path); updateCapabilityDisplayMetadata(workspaceDir, profile, entry.key, detail); updateCapabilityHubIdentity(workspaceDir, profile, entry.key, { ...hub, versionId: detail.versionId, ...(workspaceItemId ? { workspaceItemId } : {}), baseSha256: artifact.digest, lastUploadedSha256: artifact.digest, observedCloudVersionId: undefined, localOriginUnrecognized: undefined, pendingForkConflict: undefined, }); result.downloaded.push({ type: entry.type, id: entry.runtimeId, resource_id: hub.resourceId, version_id: detail.versionId, result: convergence ? 'converged' : 'updated', }); } finally { artifact.cleanup(); } } catch (error) { result.failed.push({ type: entry.type, id: entry.runtimeId, action: 'download', error: error instanceof Error ? error.message : String(error), }); } } return result; }