import { existsSync, realpathSync } from 'node:fs'; import { join, basename } from 'node:path'; import type { AuthProfile } from './auth.js'; import { localAgentWorkspaceSnapshotRoot, readLocalAgentWorkspaceSnapshot, resolveLocalAgentWorkspacePath, resolveLocalAgentWorkspaceWorkingCopyPath, type LocalAgentWorkspaceItem, type LocalAgentWorkspaceSnapshot, } from './agent-workspace-sync.js'; import { registerDiscoveredCapability } from './capability-workspace.js'; import { behaviorOperationName, perceptionOperationName } from './capability-operation-name.js'; import { getUserDataAccountCapabilitiesDir } from './user-data.js'; import { listClawclawBehaviorSources, type ResolvedClawclawBehaviorSource, } from '../runtime/clawclaw/plugins/behavior/behavior-source.js'; import { listClawclawPerceptionSourcesInDirectory, type ResolvedClawclawPerceptionSource, } from '../runtime/clawclaw/plugins/perception/perception-source.js'; function currentSnapshot( workspaceDir: string, profile: Pick, snapshot?: LocalAgentWorkspaceSnapshot, ): LocalAgentWorkspaceSnapshot | undefined { return snapshot ?? readLocalAgentWorkspaceSnapshot(workspaceDir, profile); } function existingFilePath(path: string): string | undefined { try { return realpathSync.native(path); } catch { // An unavailable projection stays undiscovered so prepare can report its diagnostic. return undefined; } } function matchHubProjections( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, items: readonly LocalAgentWorkspaceItem[], sources: readonly T[], ): { source: T; item: LocalAgentWorkspaceItem }[] { const itemsByPath = new Map(); for (const item of items) { if (!item.runtimeEntryPath) continue; const projection = resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot, item.runtimeEntryPath); const path = existingFilePath(projection); if (path !== undefined) itemsByPath.set(path, item); } return sources.flatMap(source => { const path = existingFilePath(source.sourcePath); const item = path === undefined ? undefined : itemsByPath.get(path); return item ? [{ source, item }] : []; }); } function assertUniqueBehaviorIds( sources: readonly ResolvedClawclawBehaviorSource[], origin: 'local' | 'hub', ): void { const ids = new Set(); for (const source of sources) { if (ids.has(source.id)) { throw new Error(`AGENT_RESOURCE_ID_CONFLICT:behavior:${origin}_duplicate:${source.id}`); } ids.add(source.id); } } export interface AgentWorkspaceBehaviorManagement { source: 'local' | 'hub'; managedBy: 'local_config' | 'hub_loadout'; publisher?: 'official' | 'self' | 'community'; workspaceItemId?: string; resourceId?: string; forkedFromResourceId?: string; versionId?: string; versionNumber?: string; versionDescription?: string; resolution?: LocalAgentWorkspaceSnapshot['items']['strategy'][number]['resolution']; ownerId?: string; ownerName?: string | null; } export type ManagedClawclawBehaviorSource = ResolvedClawclawBehaviorSource & { readonly management: Readonly; }; export function listAgentWorkspaceBehaviorSources( workspaceDir: string, profile: Pick, snapshot?: LocalAgentWorkspaceSnapshot, ): readonly ManagedClawclawBehaviorSource[] { const active = currentSnapshot(workspaceDir, profile, snapshot); if (!active || active.items.strategy.length === 0) return []; const root = join(localAgentWorkspaceSnapshotRoot(workspaceDir, profile, active), 'runtime', 'behaviors'); if (!existsSync(root)) return []; const projections = matchHubProjections( workspaceDir, profile, active, active.items.strategy, listClawclawBehaviorSources(root), ); const sources = projections.map(({ source, item }) => { const trusted = item.sourceFiles[0] && item.resolution !== 'local_modified' && item.resolution !== 'concurrent_difference' && item.resolution !== 'local_origin_unrecognized'; const managed = { ...source, resourceId: item.resourceId, ...(trusted ? { trustedSourceSha256: item.sourceFiles[0]!.sha256 } : {}), management: { source: 'hub', managedBy: 'hub_loadout', ...(item.hub?.publisher ? { publisher: item.hub.publisher } : {}), workspaceItemId: item.workspaceItemId, resourceId: item.resourceId, forkedFromResourceId: item.forkedFromResourceId, versionId: item.versionId, versionNumber: item.versionNumber, versionDescription: item.versionDescription, resolution: item.resolution, ...(item.hub?.ownerId ? { ownerId: item.hub.ownerId } : {}), ...(item.hub ? { ownerName: item.hub.ownerName } : {}), }, } satisfies ManagedClawclawBehaviorSource; const workingCopyPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item) ?? join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'behaviors', item.resourceId, item.sourceFiles[0]?.relativePath ?? basename(source.sourcePath)); const entry = registerDiscoveredCapability(workspaceDir, profile, { type: 'behavior', path: workingCopyPath, runtimeId: source.id, title: item.title, description: item.description, selectedByHub: true, initialDescription: source.description, hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId, publisher: item.hub?.publisher ?? 'community', ownerId: item.hub?.ownerId, ownerName: item.hub?.ownerName, pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined, ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}), baseSha256: item.sourceFiles[0]?.sha256 }, }); return behaviorOperationName({ ...managed, workingCopyPath }, entry); }); assertUniqueBehaviorIds(sources, 'hub'); return sources; } export function listAgentWorkspacePerceptionSources( workspaceDir: string, profile: Pick, snapshot?: LocalAgentWorkspaceSnapshot, ): readonly (ResolvedClawclawPerceptionSource & { readonly resourceId: string })[] { const active = currentSnapshot(workspaceDir, profile, snapshot); if (!active || active.items.perception.length === 0) return []; const root = join(localAgentWorkspaceSnapshotRoot(workspaceDir, profile, active), 'runtime', 'perceptions'); const projections = matchHubProjections( workspaceDir, profile, active, active.items.perception, listClawclawPerceptionSourcesInDirectory(root), ); const namedSources = projections.map(({ source, item }) => { const workingCopyPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item) ?? join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'perceptions', item.resourceId, item.sourceFiles[0]?.relativePath ?? basename(source.sourcePath)); const entry = registerDiscoveredCapability(workspaceDir, profile, { type: 'perception', path: workingCopyPath, runtimeId: source.id, title: item.title, description: item.description, selectedByHub: true, initialDescription: source.description, 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 perceptionOperationName({ ...source, workingCopyPath, resourceId: item.resourceId }, entry); }); const ids = new Set(); for (const source of namedSources) { if (ids.has(source.id)) throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`); ids.add(source.id); } return namedSources; } export function mergeAgentWorkspaceBehaviorSources( base: readonly ResolvedClawclawBehaviorSource[], cloud: readonly ResolvedClawclawBehaviorSource[], disabled?: ReadonlySet, ): readonly ManagedClawclawBehaviorSource[] { const activeBase = base.filter(source => !disabled?.has(source.id)); const activeCloud = cloud.filter(source => !disabled?.has(source.id)); assertUniqueBehaviorIds(activeBase, 'local'); assertUniqueBehaviorIds(activeCloud, 'hub'); const merged = new Map(activeBase.map((source) => [source.id, { ...source, management: { source: 'local', managedBy: 'local_config' }, } satisfies ManagedClawclawBehaviorSource])); for (const source of activeCloud) { if (merged.has(source.id)) continue; merged.set(source.id, { ...source, management: 'management' in source ? (source as ManagedClawclawBehaviorSource).management : { source: 'hub', managedBy: 'hub_loadout' }, }); } return [...merged.values()]; } export function mergeAgentWorkspacePerceptionSources( base: readonly ResolvedClawclawPerceptionSource[], cloud: readonly ResolvedClawclawPerceptionSource[], disabled?: ReadonlySet, ): readonly ResolvedClawclawPerceptionSource[] { const merged = new Map(base.filter(source => !disabled?.has(source.id)).map((source) => [source.id, source])); for (const source of cloud) { if (disabled?.has(source.id)) continue; if (merged.has(source.id)) { throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`); } merged.set(source.id, source); } return [...merged.values()]; }