import { rmSync } from 'node:fs'; import type { AuthProfile } from './auth.js'; import { capabilityWorkspacePath, readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry, type CapabilityWorkspaceType, } from './capability-workspace.js'; import { readGameplayConfig, writeGameplayConfig } from './gameplay-config.js'; import { readPersonaSelection, writePersonaSelection } from './persona.js'; import { getUserDataAccountPersonaSelectionFile, getUserDataAccountTriggersDir } from './user-data.js'; import { listClawclawTriggerSources } from '../runtime/clawclaw/plugins/trigger/trigger-source.js'; import { sendProfileOwnerControlRequest } from '../runtime/owner-control.js'; export type RenameableCapabilityType = Exclude; const MODULE_OPERATION_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/; function validName(type: RenameableCapabilityType, name: string): boolean { if (type !== 'persona') return MODULE_OPERATION_NAME.test(name); return !!name.trim() && name === name.trim() && name.length <= 255 && !/[\\/\u0000-\u001f]/u.test(name) && name !== '.' && name !== '..'; } export async function renameCapabilityOperationWhenIdle( workspaceDir: string, profile: AuthProfile, type: RenameableCapabilityType, currentName: string, newName: string, ownerRequest: typeof sendProfileOwnerControlRequest = sendProfileOwnerControlRequest, ) { let owner; try { owner = await ownerRequest(profile, 'behavior_status', {}, 750); } catch (error) { const code = (error as NodeJS.ErrnoException).code; if (code !== 'ENOENT' && code !== 'ECONNREFUSED') { throw new Error('capability_operation_name_runtime_check_failed', { cause: error }); } owner = null; } if (owner) throw new Error('capability_operation_name_runtime_active'); return renameCapabilityOperation(workspaceDir, profile, type, currentName, newName); } export function renameCapabilityOperation( workspaceDir: string, profile: Pick, type: RenameableCapabilityType, currentName: string, newName: string, ) { if (!validName(type, newName)) { throw new Error(`capability_operation_name_invalid:${type}:${newName}`); } const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const matches = Object.values(registry.entries).filter(entry => ( entry.type === type && entry.runtimeId === currentName && entry.selection === 'equipped' && !entry.hub?.cloudStatus && entry.operationNameAssigned !== false )); if (matches.length !== 1) { throw new Error(`capability_operation_name_target_${matches.length ? 'ambiguous' : 'not_equipped'}:${type}:${currentName}`); } const entry = matches[0]!; const path = capabilityWorkspacePath(workspaceDir, profile, entry); const identity = { resource_id: entry.hub?.resourceId, declared_id: entry.declaredId ?? currentName, working_copy_path: path }; if (newName === currentName) { return { type, old_id: currentName, id: newName, changed: false, scope: 'account_operation_name', effective: 'next_runtime', ...identity, reload_required_before_game: false }; } if (Object.values(registry.entries).some(other => ( other.key !== entry.key && other.type === type && other.runtimeId === newName && other.operationNameAssigned !== false ))) { throw new Error(`capability_operation_name_conflict:${type}:${newName}`); } const beforeRegistry = structuredClone(registry); const beforeGameplay = type === 'persona' ? undefined : readGameplayConfig(workspaceDir, profile); const nextGameplay = beforeGameplay ? structuredClone(beforeGameplay) : undefined; if (nextGameplay && type === 'behavior') { for (const role of Object.keys(nextGameplay.fallback_behaviors) as Array) { if (nextGameplay.fallback_behaviors[role] === currentName) { nextGameplay.fallback_behaviors[role] = newName; } } nextGameplay.disabled_behaviors = [...new Set(nextGameplay.disabled_behaviors.map(id => id === currentName ? newName : id))]; for (const trigger of Object.values(nextGameplay.triggers)) { if (trigger.behavior === currentName) trigger.behavior = newName; } for (const trigger of listClawclawTriggerSources(getUserDataAccountTriggersDir(workspaceDir, profile))) { if (trigger.manifest.defaultBehavior === currentName && nextGameplay.triggers[trigger.id]?.behavior === undefined) { nextGameplay.triggers[trigger.id] = { ...nextGameplay.triggers[trigger.id], behavior: newName }; } } } else if (nextGameplay) { nextGameplay.disabled_perception_modules = [...new Set(nextGameplay.disabled_perception_modules.map(id => id === currentName ? newName : id))]; } const beforePersona = type === 'persona' ? readPersonaSelection(workspaceDir, profile) : undefined; const nextPersona = beforePersona?.source === 'local' && beforePersona.id === currentName ? { source: 'local' as const, id: newName } : undefined; entry.runtimeId = newName; entry.updatedAt = new Date().toISOString(); try { writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); if (nextGameplay && JSON.stringify(nextGameplay) !== JSON.stringify(beforeGameplay)) { writeGameplayConfig(nextGameplay, workspaceDir, profile); } if (nextPersona) writePersonaSelection(workspaceDir, profile, nextPersona); } catch (error) { // Registry and command bindings must never intentionally disagree after a // failed rename. Restore every touched local source of operation names. try { writeCapabilityWorkspaceRegistry(workspaceDir, profile, beforeRegistry); if (beforeGameplay) writeGameplayConfig(beforeGameplay, workspaceDir, profile); if (type === 'persona') { if (beforePersona) writePersonaSelection(workspaceDir, profile, beforePersona); else rmSync(getUserDataAccountPersonaSelectionFile(workspaceDir, profile), { force: true }); } } catch (rollbackError) { throw new Error(`capability_operation_name_rollback_failed:${String(rollbackError)}`, { cause: error }); } throw error; } return { type, old_id: currentName, id: newName, changed: true, scope: 'account_operation_name', effective: 'next_runtime', ...identity, reload_required_before_game: true }; }