import { accountRequiredMessage } from './desktop-mode.js'; import { randomUUID } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs'; import { dirname, join, basename } from 'path'; import { AuthStore, type AuthProfile } from './auth.js'; import { getWorkspaceDir } from './init-command.js'; import { ensureAccountUserDataLayout, getUserDataAccountPersonaSelectionFile, getUserDataAccountHubPersonasDir, getUserDataAccountPersonasDir, } from './user-data.js'; import { readLocalAgentWorkspaceSnapshot, resolveLocalAgentWorkspacePath, resolveLocalAgentWorkspaceWorkingCopyPath, type LocalAgentWorkspaceSnapshot, } from './agent-workspace-sync.js'; import { filterInactiveAgentWorkspaceSnapshot } from './capability-cloud-presence.js'; import { capabilityEntryForPath, readCapabilityWorkspaceRegistry, capabilityWorkspacePath, registerDiscoveredCapability } from './capability-workspace.js'; export interface PersonaPreset { id: string; name: string; path: string; } export function listPersonaPresets(dir: string): PersonaPreset[] { if (!existsSync(dir)) return []; return readdirSync(dir, { withFileTypes: true }) .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.md')) .map(entry => { const name = entry.name.slice(0, -3); return { id: name, name, path: join(dir, entry.name), }; }) .sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN')); } export function findPersonaPreset(name: string, dir: string): PersonaPreset | null { const normalized = normalizePersonaName(name); return listPersonaPresets(dir).find(preset => normalizePersonaName(preset.id) === normalized || normalizePersonaName(preset.name) === normalized || normalizePersonaName(basename(preset.path)) === normalized, ) ?? null; } export function createPersonaPreset(name: string, dir: string): PersonaPreset { const id = name.trim().replace(/\.md$/i, ''); if ( !id || id.length > 80 || /[<>:"/\\|?*\u0000-\u001f]/u.test(id) || id === '.' || id === '..' ) { throw new Error('persona_name_invalid'); } mkdirSync(dir, { recursive: true }); const path = join(dir, `${id}.md`); try { writeFileSync(path, '', { encoding: 'utf8', flag: 'wx' }); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') { throw new Error(`Persona preset "${id}" already exists.`); } throw error; } return { id, name: id, path }; } export type PersonaSelection = | { source: 'local'; id: string } | { source: 'hub' } | { source: 'none' }; export interface ResolvedPersonaFile { path: string | null; source: 'local' | 'hub' | 'none'; id?: string; resourceId?: string; } function writeJsonAtomically(path: string, value: unknown): void { mkdirSync(dirname(path), { recursive: true }); const temporary = `${path}.${randomUUID()}.tmp`; writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8'); renameSync(temporary, path); } function parseSelection(path: string): PersonaSelection | undefined { if (!existsSync(path)) return undefined; try { const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record; if (parsed.source === 'hub' || parsed.source === 'none') return { source: parsed.source }; if (parsed.source === 'local' && typeof parsed.id === 'string' && parsed.id.trim()) { return { source: 'local', id: parsed.id }; } } catch {} throw new Error('persona_selection_invalid'); } export function readPersonaSelection( workspaceDir: string, profile: Pick, ): PersonaSelection | undefined { return parseSelection(getUserDataAccountPersonaSelectionFile(workspaceDir, profile)); } export function writePersonaSelection( workspaceDir: string, profile: Pick, selection: PersonaSelection, ): void { writeJsonAtomically(getUserDataAccountPersonaSelectionFile(workspaceDir, profile), selection); } function hubPersona( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot | undefined, ): ResolvedPersonaFile | undefined { const item = snapshot?.items.persona[0]; if (!item) return undefined; let working = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item); const sourcePath = item.sourceFiles[0]?.relativePath; if ( !working && /^[A-Za-z0-9._-]+$/.test(item.resourceId) && sourcePath && basename(sourcePath) === sourcePath ) { working = join(getUserDataAccountHubPersonasDir(workspaceDir, profile), item.resourceId, sourcePath); } if (working && existsSync(working)) { const entry = registerDiscoveredCapability(workspaceDir, profile, { type: 'persona', path: working, runtimeId: basename(working, '.md'), selectedByHub: true, hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId, ownerId: item.hub?.ownerId, ownerName: item.hub?.ownerName, pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined, ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}), publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 }, }); return { path: working, source: 'hub', resourceId: item.resourceId, id: entry.runtimeId }; } if (item.runtimeEntryPath) { const runtime = resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot!, item.runtimeEntryPath); if (existsSync(runtime)) return { path: runtime, source: 'hub', resourceId: item.resourceId }; } return { path: working ?? null, source: 'hub', resourceId: item.resourceId }; } export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedPersonaFile { const profile = authStore.getActive(); if (!profile) throw new Error(accountRequiredMessage('Not logged in.')); const workspaceDir = getWorkspaceDir(); ensureAccountUserDataLayout(workspaceDir, profile); const snapshot = filterInactiveAgentWorkspaceSnapshot( workspaceDir, profile, readLocalAgentWorkspaceSnapshot(workspaceDir, profile), ); const selectedHub = hubPersona(workspaceDir, profile, snapshot); const selection = readPersonaSelection(workspaceDir, profile) ?? (selectedHub ? { source: 'hub' as const } : { source: 'none' as const }); if (selection?.source === 'local') { const selectedEntry = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .find(entry => entry.type === 'persona' && entry.runtimeId === selection.id); if (selectedEntry) { if (selectedEntry.hub || selectedEntry.selection !== 'equipped') return selectedHub ?? { path: null, source: 'none' }; return { path: capabilityWorkspacePath(workspaceDir, profile, selectedEntry), source: 'local', id: selectedEntry.runtimeId }; } const preset = findPersonaPreset(selection.id, getUserDataAccountPersonasDir(workspaceDir, profile)); const entry = preset ? capabilityEntryForPath(workspaceDir, profile, 'persona', preset.path) : undefined; if (entry?.hub) return selectedHub ?? { path: null, source: 'none' }; if (entry && entry.selection !== 'equipped') return selectedHub ?? { path: null, source: 'none' }; return { path: preset?.path ?? null, source: 'local', id: selection.id }; } if (selectedHub) return selectedHub; const local = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .find(entry => entry.type === 'persona' && !entry.hub && entry.selection === 'equipped'); if (local) return { path: capabilityWorkspacePath(workspaceDir, profile, local), source: 'local', id: local.runtimeId }; if (selection?.source === 'none') return { path: null, source: 'none' }; return selectedHub ?? { path: null, source: 'none' }; } export function readPersonaFile(path: string): string { return existsSync(path) ? readFileSync(path, 'utf8') : ''; } function normalizePersonaName(value: string): string { return value.trim().replace(/\.md$/i, '').toLowerCase(); }