import { isPackageManagedSkill } from './package-skills.js'; import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs'; import { createHash, randomUUID } from 'node:crypto'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import type { AuthProfile } from './auth.js'; import { getUserDataAccountCapabilitiesDir, getUserDataAccountCapabilityRegistryFile, getUserDataAccountDraftsDir, getUserDataAccountDir, } from './user-data.js'; export type CapabilityWorkspaceType = 'behavior' | 'perception' | 'persona' | 'skill'; export type CapabilitySelection = 'pending' | 'equipped' | 'unequipped'; export type StrategyLifecycle = 'long' | 'short'; export interface CapabilityHubIdentity { resourceId: string; versionId: string; workspaceItemId?: string; publisher: 'official' | 'self' | 'community'; ownerId?: string; ownerName?: string | null; baseSha256?: string; lastUploadedSha256?: string; pendingBackpackRestoreResourceId?: string; /** Retry a local equipment choice after the cloud resource itself was created successfully. */ pendingEquipment?: boolean; observedCloudVersionId?: string; /** Retain a bridged A→B conflict even while B is unequipped. */ pendingForkConflict?: boolean; forkRelationshipUnresolved?: boolean; /** The working copy existed before CCL had a trustworthy Hub baseline. */ localOriginUnrecognized?: boolean; /** Cloud association is retained locally but automatic cloud I/O is suspended. */ cloudStatus?: 'workspace_missing'; } export interface CapabilityWorkspaceEntry { key: string; type: CapabilityWorkspaceType; origin: 'local' | 'hub'; relativePath: string; runtimeId: string; /** Original source identity. runtimeId becomes the stable Agent operation name on equip. */ declaredId?: string; /** New local discoveries have only a selection reference until first equip. */ operationNameAssigned?: boolean; title: string; description: string; selection: CapabilitySelection; strategyLifecycle?: StrategyLifecycle; conflictChoice?: 'local'; hub?: CapabilityHubIdentity; discoveredAt: string; updatedAt: string; } export interface CapabilityWorkspaceRegistry { format: 1; entries: Record; } const EMPTY = (): CapabilityWorkspaceRegistry => ({ format: 1, entries: {} }); const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/; function pathInside(root: string, candidate: string): boolean { const child = relative(resolve(root), resolve(candidate)); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function normalizedRelativePath(root: string, path: string): string { const absolute = resolve(path); if (!pathInside(root, absolute)) throw new Error('capability_workspace_path_escape'); const value = relative(resolve(root), absolute).replaceAll('\\', '/'); if (!value || value.split('/').some((segment) => !segment || segment === '.' || segment === '..')) { throw new Error('capability_workspace_relative_path_invalid'); } return value; } function registryKey(type: CapabilityWorkspaceType, relativePath: string): string { return `${type}:${relativePath}`; } function writeRegistryFile(path: string, registry: CapabilityWorkspaceRegistry): void { mkdirSync(dirname(path), { recursive: true }); const temporary = `${path}.${randomUUID()}.tmp`; writeFileSync(temporary, `${JSON.stringify(registry, null, 2)}\n`, 'utf8'); renameSync(temporary, path); } export function readCapabilityWorkspaceRegistry( workspaceDir: string, profile: Pick, ): CapabilityWorkspaceRegistry { const path = getUserDataAccountCapabilityRegistryFile(workspaceDir, profile); if (!existsSync(path)) return EMPTY(); try { const value = JSON.parse(readFileSync(path, 'utf8')) as CapabilityWorkspaceRegistry; if (value.format !== 1 || !value.entries || typeof value.entries !== 'object') return EMPTY(); return value; } catch { return EMPTY(); } } export function writeCapabilityWorkspaceRegistry( workspaceDir: string, profile: Pick, registry: CapabilityWorkspaceRegistry, ): void { writeRegistryFile(getUserDataAccountCapabilityRegistryFile(workspaceDir, profile), registry); } export function registerDiscoveredCapability( workspaceDir: string, profile: Pick, input: { type: CapabilityWorkspaceType; path: string; runtimeId: string; title?: string; description?: string; initialDescription?: string; strategyLifecycle?: StrategyLifecycle; hub?: CapabilityHubIdentity; selectedByHub?: boolean; }, ): CapabilityWorkspaceEntry { const validRuntimeId = input.type === 'persona' ? !!input.runtimeId.trim() && input.runtimeId.length <= 255 && !/[\\/\u0000-\u001f]/u.test(input.runtimeId) : SAFE_ID.test(input.runtimeId); if (!validRuntimeId) throw new Error('capability_workspace_runtime_id_invalid'); const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile); const relativePath = normalizedRelativePath(root, input.path); const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const existingByResource = input.hub ? Object.values(registry.entries).find((entry) => ( entry.type === input.type && entry.hub?.resourceId === input.hub?.resourceId )) : undefined; const key = existingByResource?.key ?? registryKey(input.type, relativePath); const now = new Date().toISOString(); const previous = registry.entries[key]; const declaredId = input.runtimeId; const operationNameAssigned = input.type === 'skill' || (previous?.operationNameAssigned !== false && (previous !== undefined || input.selectedByHub === true)); const assigningNow = input.type !== 'skill' && input.selectedByHub === true && previous?.operationNameAssigned === false; const occupied = new Set(Object.values(registry.entries) .filter(entry => entry.type === input.type && entry.key !== key && (!operationNameAssigned || entry.operationNameAssigned !== false)) .map(entry => entry.runtimeId)); let runtimeId = assigningNow ? declaredId : previous?.runtimeId ?? declaredId; // Already assigned operation names stay reserved across deselection. A new // pending item has only a provisional management name and selection_ref. for (let suffix = 1; input.type !== 'skill' && occupied.has(runtimeId); suffix++) { const tail = `_${suffix}`; runtimeId = `${declaredId.slice(0, 255 - tail.length)}${tail}`; } const entry: CapabilityWorkspaceEntry = { key, type: input.type, origin: previous?.origin ?? (input.selectedByHub ? 'hub' : 'local'), relativePath, runtimeId, declaredId, operationNameAssigned: operationNameAssigned || assigningNow, // Only a Hub snapshot may replace existing human-facing text. Rediscovering // a script must not overwrite it with Agent-facing documentation. title: (input.selectedByHub ? input.title?.trim() : undefined) || previous?.title || Array.from(input.title?.trim() || input.runtimeId).slice(0, 50).join(''), description: (input.selectedByHub ? input.description?.trim() : undefined) || previous?.description || Array.from(input.description?.trim() || input.initialDescription?.trim() || `${input.type} ${input.runtimeId}`).slice(0, 600).join(''), selection: input.selectedByHub ? 'equipped' : previous?.selection ?? 'pending', ...(input.strategyLifecycle ? { strategyLifecycle: input.strategyLifecycle } : {}), ...(previous?.conflictChoice ? { conflictChoice: previous.conflictChoice } : {}), ...(input.hub ? { hub: { ...previous?.hub, ...input.hub } } : previous?.hub ? { hub: previous.hub } : {}), discoveredAt: previous?.discoveredAt ?? now, updatedAt: now, }; if (previous && previous.relativePath !== relativePath) delete registry.entries[previous.key]; registry.entries[key] = entry; writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); return entry; } /** Stable management selector, independent of an Agent operation name. */ export function capabilitySelectionRef(entry: Pick): string { const digest = createHash('sha256').update(entry.key, 'utf8').digest('hex'); return `${entry.type}/@${digest}`; } export function assignCapabilityOperationName( registry: CapabilityWorkspaceRegistry, entry: CapabilityWorkspaceEntry, ): void { if (entry.type === 'skill' || entry.operationNameAssigned !== false) return; const declaredId = entry.declaredId ?? entry.runtimeId; const occupied = new Set(Object.values(registry.entries) .filter(other => other.key !== entry.key && other.type === entry.type && other.operationNameAssigned !== false).map(other => other.runtimeId)); let operationName = declaredId; for (let suffix = 1; occupied.has(operationName); suffix++) { const tail = `_${suffix}`; operationName = `${declaredId.slice(0, 255 - tail.length)}${tail}`; } entry.runtimeId = operationName; entry.operationNameAssigned = true; } export function capabilityEntryForPath( workspaceDir: string, profile: Pick, type: CapabilityWorkspaceType, path: string, ): CapabilityWorkspaceEntry | undefined { const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile); const relativePath = normalizedRelativePath(root, path); const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); return registry.entries[registryKey(type, relativePath)] ?? Object.values(registry.entries).find((entry) => ( entry.type === type && entry.relativePath === relativePath )); } export function capabilityEntryForHubResource( workspaceDir: string, profile: Pick, type: CapabilityWorkspaceType, resourceId: string, ): CapabilityWorkspaceEntry | undefined { return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .find((entry) => entry.type === type && entry.hub?.resourceId === resourceId); } export function setCapabilitySelection( workspaceDir: string, profile: Pick, type: CapabilityWorkspaceType, runtimeId: string, equipped: boolean, ): CapabilityWorkspaceEntry { const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const matches = Object.values(registry.entries) .filter((entry) => entry.type === type && entry.origin === 'local' && (runtimeId.startsWith('@') ? capabilitySelectionRef(entry) === `${type}/${runtimeId}` : entry.runtimeId === runtimeId)); if (matches.length !== 1) throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${runtimeId}`); const entry = matches[0]!; if (equipped) assignCapabilityOperationName(registry, entry); entry.selection = equipped ? 'equipped' : 'unequipped'; entry.updatedAt = new Date().toISOString(); writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); return entry; } export function updateCapabilityDisplayMetadata( workspaceDir: string, profile: Pick, key: string, display: { title?: string; description?: string }, ): void { const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const entry = registry.entries[key]; if (!entry) return; if (display.title?.trim()) entry.title = display.title.trim(); if (display.description?.trim()) entry.description = display.description.trim(); writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); } export function updateCapabilityHubIdentity( workspaceDir: string, profile: Pick, key: string, hub: CapabilityHubIdentity, ): CapabilityWorkspaceEntry { const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const entry = registry.entries[key]; if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`); entry.hub = { ...entry.hub, ...hub }; entry.updatedAt = new Date().toISOString(); writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); return entry; } export function setCapabilityConflictChoice( workspaceDir: string, profile: Pick, key: string, choice: 'local' | undefined, ): CapabilityWorkspaceEntry { const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const entry = registry.entries[key]; if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`); if (choice) entry.conflictChoice = choice; else delete entry.conflictChoice; entry.updatedAt = new Date().toISOString(); writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); return entry; } export function pendingCapabilitySelections( workspaceDir: string, profile: Pick, ): readonly CapabilityWorkspaceEntry[] { return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .filter((entry) => entry.origin === 'local' && entry.selection === 'pending' && !(entry.type === 'skill' && isPackageManagedSkill(entry.runtimeId))) .sort((left, right) => left.discoveredAt.localeCompare(right.discoveredAt)); } export function capabilityWorkspacePath( workspaceDir: string, profile: Pick, entry: Pick, ): string { const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile); const path = resolve(root, ...entry.relativePath.split('/')); if (!pathInside(root, path)) throw new Error('capability_workspace_path_escape'); return path; } export function saveCapabilityDraft( workspaceDir: string, profile: Pick, input: { type: CapabilityWorkspaceType; runtimeId: string; bytes: Buffer; extension: string }, ): string { const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability'; const directory = join( getUserDataAccountDraftsDir(workspaceDir, profile), input.type, `${safeRuntimeId}-${randomUUID()}`, ); mkdirSync(directory, { recursive: true }); const path = join(directory, `${safeRuntimeId}${input.extension}`); writeFileSync(path, input.bytes); return path; } export function saveCapabilityDirectoryDraft( workspaceDir: string, profile: Pick, input: { type: CapabilityWorkspaceType; runtimeId: string; sourcePath: string }, ): string { const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability'; const directory = join( getUserDataAccountDraftsDir(workspaceDir, profile), input.type, `${safeRuntimeId}-${randomUUID()}`, ); mkdirSync(dirname(directory), { recursive: true }); cpSync(input.sourcePath, directory, { recursive: true, errorOnExist: true }); return directory; } /** Product classification: a Behavior that can emit a finish effect is short. */ export function classifyStrategyLifecycle(source: string): StrategyLifecycle { return /\bfinish\s*:|\bfinished\s*\(/.test(source) ? 'short' : 'long'; }