import { harnessContext, stateRoot } from './harness-context.js'; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync, } from 'fs'; import { createHash } from 'crypto'; import { dirname, join } from 'path'; import type { AuthData, AuthProfile } from './auth.js'; export const USER_DATA_DIR = 'user-data'; export const RUNTIME_DIR = 'runtime'; export interface UserDataMigrationResult { copied: string[]; skipped: string[]; skippedExisting: string[]; } export interface RuntimeAuthStateProfile { gameServerUrl?: string; updatedAt?: string; } export interface RuntimeAuthState { profiles: Record; } const EMPTY_RESULT = (): UserDataMigrationResult => ({ copied: [], skipped: [], skippedExisting: [], }); export function getUserDataDir(workspaceDir: string): string { return join(workspaceDir, USER_DATA_DIR); } export function getRuntimeDir(workspaceDir: string): string { return join(stateRoot(workspaceDir), RUNTIME_DIR); } export function getUserDataAuthFile(workspaceDir: string): string { return join(getUserDataDir(stateRoot(workspaceDir)), 'auth.json'); } export function getRuntimeAuthStateFile(workspaceDir: string): string { return join(getRuntimeDir(workspaceDir), 'auth-state.json'); } export function getUserDataAccountsDir(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'accounts'); } export function getUserDataAccountHash(apiKey: string): string { return createHash('sha256').update(apiKey).digest('hex').slice(0, 16); } export function getUserDataAccountDir(workspaceDir: string, profile: Pick): string { return join(getUserDataAccountsDir(workspaceDir), getUserDataAccountHash(profile.apiKey)); } export function getUserDataPersonaFile(workspaceDir: string, profile: Pick): string { return join(getUserDataAccountDir(workspaceDir, profile), 'persona.md'); } export function getUserDataMemoryFile(workspaceDir: string, profile: Pick): string { return join(getUserDataAccountDir(workspaceDir, profile), 'memory.md'); } export function getUserDataAgentWorkspaceDir( workspaceDir: string, profile: Pick, ): string { const directory = join(getUserDataAccountDir(workspaceDir, profile), 'hub-loadout'); // Staging and validating an update must use the same directory the module scanner sees. return existsSync(directory) ? realpathSync(directory) : directory; } export function getUserDataAgentWorkspaceCurrentFile( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAgentWorkspaceDir(workspaceDir, profile), 'current.json'); } export function getUserDataAgentWorkspaceRevisionsDir( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAgentWorkspaceDir(workspaceDir, profile), 'revisions'); } export function getUserDataAccountLocalDir( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountDir(workspaceDir, profile), 'local'); } export function getUserDataAccountCapabilitiesDir( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountDir(workspaceDir, profile), 'capabilities'); } export function getUserDataAccountDraftsDir( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountDir(workspaceDir, profile), 'drafts'); } export function getUserDataAccountCapabilityRegistryFile( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'registry.json'); } export function getUserDataAccountBehaviorsRoot( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'behaviors'); } export function getUserDataAccountBehaviorsDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountBehaviorsRoot(workspaceDir, profile); } export function getUserDataAccountHubBehaviorsDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountBehaviorsRoot(workspaceDir, profile); } export function getUserDataAccountPerceptionsRoot( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'perceptions'); } export function getUserDataAccountPerceptionsDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountPerceptionsRoot(workspaceDir, profile); } export function getUserDataAccountHubPerceptionsDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountPerceptionsRoot(workspaceDir, profile); } export function getUserDataAccountPersonasRoot( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'personas'); } export function getUserDataAccountPersonasDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountPersonasRoot(workspaceDir, profile); } export function getUserDataAccountHubPersonasDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountPersonasRoot(workspaceDir, profile); } export function getUserDataAccountPersonaSelectionFile( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountPersonasRoot(workspaceDir, profile), 'selection.json'); } export function getUserDataAccountTriggersRoot( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'triggers'); } export function getUserDataAccountTriggersDir( workspaceDir: string, profile: Pick, ): string { return getUserDataAccountTriggersRoot(workspaceDir, profile); } export function getUserDataAccountSkillsDir( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'skills'); } export function getUserDataAccountGameplayConfigFile( workspaceDir: string, profile: Pick, ): string { return join(getUserDataAccountDir(workspaceDir, profile), 'gameplay.json'); } export function getUserDataBehaviorsDir(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'behaviors'); } export function getUserDataPerceptionsDir(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'perceptions'); } export function getUserDataTriggersDir(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'triggers'); } export function getUserDataGameplayConfigFile(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'gameplay.json'); } export function getUserDataDiagnosticsConfigFile(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'diagnostics.json'); } export function getUserDataOfficialBehaviorsManifestFile(workspaceDir: string): string { return join(getUserDataBehaviorsDir(workspaceDir), '.official-manifest.json'); } export function getUserDataOfficialPerceptionsManifestFile(workspaceDir: string): string { return join(getUserDataPerceptionsDir(workspaceDir), '.official-manifest.json'); } export function getUserDataOfficialTriggersManifestFile(workspaceDir: string): string { return join(getUserDataTriggersDir(workspaceDir), '.official-manifest.json'); } export function getUserDataHubDir(workspaceDir: string): string { return join(getUserDataDir(workspaceDir), 'hub'); } function ensureDir(path: string): void { mkdirSync(path, { recursive: true }); } function readJson(path: string): T | null { if (!existsSync(path)) return null; try { return JSON.parse(readFileSync(path, 'utf8')) as T; } catch { return null; } } function writeJson(path: string, data: unknown): void { ensureDir(dirname(path)); writeFileSync(path, JSON.stringify(data, null, 2) + '\n', 'utf8'); } export function splitAuthData(data: AuthData): { auth: AuthData; runtime: RuntimeAuthState; changed: boolean; } { const auth: AuthData = { ...data, activeProfile: data.activeProfile ?? '', profiles: Object.fromEntries( Object.entries(data.profiles ?? {}).map(([name, profile]) => [name, { ...profile }]), ), }; const runtime: RuntimeAuthState = { profiles: {} }; let changed = false; const longTermProfiles: Record = {}; for (const [name, originalProfile] of Object.entries(auth.profiles ?? {})) { const { gameServerUrl, tts, ...longTermProfile } = originalProfile as AuthProfile & { tts?: unknown }; longTermProfiles[name] = longTermProfile; if (gameServerUrl) { runtime.profiles[name] = { gameServerUrl, updatedAt: new Date().toISOString() }; changed = true; } if (tts !== undefined) changed = true; } auth.profiles = longTermProfiles; if ('ttsKeys' in auth) { delete (auth as AuthData & { ttsKeys?: unknown }).ttsKeys; changed = true; } if ('neteaseTtsKey' in auth) { delete (auth as AuthData & { neteaseTtsKey?: unknown }).neteaseTtsKey; changed = true; } return { auth, runtime, changed }; } export function readRuntimeAuthState(path: string): RuntimeAuthState { return readJson(path) ?? { profiles: {} }; } export function writeRuntimeAuthState(path: string, state: RuntimeAuthState): void { writeJson(path, { profiles: state.profiles ?? {} }); } function mergeRuntimeAuthState(path: string, incoming: RuntimeAuthState, result?: UserDataMigrationResult): void { const incomingEntries = Object.entries(incoming.profiles ?? {}).filter(([, profile]) => profile.gameServerUrl); if (incomingEntries.length === 0) return; const current = readRuntimeAuthState(path); let changed = false; for (const [name, profile] of incomingEntries) { if (current.profiles[name]?.gameServerUrl) { result?.skippedExisting.push(`runtime/auth-state.json profiles.${name}.gameServerUrl`); continue; } current.profiles[name] = profile; changed = true; } if (changed) { writeRuntimeAuthState(path, current); result?.copied.push('auth gameServerUrl -> runtime/auth-state.json'); } } function migrateAuth(workspaceDir: string, result: UserDataMigrationResult): AuthData | null { const legacyAuthFile = join(workspaceDir, '.auth.json'); const authFile = getUserDataAuthFile(workspaceDir); const runtimeFile = getRuntimeAuthStateFile(workspaceDir); const source = existsSync(authFile) ? readJson(authFile) : readJson(legacyAuthFile); if (!source) return null; const { auth, runtime, changed } = splitAuthData(source); if (!existsSync(authFile)) { writeJson(authFile, auth); result.copied.push('.auth.json -> user-data/auth.json'); } else if (changed) { writeJson(authFile, auth); result.copied.push('normalized user-data/auth.json'); } mergeRuntimeAuthState(runtimeFile, runtime, result); return auth; } function migrateAccountFiles(workspaceDir: string, auth: AuthData | null, result: UserDataMigrationResult): void { if (!auth) return; for (const profile of Object.values(auth.profiles ?? {})) { const legacyDir = join(workspaceDir, 'accounts', profile.apiKey); const newDir = getUserDataAccountDir(workspaceDir, profile); for (const fileName of ['persona.md', 'memory.md']) { const from = join(legacyDir, fileName); const to = join(newDir, fileName); if (!existsSync(from)) continue; if (existsSync(to)) { result.skippedExisting.push(`user-data/accounts/${getUserDataAccountHash(profile.apiKey)}/${fileName}`); continue; } ensureDir(dirname(to)); copyFileSync(from, to); result.copied.push(`accounts//${fileName} -> user-data/accounts//${fileName}`); } } } function writeMigrationMarker(workspaceDir: string, result: UserDataMigrationResult): void { if (result.copied.length === 0 && result.skipped.length === 0 && result.skippedExisting.length === 0) return; const marker = join(getUserDataDir(workspaceDir), '.migration.json'); if (existsSync(marker)) return; writeJson(marker, { from: 'legacy-workspace-layout', migrated_at: new Date().toISOString(), copied: result.copied, skipped: result.skipped, skipped_existing: result.skippedExisting, }); } export function ensureUserDataLayout(workspaceDir: string): UserDataMigrationResult { const result = EMPTY_RESULT(); ensureDir(getUserDataDir(workspaceDir)); ensureDir(getUserDataAccountsDir(workspaceDir)); ensureDir(getUserDataBehaviorsDir(workspaceDir)); ensureDir(getUserDataPerceptionsDir(workspaceDir)); ensureDir(getUserDataTriggersDir(workspaceDir)); ensureDir(getUserDataHubDir(workspaceDir)); ensureDir(getRuntimeDir(workspaceDir)); // 客户端不导入终端已有的凭据。 if (harnessContext()) return result; const auth = migrateAuth(workspaceDir, result); migrateAccountFiles(workspaceDir, auth, result); writeMigrationMarker(workspaceDir, result); return result; } /** * Materialize the account-scoped canonical capability workspace. Legacy local/hub * trees are deliberately not migrated: the v3 product model has one editable source. */ export function ensureAccountUserDataLayout( workspaceDir: string, profile: Pick, ): UserDataMigrationResult { ensureUserDataLayout(workspaceDir); const result = EMPTY_RESULT(); const accountDir = getUserDataAccountDir(workspaceDir, profile); const marker = join(accountDir, '.capability-layout-v3.json'); ensureDir(accountDir); ensureDir(getUserDataAccountBehaviorsDir(workspaceDir, profile)); ensureDir(getUserDataAccountHubBehaviorsDir(workspaceDir, profile)); ensureDir(getUserDataAccountPerceptionsDir(workspaceDir, profile)); ensureDir(getUserDataAccountHubPerceptionsDir(workspaceDir, profile)); ensureDir(getUserDataAccountPersonasDir(workspaceDir, profile)); ensureDir(getUserDataAccountHubPersonasDir(workspaceDir, profile)); ensureDir(getUserDataAccountTriggersDir(workspaceDir, profile)); ensureDir(getUserDataAccountSkillsDir(workspaceDir, profile)); ensureDir(getUserDataAccountDraftsDir(workspaceDir, profile)); if (existsSync(marker)) return result; writeJson(marker, { format: 3, created_at: new Date().toISOString(), migrated: false, }); return result; }