import { accountRequiredMessage } from '../lib/desktop-mode.js'; import { isPackageManagedSkill, PACKAGE_MANAGED_SKILL_NAMES } from '../lib/package-skills.js'; import { Command, InvalidArgumentError } from 'commander'; import { AuthStore, type AuthProfile } from '../lib/auth.js'; import { discoverLocalCapabilities } from '../lib/capability-discovery.js'; import { capabilitySelectionRef, capabilityWorkspacePath, pendingCapabilitySelections, readCapabilityWorkspaceRegistry, saveCapabilityDirectoryDraft, saveCapabilityDraft, setCapabilityConflictChoice, updateCapabilityHubIdentity, type CapabilityWorkspaceEntry, type CapabilityWorkspaceType, } from '../lib/capability-workspace.js'; import { getWorkspaceDir } from '../lib/init-command.js'; import { writePersonaSelection, readPersonaSelection } from '../lib/persona.js'; import { selectCapability } from '../lib/capability-selection.js'; import { agentSkillTargets, agentSkillLinkPointsTo, runSkillHostOperations, type SkillHostSkip, findSkillRoot, linkAgentSkillTarget, overwriteAgentSkillTarget, unlinkAgentSkillTarget, type SkillHostMutationResult, } from '../lib/skill-host.js'; import { HubClient, type ResourceType } from '../lib/hub-client.js'; import { unzip } from '../lib/hub-unzip.js'; import { zipContentDigest } from '../lib/zip-store.js'; import { createHash, randomUUID } from 'node:crypto'; import { tmpdir } from 'node:os'; import { dirname, extname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import { readLocalAgentWorkspaceSnapshot, resolveLocalAgentWorkspaceSnapshot, } from '../lib/agent-workspace-sync.js'; import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js'; import { CommandOutputError } from '../lib/command-error.js'; interface CapabilityResolveCloudClient { findWorkspaceItem: HubClient['findWorkspaceItem']; getResource(type: ResourceType, id: string, workspaceItemId?: string): ReturnType; downloadArtifact(type: ResourceType, id: string, workspaceItemId?: string): ReturnType; updateWorkspaceEquipment( workspaceItemId: string, equipped: boolean, ): ReturnType; updateWorkspaceLoadout(input: Parameters[0]): ReturnType; } export interface CapabilityCommandDependencies { client?: CapabilityResolveCloudClient; cloudSync?: typeof syncCapabilitiesToCloud; skillTargets?: (name: string) => readonly string[]; linkSkillTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult; unlinkSkillTarget?: (targetPath: string) => SkillHostMutationResult; } function pathInside(root: string, candidate: string): boolean { const child = relative(resolvePath(root), resolvePath(candidate)); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function writeCloudFileAtomically(target: string, bytes: Buffer): void { const stage = `${target}.ccl-stage-${randomUUID()}`; const displaced = `${target}.ccl-old-${randomUUID()}`; let moved = false; try { mkdirSync(dirname(target), { recursive: true }); writeFileSync(stage, bytes); if (existsSync(target)) { renameSync(target, displaced); moved = true; } renameSync(stage, target); if (moved) rmSync(displaced, { force: true }); } catch (error) { rmSync(stage, { force: true }); if (moved && !existsSync(target) && existsSync(displaced)) { try { renameSync(displaced, target); } catch { /* retain displaced recovery copy */ } } throw error; } } function cloudSkillStage(archive: Buffer): { root: string; stage: string; digest: string } { const stage = mkdtempSync(join(tmpdir(), 'ccl-capability-cloud-skill-')); try { for (const entry of unzip(archive)) { const target = resolvePath(stage, ...entry.path.split('/')); if (!pathInside(stage, target) || target === resolvePath(stage)) { throw new Error('capability_cloud_skill_path_invalid'); } mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, entry.content); } const root = findSkillRoot(stage); if (!existsSync(join(root, 'SKILL.md'))) throw new Error('capability_cloud_skill_invalid'); const files: Array<{ path: string; content: Buffer }> = []; const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const path = join(directory, entry.name); if (entry.isDirectory()) visit(path); else if (entry.isFile()) files.push({ path: relative(root, path).replaceAll('\\', '/'), content: readFileSync(path), }); } }; visit(root); return { root, stage, digest: zipContentDigest(files) }; } catch (error) { rmSync(stage, { recursive: true, force: true }); throw error; } } function activeProfile(): AuthProfile { const profile = new AuthStore().getActive(); if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.')); return profile; } function parseRef(value: string): { type: CapabilityWorkspaceType; id: string } { const match = /^(strategy|behavior|perception|persona|skill)\/(\S.{0,254})$/u.exec(value); if (!match) { throw new InvalidArgumentError('expected /'); } const parsed = { type: (match[1] === 'strategy' ? 'behavior' : match[1]) as CapabilityWorkspaceType, id: match[2]! }; if (parsed.type === 'skill' && isPackageManagedSkill(parsed.id)) { throw new InvalidArgumentError(`The official ${parsed.id} Skill is managed by the installed CCL package`); } return parsed; } function applySkillSelection( entry: CapabilityWorkspaceEntry, equipped: boolean, workspaceDir: string, profile: AuthProfile, dependencies: CapabilityCommandDependencies, ): { effective: 'immediate' | 'skipped'; skipped: SkillHostSkip[] } { const source = capabilityWorkspacePath(workspaceDir, profile, entry); const targets = dependencies.skillTargets ?? agentSkillTargets; const link = dependencies.linkSkillTarget ?? linkAgentSkillTarget; const unlink = dependencies.unlinkSkillTarget ?? unlinkAgentSkillTarget; const { applied, failed, skipped } = runSkillHostOperations(entry.runtimeId, targets(entry.runtimeId), target => { if (!equipped && existsSync(target) && !agentSkillLinkPointsTo(target, source)) return; return equipped ? link(source, target) : unlink(target); }, 'stop'); if (failed.length) { for (const completed of applied.reverse()) { if (equipped) unlink(completed); else link(source, completed); } throw new Error(`capability_skill_${equipped ? 'equip' : 'unequip'}_failed:${ failed[0].error ?? failed[0].stderr?.trim() ?? 'skill host mutation failed' }`); } return { effective: equipped && skipped.length > 0 && applied.length === 0 ? 'skipped' : 'immediate', skipped, }; } async function updateSelection( ref: string, equipped: boolean, dependencies: CapabilityCommandDependencies, ): Promise> { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(); discoverLocalCapabilities(workspaceDir, profile); const { type, id } = parseRef(ref); const entry = await selectCapability(workspaceDir, profile, type, id, equipped, dependencies.client); let skillSelection: ReturnType | undefined; if (type === 'skill') { try { skillSelection = applySkillSelection(entry, equipped, workspaceDir, profile, dependencies); } catch (error) { throw new Error(`capability_selection_saved_skill_links_failed:run_ccl_load:${error instanceof Error ? error.message : String(error)}`); } } if (type === 'persona' && equipped) { writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: entry.runtimeId }); } else if (type === 'persona') { // Do not clear another active Persona when this particular item is unequipped. const selected = readPersonaSelection(workspaceDir, profile); if (selected?.source === 'local' && selected.id === entry.runtimeId) { writePersonaSelection(workspaceDir, profile, { source: 'hub' }); } } return { capability: `${type}/${entry.runtimeId}`, selection_ref: capabilitySelectionRef(entry), equipped, selection: entry.selection, effective: skillSelection?.effective ?? 'immediate', reload_required_before_game: true, ...(skillSelection?.skipped.length ? { skipped: skillSelection.skipped } : {}), }; } export function createCapabilityCommand(dependencies: CapabilityCommandDependencies = {}): Command { const capability = new Command('capability') .alias('cap') .description('Inspect and persist one-time local capability assembly choices'); capability.addCommand(new Command('pending') .description('List newly discovered local capabilities awaiting one assembly choice') .action(() => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(); discoverLocalCapabilities(workspaceDir, profile); console.log(JSON.stringify({ pending: pendingCapabilitySelections(workspaceDir, profile) .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })) }, null, 2)); })); capability.addCommand(new Command('list') .description('List persisted local capability assembly choices') .action(() => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(); const { reservedSkills } = discoverLocalCapabilities(workspaceDir, profile); console.log(JSON.stringify({ capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })), reserved_skill_names: PACKAGE_MANAGED_SKILL_NAMES, ...(reservedSkills.length ? { skipped_skills: reservedSkills } : {}), }, null, 2)); })); capability.addCommand(new Command('equip') .argument('', 'Local capability reference') .allowExcessArguments(false) .action(async (ref: string) => console.log(JSON.stringify( await updateSelection(ref, true, dependencies), null, 2, )))); capability.addCommand(new Command('unequip') .argument('', 'Local capability reference') .allowExcessArguments(false) .action(async (ref: string) => console.log(JSON.stringify( await updateSelection(ref, false, dependencies), null, 2, )))); capability.addCommand(new Command('resolve') .description('Resolve one local/cloud content conflict') .argument('', 'Capability reference') .requiredOption('--use ', 'local | cloud | later') .allowExcessArguments(false) .action(async (ref: string, opts: { use: string }) => { if (!['local', 'cloud', 'later'].includes(opts.use)) { throw new InvalidArgumentError('--use must be local, cloud, or later'); } const workspaceDir = getWorkspaceDir(); const profile = activeProfile(); const { type, id } = parseRef(ref); const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); const matches = Object.values(registry.entries).filter((entry) => ( entry.type === type && entry.hub && (id.startsWith('@') ? capabilitySelectionRef(entry) === `${type}/${id}` : entry.runtimeId === id) )); if (matches.length !== 1) throw new Error(`capability_conflict_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${ref}`); const entry = matches[0]!; const operationId = entry.runtimeId; if (opts.use === 'local') { const storedSnapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile); if (!storedSnapshot) throw new Error(`capability_local_upload_requires_load:${ref}`); const snapshot = resolveLocalAgentWorkspaceSnapshot(workspaceDir, profile, storedSnapshot); setCapabilityConflictChoice(workspaceDir, profile, entry.key, 'local'); const synced = await (dependencies.cloudSync ?? syncCapabilitiesToCloud)( workspaceDir, profile, snapshot, { entryKeys: [entry.key] }, ); const uploaded = synced.uploaded.find((item) => item.type === type && item.id === operationId); const unchanged = synced.unchanged.some((item) => item.type === type && item.id === operationId); const conflict = synced.conflicts.find((item) => item.type === type && item.id === operationId); const failures = synced.failed.filter((item) => item.type === type && item.id === operationId); if (!uploaded && !unchanged) { if (conflict) throw new Error(`capability_upload_conflict:${ref}`); throw new CommandOutputError(`capability_upload_failed:${ref}:${failures[0]?.error ?? 'unknown'}`, { error: 'capability_upload_failed', capability: ref, failures, }); } console.log(JSON.stringify({ capability: `${type}/${operationId}`, resolution: 'local', effective: 'immediate', upload: uploaded ? { status: 'completed', action: uploaded.action, resource_id: uploaded.resource_id, version_id: uploaded.version_id, } : { status: 'unchanged' }, ...(failures.length > 0 ? { warnings: failures.map(({ error }) => error), failures } : {}), reload_required_before_game: true, }, null, 2)); return; } if (opts.use === 'later') { setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined); console.log(JSON.stringify({ capability: `${type}/${operationId}`, resolution: 'deferred', effective: 'current_local', reload_required_before_game: false, }, null, 2)); return; } if (!entry.hub) throw new Error(`capability_cloud_identity_missing:${ref}`); const hubType = (type === 'behavior' ? 'strategy' : type) as ResourceType; const client = dependencies.client ?? HubClient.fromProfile(profile); const workspaceItemId = entry.hub.publisher === 'self' ? undefined : entry.hub.workspaceItemId; const detail = await client.getResource(hubType, entry.hub.resourceId, workspaceItemId); const cloudBytes = await client.downloadArtifact(hubType, entry.hub.resourceId, workspaceItemId); const target = capabilityWorkspacePath(workspaceDir, profile, entry); let draft: string; let digest: string; if (type === 'skill') { const staged = cloudSkillStage(cloudBytes); try { draft = saveCapabilityDirectoryDraft(workspaceDir, profile, { type, runtimeId: operationId, sourcePath: target, }); const replaced = overwriteAgentSkillTarget(staged.root, target); if (!replaced.ok) throw new Error(replaced.error ?? 'capability_cloud_restore_failed'); digest = staged.digest; } finally { rmSync(staged.stage, { recursive: true, force: true }); } } else { draft = saveCapabilityDraft(workspaceDir, profile, { type, runtimeId: operationId, bytes: readFileSync(target), extension: extname(target), }); writeCloudFileAtomically(target, cloudBytes); digest = createHash('sha256').update(cloudBytes).digest('hex'); } updateCapabilityHubIdentity(workspaceDir, profile, entry.key, { ...entry.hub, versionId: detail.versionId, baseSha256: digest, lastUploadedSha256: digest, observedCloudVersionId: undefined, localOriginUnrecognized: undefined, pendingForkConflict: undefined, }); setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined); console.log(JSON.stringify({ capability: `${type}/${operationId}`, resolution: 'cloud', draft, effective: 'immediate', reload_required_before_game: true, }, null, 2)); })); return capability; }