import { existsSync, readdirSync, realpathSync } from 'fs'; import { join, dirname, relative, sep } from 'path'; import * as p from '@clack/prompts'; import { readSkillLock, getGitHubToken, addSkillToLock, type SkillLockEntry, } from './skill-lock.ts'; import { computeSkillFolderHash, readLocalLock, getLockedSkillState, addSkillToLocalLock, type LocalSkillLockEntry, } from './local-lock.ts'; import { formatSourceInput, buildUpdateInstallSource, buildLocalUpdateSource, buildLocalCloneSource, buildGitHubCompareUrl, shouldUseFullDepthForUpdate, } from './update-source.ts'; import { cloneRepo, cleanupTempDir, getGitTreeHash, getHeadCommit } from './git.ts'; import { discoverSkills, isSubpathSafe, parseSkillMd } from './skills.ts'; import { fetchRepoTree, getSkillFolderHashFromTree, type RepoTree } from './blob.ts'; import { mapConcurrent } from './concurrency.ts'; import { parseSource } from './source-parser.ts'; import { buildInstallTargets, defaultInstallMode, downloadSkillPath, renameSkill, sourceSkillHash, fetchSources, installFetched, installToTargets, nonInteractiveTargetAgents, recordGlobalWellKnownLock, recordProjectLock, releaseSource, type InstallPlacement, type ResolvedSkills, type TargetInstallResult, } from './add.ts'; import { resolveSkillLocations, type DiscoveredSkillLocation, type SkillLocationResolution, type SkillLocationResolutionOptions, } from './skill-relocation.ts'; import { listInstalledSkills } from './installer.ts'; import { parseCliArgs, throwFirstError } from './cli-args.ts'; import { wellKnownProvider, computeWellKnownSkillDigest } from './providers/index.ts'; import { diagnostics } from './diagnostics.ts'; import { removeCommand } from './remove.ts'; import { sanitizeMetadata, sanitizeName } from './sanitize.ts'; import { track } from './telemetry.ts'; import { agents, isUniversalAgent } from './agents.ts'; import type { AgentType, Skill } from './types.ts'; import { BOLD, CLEAR_LINE, DIM, RESET, TEXT, pc } from './color.ts'; function printFetching(sourceCount: number): void { if (sourceCount === 0) return; console.log(`${DIM}Fetching ${sourceCount} source${sourceCount === 1 ? '' : 's'}…${RESET}`); } /** * Detected agents without a global skills dir (e.g. PromptScript, pulled in as a * universal agent) can't take a global reinstall; drop them like `add -g -y` does. */ export function withGlobalSkillsDir(targetAgents: AgentType[]): AgentType[] { const supported = targetAgents.filter((a) => agents[a].globalSkillsDir !== undefined); return supported.length > 0 ? supported : targetAgents; } /** * Where a reinstalled skill goes: what `add -y` would pick, with Eve fanned * out over the subagents recorded at install time (`''` is the root agent) * and the install mode the user chose. Agent detection runs once per resolver. */ function placementResolver( global: boolean ): (subagents?: string[], installMode?: 'copy') => Promise { let agentsPromise: Promise | undefined; return async (subagents, installMode) => { agentsPromise ??= nonInteractiveTargetAgents(); let targetAgents = await agentsPromise; const hasSubagents = !!subagents?.length; if (hasSubagents && !targetAgents.includes('eve')) targetAgents = [...targetAgents, 'eve']; if (global) targetAgents = withGlobalSkillsDir(targetAgents); const targets = buildInstallTargets( targetAgents, hasSubagents ? subagents.map((s) => (s === '' ? undefined : s)) : [undefined] ); return { global, targets, mode: installMode ?? defaultInstallMode(targets), createMissingAgentRoot: (agent) => hasSubagents && agent === 'eve', }; }; } /** Print per-target failures and the skill's verdict; true when at least one target took it. */ function reportInstall( name: string, outcome: { ok: boolean; failed: string[]; error?: string } ): boolean { const safeName = sanitizeMetadata(name); for (const failure of outcome.failed) console.log(` ${DIM}✗ ${failure}${RESET}`); if (outcome.ok && !outcome.error) { console.log(` ${TEXT}✓${RESET} Updated ${safeName}`); return true; } console.log( ` ${DIM}✗ Failed to update ${safeName}${outcome.error ? `: ${outcome.error}` : ''}${RESET}` ); return false; } /** Skills present on disk in a scope; a locked skill missing here is reinstalled. */ async function installedSkillNames(global: boolean): Promise> { return new Set((await listInstalledSkills({ global })).map((skill) => skill.name)); } function targetOutcome(results: TargetInstallResult[]): { ok: boolean; failed: string[] } { return { ok: results.some((r) => r.success), failed: results.filter((r) => !r.success).map((r) => `${r.agent}: ${r.error}`), }; } // ============================================ // Scope Detection and Prompt // ============================================ export type UpdateScope = 'project' | 'global' | 'both'; export interface UpdateCheckOptions { global?: boolean; project?: boolean; yes?: boolean; /** Optional skill name(s) to filter on (positional args) */ skills?: string[]; /** Check mode: report each skill that has an update instead of installing it. */ reportOutdated?: (name: string, compareUrl?: string) => void; } /** * Public GitHub lock entries use owner/repo shorthand to preserve the exact * skill subpath. Pin that shorthand to github.com so an ambient GH_HOST for a * GitHub Enterprise account cannot redirect an existing public installation. */ function parseUpdateSource(installUrl: string, sourceType: string) { return parseSource(installUrl, sourceType === 'github' ? { githubHost: 'github.com' } : {}); } export function parseUpdateOptions(args: string[]): UpdateCheckOptions { const { values, positionals, errors } = parseCliArgs(args, { global: { type: 'boolean', short: 'g' }, project: { type: 'boolean', short: 'p' }, yes: { type: 'boolean', short: 'y' }, }); throwFirstError(errors); const options: UpdateCheckOptions = {}; if (values.global) options.global = true; if (values.project) options.project = true; if (values.yes) options.yes = true; if (positionals.length > 0) options.skills = positionals; return options; } /** * Check whether the current working directory has project-level skills. * Returns true if either: * - skills-lock.json exists in cwd, OR * - .agents/skills/ contains at least one subdirectory with a SKILL.md */ export function hasProjectSkills(cwd?: string): boolean { const dir = cwd || process.cwd(); // Check 1: skills-lock.json exists const lockPath = join(dir, 'skills-lock.json'); if (existsSync(lockPath)) { return true; } // Check 2: .agents/skills/ has at least one skill const skillsDir = join(dir, '.agents', 'skills'); try { const entries = readdirSync(skillsDir, { withFileTypes: true }); for (const entry of entries) { if (entry.isDirectory()) { const skillMd = join(skillsDir, entry.name, 'SKILL.md'); if (existsSync(skillMd)) { return true; } } } } catch { // Directory doesn't exist } return false; } /** * Determine the update/check scope via interactive prompt or auto-detection. */ export async function resolveUpdateScope(options: UpdateCheckOptions): Promise { if (options.skills && options.skills.length > 0) { if (options.global) return 'global'; if (options.project) return 'project'; return 'both'; } if (options.global && options.project) { return 'both'; } if (options.global) { return 'global'; } if (options.project) { return 'project'; } if (options.yes || !process.stdin.isTTY) { return hasProjectSkills() ? 'project' : 'global'; } const scope = await p.select({ message: 'Update scope', options: [ { value: 'project' as UpdateScope, label: 'Project', hint: 'Update skills in current directory', }, { value: 'global' as UpdateScope, label: 'Global', hint: 'Update skills in home directory', }, { value: 'both' as UpdateScope, label: 'Both', hint: 'Update all skills', }, ], }); if (p.isCancel(scope)) { p.cancel('Cancelled'); process.exit(0); } return scope as UpdateScope; } export function matchesSkillFilter(name: string, filter?: string[]): boolean { if (!filter || filter.length === 0) return true; const lower = name.toLowerCase(); return filter.some((f) => f.toLowerCase() === lower); } export interface SkippedSkill { name: string; reason: string; sourceUrl: string; sourceType: string; ref?: string; } export function getSkipReason(entry: SkillLockEntry): string { if (entry.sourceType === 'local') { return 'Local path'; } if (entry.sourceType === 'git') { return 'Git URL'; } if (entry.sourceType === 'well-known') { return 'Well-known skill'; } if (!entry.skillFolderHash) { return 'Private or deleted repo'; } if (!entry.skillPath) { return 'No skill path recorded'; } return 'No version tracking'; } export function getInstallSource(skill: SkippedSkill): string { let url = skill.sourceUrl; if (skill.sourceType === 'well-known') { const idx = url.indexOf('/.well-known/'); if (idx !== -1) { url = url.slice(0, idx); } } return formatSourceInput(url, skill.ref); } export function printSkippedSkills(skipped: SkippedSkill[]): void { if (skipped.length === 0) return; console.log(); console.log(`${DIM}${skipped.length} skill(s) cannot be checked automatically:${RESET}`); const grouped = new Map(); for (const skill of skipped) { const source = getInstallSource(skill); const existing = grouped.get(source) || []; existing.push(skill); grouped.set(source, existing); } for (const [source, skills] of grouped) { if (skills.length === 1) { const skill = skills[0]!; console.log( ` ${TEXT}•${RESET} ${sanitizeMetadata(skill.name)} ${DIM}(${skill.reason})${RESET}` ); } else { const reason = skills[0]!.reason; const names = skills.map((s) => sanitizeMetadata(s.name)).join(', '); console.log(` ${TEXT}•${RESET} ${names} ${DIM}(${reason})${RESET}`); } console.log(` ${DIM}To update: ${TEXT}npx skills add ${source} -g -y${RESET}`); } } export async function getProjectSkillsForUpdate( skillFilter?: string[] ): Promise> { const localLock = await readLocalLock(); const skills: Array<{ name: string; source: string; entry: LocalSkillLockEntry }> = []; for (const [name, entry] of Object.entries(localLock.skills)) { if (!matchesSkillFilter(name, skillFilter)) continue; if (entry.sourceType === 'node_modules' || entry.sourceType === 'local') { continue; } skills.push({ name, source: entry.sourceUrl || entry.source, entry }); } return skills; } export async function promptDeletions( source: string, deletedSkills: string[], isGlobal: boolean, options: UpdateCheckOptions ): Promise { if (deletedSkills.length === 0) return; console.log(); console.log( `${DIM}Warning:${RESET} The following skills from ${DIM}${source}${RESET} appear to have been deleted upstream:` ); for (const s of deletedSkills) { console.log(` ${DIM}•${RESET} ${s}`); } const isNonInteractive = options.yes || !process.stdin.isTTY; if (isNonInteractive) { console.log(`${DIM}Skipping deletion in non-interactive mode.${RESET}`); return; } const confirmed = await p.confirm({ message: `Would you like to remove the local copies of these deleted skills?`, }); if (confirmed && !p.isCancel(confirmed)) { for (const s of deletedSkills) { console.log(`${DIM}Removing${RESET} ${s}…`); await removeCommand([s], { yes: true, global: isGlobal }); } } } export async function checkAndPromptForDeletions( source: string, allLockedForSource: string[], lockSkills: Record, isGlobal: boolean, options: UpdateCheckOptions, discovered: DiscoveredSkillLocation[], locationOptions: SkillLocationResolutionOptions = {} ): Promise { const resolution = resolveSkillLocations( allLockedForSource, lockSkills, discovered, locationOptions ); if (resolution.ambiguousSkills.length > 0) { console.log(); console.log( `${DIM}Warning:${RESET} Multiple current paths match these skills from ${DIM}${source}${RESET}; skipping them rather than deleting or migrating the wrong skill:` ); for (const name of resolution.ambiguousSkills) { console.log(` ${DIM}•${RESET} ${sanitizeMetadata(name)}`); } } await promptDeletions(source, resolution.deletedSkills, isGlobal, options); return resolution; } export interface WellKnownUpdateItem { /** Installed name (the lock key). */ name: string; /** Name the endpoint publishes the skill under, when installed with `--rename`. */ skillName?: string; digest: string; subagents?: string[]; } /** The name a lock item's skill has in its source. */ function sourceNameOf(item: { name: string; skillName?: string }): string { return item.skillName ?? item.name; } /** `skill` as the lock item installed it: under the item's name when it was renamed. */ function asLocked(skill: T, item: { name: string; skillName?: string }): T { return item.skillName ? renameSkill(skill, item.name) : skill; } export type WellKnownCheckResult = | { status: 'error' } | { status: 'current'; newSkills: string[] } | { status: 'changed'; changedSkills: string[]; removedSkills: string[]; newSkills: string[]; }; export async function checkWellKnownForUpdates( baseUrl: string, items: WellKnownUpdateItem[] ): Promise { let indexResult: Awaited>; try { indexResult = await wellKnownProvider.fetchIndex(baseUrl, { updateCheck: true }); } catch { return { status: 'error' }; } if (!indexResult) return { status: 'error' }; const byName = new Map(indexResult.entries.map((entry) => [entry.name, entry])); const removedSkills = items .filter((item) => !byName.has(sourceNameOf(item))) .map((item) => item.name); const localNames = new Set(items.map(sourceNameOf)); const newSkills = indexResult.entries .map((entry) => entry.name) .filter((name) => !localNames.has(name)); const changedSkills: string[] = []; const needsContentCheck: WellKnownUpdateItem[] = []; for (const item of items) { const entry = byName.get(sourceNameOf(item)); if (!entry) continue; if (entry.version === '0.2.0') { if (!item.digest || entry.digest !== item.digest) { changedSkills.push(item.name); } } else { needsContentCheck.push(item); } } if (needsContentCheck.length > 0) { const tracked = new Set(needsContentCheck.map(sourceNameOf)); // An incomplete download says nothing about upstream changes, so skip the skill. const incomplete = new Set(); const skills = ( await Promise.all( indexResult.entries .filter((entry) => tracked.has(entry.name)) .map((entry) => wellKnownProvider.fetchSkillByEntry(entry).catch((error) => { if (diagnostics.SKILLS_WELLKNOWN_FILE_FETCH_FAILED.is(error)) { incomplete.add(entry.name); } return null; }) ) ) ).filter((skill): skill is NonNullable => skill !== null); if (skills.length === 0) return { status: 'error' }; const digests = new Map( skills.map((skill) => [skill.installName, computeWellKnownSkillDigest(skill)]) ); for (const item of needsContentCheck) { if (incomplete.has(sourceNameOf(item))) continue; const digest = digests.get(sourceNameOf(item)); if (!digest || !item.digest || digest !== item.digest) { changedSkills.push(item.name); } } } if (changedSkills.length === 0 && removedSkills.length === 0) { return { status: 'current', newSkills }; } return { status: 'changed', changedSkills, removedSkills, newSkills }; } function printNewSkills(baseUrl: string, newSkills: string[], isGlobal: boolean): void { if (newSkills.length === 0) return; const names = newSkills.map(sanitizeMetadata); console.log( ` ${DIM}${newSkills.length} new skill(s) available from this source:${RESET} ${names.join(', ')}` ); console.log( ` ${DIM}To install: ${TEXT}npx skills add ${baseUrl} --skill ${names.join(' ')}${isGlobal ? ' -g' : ''}${RESET}` ); } export async function processWellKnownUpdates( groups: Map, isGlobal: boolean, options: UpdateCheckOptions ): Promise<{ successCount: number; failCount: number; changed: boolean }> { let successCount = 0; let failCount = 0; let changed = false; const entries = [...groups]; printFetching(entries.length); const results = await mapConcurrent(entries, ([baseUrl, items]) => checkWellKnownForUpdates(baseUrl, items) ); const pending: Array<{ baseUrl: string; items: WellKnownUpdateItem[]; changedSkills: string[] }> = []; for (const [index, [baseUrl, items]] of entries.entries()) { process.stdout.write(`${CLEAR_LINE}${DIM}Checking skills from source: ${baseUrl}${RESET}\n`); const result = results[index]!; if (result.status === 'error') { console.log(` ${DIM}✗ Failed to check skills from ${baseUrl}${RESET}`); continue; } if (result.status === 'current') { printNewSkills(baseUrl, result.newSkills, isGlobal); continue; } changed = true; await promptDeletions(baseUrl, result.removedSkills, isGlobal, options); printNewSkills(baseUrl, result.newSkills, isGlobal); if (result.changedSkills.length > 0) { if (options.reportOutdated) { for (const name of result.changedSkills) options.reportOutdated(name); } else { pending.push({ baseUrl, items, changedSkills: result.changedSkills }); } } } const fetched = await fetchSources( pending.map(({ baseUrl, items, changedSkills }) => { const itemByName = new Map(items.map((item) => [item.name, item])); return { parsed: parseSource(baseUrl), skills: changedSkills.map((name) => { const item = itemByName.get(name); return item ? sourceNameOf(item) : name; }), }; }) ); const placementFor = placementResolver(isGlobal); for (const [index, { baseUrl, items, changedSkills }] of pending.entries()) { const source = fetched[index]!; const itemByName = new Map(items.map((item) => [item.name, item])); // One install per skill: each may record different Eve subagents. for (const name of changedSkills) { console.log(`${TEXT}Updating ${sanitizeMetadata(name)}…${RESET}`); const item: WellKnownUpdateItem = itemByName.get(name) ?? { name, digest: '' }; const outcome = await installFetched(source, { skills: [sourceNameOf(item)], placement: await placementFor(isGlobal ? undefined : item.subagents), select: async (skills) => skills.map((skill) => asLocked(skill, item)), }); if (isGlobal) await recordGlobalWellKnownLock(baseUrl, outcome.installed); else await recordProjectLock(source, outcome.installed); if (reportInstall(name, { ok: outcome.installed.length > 0, ...outcome })) successCount++; else failCount++; } await releaseSource(source); } return { successCount, failCount, changed }; } /** A locked direct download (raw SKILL.md, archive, Notion) and the hash it was installed at. */ interface DownloadUpdateItem { /** Installed name (the lock key). */ name: string; /** Name of the skill in the download, when installed with `--rename`. */ skillName?: string; /** URL that fetches the download again. */ url: string; skillPath?: string; hash: string; subagents?: string[]; installMode?: 'copy'; } /** * The skill in a fresh download that a lock entry points at: the one with its * name, preferring the locked SKILL.md path when several share the name. */ function findDownloadedSkill(resolved: ResolvedSkills, item: DownloadUpdateItem) { const named = resolved.skills.filter((skill) => skill.name === sourceNameOf(item)); return ( named.find((skill) => downloadSkillPath(resolved.rootDir!, skill.path) === item.skillPath) ?? named[0] ); } /** * Download each locked URL again and reinstall the skills whose content hash * changed or whose folder is gone. `record` writes the new lock entry. */ async function processDownloadUpdates( items: DownloadUpdateItem[], isGlobal: boolean, options: UpdateCheckOptions, record: (item: DownloadUpdateItem, skillPath: string, hash: string) => Promise ): Promise<{ successCount: number; failCount: number; upToDateCount: number }> { let successCount = 0; let failCount = 0; let upToDateCount = 0; if (items.length === 0) return { successCount, failCount, upToDateCount }; const byUrl = new Map(); for (const item of items) byUrl.set(item.url, [...(byUrl.get(item.url) ?? []), item]); const groups = [...byUrl]; const fetched = await fetchSources( groups.map(([url, group]) => ({ parsed: { type: 'download' as const, url }, skills: group.map(sourceNameOf), fullDepth: true, })) ); const onDisk = await installedSkillNames(isGlobal); const placementFor = placementResolver(isGlobal); for (const [index, [url, group]] of groups.entries()) { const source = fetched[index]!; process.stdout.write(`${CLEAR_LINE}${DIM}Checking skills from source: ${url}${RESET}\n`); if (!source.resolved) { failCount += group.length; console.log(` ${DIM}✗ Failed to check skills from ${url}: ${source.error}${RESET}`); continue; } try { for (const item of group) { const skill = findDownloadedSkill(source.resolved, item); if (!skill) { failCount++; console.log( ` ${DIM}✗ ${sanitizeMetadata(item.name)} is no longer in this download${RESET}` ); continue; } const hash = await sourceSkillHash(asLocked(skill, item)); if (hash === item.hash && onDisk.has(item.name)) { upToDateCount++; continue; } if (options.reportOutdated) { options.reportOutdated(item.name); continue; } console.log(`${TEXT}Updating ${sanitizeMetadata(item.name)}…${RESET}`); const results = await installToTargets( source.resolved, [asLocked(skill, item)], await placementFor(isGlobal ? undefined : item.subagents, item.installMode) ); const outcome = targetOutcome(results); if (outcome.ok) { await record(item, downloadSkillPath(source.resolved.rootDir!, skill.path), hash); } if (reportInstall(item.name, outcome)) successCount++; else failCount++; } } finally { await releaseSource(source); } } return { successCount, failCount, upToDateCount }; } /** The network half of a source check; `tempDir` is the caller's to clean up. */ type SourceCheckout = { tree: RepoTree } | { tempDir: string; note?: string } | { error: true }; /** * GitHub sources are checked through the Trees API unless a locked skill path * no longer exists there (a rename), in which case the repo is cloned to * relocate it. Other sources are always cloned. */ async function fetchGlobalSource( entry: SkillLockEntry, lockedSkillPaths: Array ): Promise { let note: string | undefined; try { if (entry.sourceType === 'github') { const tree = await fetchRepoTree(entry.source, entry.ref, getGitHubToken); if (tree) { const treePaths = new Set(tree.tree.filter((e) => e.type === 'blob').map((e) => e.path)); if (lockedSkillPaths.every((path) => !path || treePaths.has(path))) return { tree }; note = 'Skill paths changed; resolving via Git clone'; } else { note = 'GitHub API unavailable; checking via Git clone'; } } return { tempDir: await cloneRepo(entry.sourceUrl || entry.source, entry.ref), note }; } catch { return { error: true }; } } export async function updateGlobalSkills( options: UpdateCheckOptions = {} ): Promise<{ successCount: number; failCount: number; checkedCount: number }> { const lock = await readSkillLock(); const skillNames = Object.keys(lock.skills); let successCount = 0; let failCount = 0; if (skillNames.length === 0) { if (!options.skills) { console.log(`${DIM}No global skills tracked in lock file.${RESET}`); console.log(`${DIM}Install skills with${RESET} ${TEXT}npx skills add -g${RESET}`); } return { successCount, failCount, checkedCount: 0 }; } const updates: Array<{ name: string; entry: SkillLockEntry; /** Upstream hash of the skill folder, recorded once the reinstall succeeds. */ skillFolderHash: string; }> = []; const skipped: SkippedSkill[] = []; const checkable: Array<{ name: string; entry: SkillLockEntry }> = []; const wellKnownGroups = new Map(); const downloadItems: DownloadUpdateItem[] = []; for (const skillName of skillNames) { if (!matchesSkillFilter(skillName, options.skills)) continue; const entry = lock.skills[skillName]; if (!entry) continue; if (entry.sourceType === 'well-known' && entry.sourceBaseUrl && entry.wellKnownDigest) { const group = wellKnownGroups.get(entry.sourceBaseUrl) || []; group.push({ name: skillName, skillName: entry.skillName, digest: entry.wellKnownDigest }); wellKnownGroups.set(entry.sourceBaseUrl, group); continue; } if (entry.sourceType === 'download' && entry.sourceUrl) { downloadItems.push({ name: skillName, skillName: entry.skillName, url: entry.sourceUrl, skillPath: entry.skillPath, hash: entry.skillFolderHash, installMode: entry.installMode, }); continue; } if (!entry.skillFolderHash || !entry.skillPath) { skipped.push({ name: skillName, reason: getSkipReason(entry), sourceUrl: entry.sourceUrl, sourceType: entry.sourceType, ref: entry.ref, }); continue; } checkable.push({ name: skillName, entry }); } const wellKnownCount = Array.from(wellKnownGroups.values()).reduce( (sum, items) => sum + items.length, 0 ); const { successCount: wkSuccessCount, failCount: wkFailCount, changed: wkChanged, } = await processWellKnownUpdates(wellKnownGroups, true, options); successCount += wkSuccessCount; failCount += wkFailCount; const downloads = await processDownloadUpdates( downloadItems, true, options, (item, skillPath, skillFolderHash) => addSkillToLock(item.name, { ...lock.skills[item.name]!, skillPath, skillFolderHash }) ); successCount += downloads.successCount; failCount += downloads.failCount; // Remote sources other than git: well-known indexes and direct downloads. const otherCount = wellKnownCount + downloadItems.length; const otherChanged = wkChanged || downloads.upToDateCount < downloadItems.length; // Key by source AND ref: two skills from the same repo pinned to different // refs must each be checked against their own ref's tree. Grouping by source // alone checks the whole group against the first entry's ref, which falsely // reports the other-ref skills as deleted upstream (and then removes them). const bySource = new Map(); for (const item of checkable) { const key = `${item.entry.source}\n${item.entry.ref ?? ''}`; const existing = bySource.get(key) || []; existing.push(item); bySource.set(key, existing); } const lockedNamesFor = (first: SkillLockEntry) => Object.entries(lock.skills) .filter(([_, entry]) => entry.source === first.source && entry.ref === first.ref) .map(([name, _]) => name); const onDisk = await installedSkillNames(true); const groups = [...bySource.values()]; printFetching(groups.length); const checkouts = await mapConcurrent(groups, (itemsForSource) => { const firstEntry = itemsForSource[0]!.entry; return fetchGlobalSource( firstEntry, lockedNamesFor(firstEntry).map((name) => lock.skills[name]?.skillPath) ); }); for (const [index, itemsForSource] of groups.entries()) { const firstEntry = itemsForSource[0]!.entry; const source = firstEntry.source; const isGitHubSource = firstEntry.sourceType === 'github'; const checkout = checkouts[index]!; process.stdout.write(`${CLEAR_LINE}${DIM}Checking skills from source: ${source}${RESET}\n`); if ('error' in checkout) { console.log(` ${DIM}✗ Failed to check skills from ${source}${RESET}`); continue; } if ('tree' in checkout) { for (const { name: skillName, entry } of itemsForSource) { const latestHash = getSkillFolderHashFromTree(checkout.tree, entry.skillPath!); if (latestHash && (latestHash !== entry.skillFolderHash || !onDisk.has(skillName))) { updates.push({ name: skillName, entry, skillFolderHash: latestHash }); } } continue; } const { tempDir, note } = checkout; if (note) console.log(` ${DIM}${note}${RESET}`); try { const discovered = await discoverSkills(tempDir, undefined, { fullDepth: true, includeDuplicateNames: true, }); const discoveredLocations = discovered.map((skill) => ({ name: skill.name, skillPath: join(relative(tempDir, skill.path), 'SKILL.md').split(sep).join('/'), })); const resolution = await checkAndPromptForDeletions( source, lockedNamesFor(firstEntry), lock.skills, true, options, discoveredLocations, // Path-addressable sources reinstall only the locked directory, so a // same-name mirror elsewhere in the repo is not ambiguous. Generic Git // sources reinstall from the whole repo and remain fail-closed. { exactPathDisambiguates: !shouldUseFullDepthForUpdate(firstEntry) } ); const deletedSkillSet = new Set(resolution.deletedSkills); for (const { name: skillName, entry } of itemsForSource) { if (deletedSkillSet.has(skillName)) continue; const skillPath = resolution.resolvedPaths.get(skillName); if (!skillPath) continue; const usesGitTreeHash = isGitHubSource && /^[0-9a-f]{40}$/i.test(entry.skillFolderHash); const latestHash = usesGitTreeHash ? await getGitTreeHash(tempDir, skillPath) : await computeSkillFolderHash(join(tempDir, dirname(skillPath))); const relocated = skillPath !== entry.skillPath; if ( relocated || (latestHash && (latestHash !== entry.skillFolderHash || !onDisk.has(skillName))) ) { updates.push({ name: skillName, entry: { ...entry, skillPath }, skillFolderHash: latestHash ?? '', }); } } } catch (error) { console.log(` ${DIM}✗ Failed to check skills from ${source}${RESET}`); } finally { await cleanupTempDir(tempDir); } } if (checkable.length > 0) { process.stdout.write(CLEAR_LINE); } const checkedCount = checkable.length + skipped.length + otherCount; if (checkable.length === 0 && skipped.length === 0 && otherCount === 0) { if (!options.skills) { console.log(`${DIM}No global skills to check.${RESET}`); } return { successCount, failCount, checkedCount: 0 }; } if (updates.length === 0) { if (!otherChanged && skipped.length === 0) { console.log(`${TEXT}✓ All global skills are up to date${RESET}`); } printSkippedSkills(skipped); return { successCount, failCount, checkedCount }; } if (options.reportOutdated) { for (const { name } of updates) options.reportOutdated(name); printSkippedSkills(skipped); return { successCount, failCount, checkedCount }; } console.log(`${TEXT}Found ${updates.length} global update(s)${RESET}`); console.log(); // Each update is fetched on its own (its skill folder as the subpath), as // `add` would, so eligible GitHub repos take the blob fast path. const installable = updates.flatMap((update) => { const installUrl = buildUpdateInstallSource(update.entry); if (installUrl) return [{ ...update, installUrl }]; failCount++; console.log( ` ${DIM}✗ Cannot update ${sanitizeMetadata(update.name)}: lock file is missing sourceUrl for this generic Git source${RESET}` ); return []; }); const fetched = await fetchSources( installable.map(({ entry, name, installUrl }) => ({ parsed: parseUpdateSource(installUrl, entry.sourceType), skills: [entry.skillName ?? name], fullDepth: shouldUseFullDepthForUpdate(entry), })) ); const placementFor = placementResolver(true); for (const [index, { name, entry, skillFolderHash }] of installable.entries()) { console.log(`${TEXT}Updating ${sanitizeMetadata(name)}…${RESET}`); const source = fetched[index]!; const outcome = await installFetched(source, { skills: [entry.skillName ?? name], placement: await placementFor(undefined, entry.installMode), select: async (skills) => skills.map((skill) => asLocked(skill, { name, skillName: entry.skillName })), }); await releaseSource(source); if (outcome.installed.length > 0) { // Drop a stale commit when the new one is unknown await addSkillToLock(name, { ...entry, skillFolderHash, commit: source.resolved?.commit }); } if (reportInstall(name, { ok: outcome.installed.length > 0, ...outcome })) successCount++; else failCount++; } printSkippedSkills(skipped); return { successCount, failCount, checkedCount }; } function isRealpathWithin(realRoot: string, path: string): boolean { try { const real = realpathSync(path); return real === realRoot || real.startsWith(realRoot + sep); } catch { return false; } } async function readLockedSkills( tempDir: string, lockSkills: Record, names: string[] ): Promise { const skills: Skill[] = []; const realRoot = realpathSync(tempDir); for (const name of names) { const skillPath = lockSkills[name]?.skillPath; if (!skillPath || !isSubpathSafe(tempDir, skillPath)) return null; const skillMdPath = join(tempDir, skillPath); if (!existsSync(skillMdPath)) return null; // The lexical check above does not see symlinks; a linked skill directory // or SKILL.md could point at host files outside the clone. if (!isRealpathWithin(realRoot, dirname(skillMdPath))) return null; if (!isRealpathWithin(realRoot, skillMdPath)) return null; // An unparseable locked skill may have moved; let full discovery decide. const skill = await parseSkillMd(skillMdPath); if (!skill) return null; skills.push(skill); } return skills; } export async function updateProjectSkills( options: UpdateCheckOptions = {} ): Promise<{ successCount: number; failCount: number; foundCount: number }> { const projectSkills = await getProjectSkillsForUpdate(options.skills); let successCount = 0; let failCount = 0; if (projectSkills.length === 0) { if (!options.skills) { console.log(`${DIM}No project skills to update.${RESET}`); console.log( `${DIM}Install project skills with${RESET} ${TEXT}npx skills add ${RESET}` ); } return { successCount, failCount, foundCount: 0 }; } const wellKnownGroups = new Map(); const nonWellKnown: typeof projectSkills = []; const downloadItems: DownloadUpdateItem[] = []; for (const skill of projectSkills) { const { entry } = skill; if (entry.sourceType === 'download' && entry.sourceUrl) { downloadItems.push({ name: skill.name, skillName: entry.skillName, url: entry.sourceUrl, skillPath: entry.skillPath, hash: entry.computedHash, subagents: entry.subagents, installMode: entry.installMode, }); } else if (entry.sourceType === 'well-known' && entry.sourceUrl && entry.wellKnownDigest) { const group = wellKnownGroups.get(entry.sourceUrl) || []; group.push({ name: skill.name, skillName: entry.skillName, digest: entry.wellKnownDigest, subagents: entry.subagents, }); wellKnownGroups.set(entry.sourceUrl, group); } else { nonWellKnown.push(skill); } } const wellKnownCount = Array.from(wellKnownGroups.values()).reduce( (sum, items) => sum + items.length, 0 ); const updatable = nonWellKnown.filter((s) => s.entry.skillPath); const legacy = nonWellKnown.filter((s) => !s.entry.skillPath); if (updatable.length === 0 && wellKnownCount === 0 && downloadItems.length === 0) { console.log(`${DIM}No project skills can be updated in place.${RESET}`); printLegacyProjectSkills(legacy); return { successCount, failCount, foundCount: projectSkills.length }; } const cwd = process.cwd(); const targetAgentNames: string[] = []; let hasUniversal = false; for (const [type, config] of Object.entries(agents)) { if (isUniversalAgent(type as AgentType)) { if (!hasUniversal && existsSync(join(cwd, '.agents'))) { hasUniversal = true; } } else { const agentRoot = config.skillsDir.split('/')[0]!; if (existsSync(join(cwd, agentRoot))) { targetAgentNames.push(config.displayName); } } } const targetParts: string[] = []; if (hasUniversal) targetParts.push('Universal'); targetParts.push(...targetAgentNames); if (targetParts.length > 0) { console.log(`${TEXT}Updating for: ${targetParts.join(', ')}${RESET}`); } console.log( `${TEXT}Checking ${updatable.length + wellKnownCount + downloadItems.length} skill(s)…${RESET}` ); console.log(); const { successCount: wkSuccessCount, failCount: wkFailCount } = await processWellKnownUpdates( wellKnownGroups, false, options ); successCount += wkSuccessCount; failCount += wkFailCount; const entryOf = new Map(projectSkills.map((skill) => [skill.name, skill.entry])); const downloads = await processDownloadUpdates( downloadItems, false, options, (item, skillPath, computedHash) => addSkillToLocalLock(item.name, { ...entryOf.get(item.name)!, skillPath, computedHash }) ); successCount += downloads.successCount; failCount += downloads.failCount; // Key by source AND ref (see updateGlobalSkills) so skills from one repo // pinned to different refs are each checked against their own ref's tree. const bySource = new Map(); for (const skill of updatable) { const source = skill.entry.sourceUrl || skill.entry.source; const key = `${source}\n${skill.entry.ref ?? ''}`; const existing = bySource.get(key) || []; existing.push(skill); bySource.set(key, existing); } const localLock = await readLocalLock(); const onDisk = await installedSkillNames(false); const placementFor = placementResolver(false); let upToDateCount = downloads.upToDateCount; const groups = [...bySource.values()].map((skillsForSource) => ({ skillsForSource, cloneSource: buildLocalCloneSource(skillsForSource[0]!.entry), })); printFetching(groups.filter((group) => group.cloneSource !== null).length); // Clone dir per group; null when the source is unresolvable or the clone failed. const clones = await mapConcurrent(groups, ({ skillsForSource, cloneSource }) => cloneSource === null ? Promise.resolve(null) : cloneRepo(cloneSource, skillsForSource[0]!.entry.ref).catch(() => null) ); for (const [index, { skillsForSource, cloneSource }] of groups.entries()) { const firstEntry = skillsForSource[0]!.entry; const source = firstEntry.sourceUrl || firstEntry.source; const ref = firstEntry.ref; const allLockedForSource = Object.entries(localLock.skills) .filter(([_, entry]) => (entry.sourceUrl || entry.source) === source && entry.ref === ref) .map(([name, _]) => name); const tempDir = clones[index]!; if (cloneSource === null) { failCount += skillsForSource.length; console.log( `${DIM}✗ Cannot update ${source}: skills-lock.json is missing sourceUrl for this generic Git source${RESET}` ); continue; } if (tempDir === null) { failCount += skillsForSource.length; console.log(`${DIM}✗ Failed to check for deleted skills from ${source}${RESET}`); continue; } let checked = false; try { // Every lock entry for the source must be path-addressable: deletion checks // resolve all of them, including skills filtered out of this run. // Generic Git sources reinstall by name, so they keep full discovery to // detect same-name mirrors. const reinstallsByName = shouldUseFullDepthForUpdate(firstEntry); let discovered = reinstallsByName ? null : await readLockedSkills(tempDir, localLock.skills, allLockedForSource); discovered ??= await discoverSkills(tempDir, undefined, { fullDepth: true, includeDuplicateNames: true, }); const discoveredLocations = discovered.map((skill) => ({ name: skill.name, skillPath: join(relative(tempDir, skill.path), 'SKILL.md').split(sep).join('/'), })); const resolution = await checkAndPromptForDeletions( source, allLockedForSource, localLock.skills, false, options, discoveredLocations, { exactPathDisambiguates: !reinstallsByName } ); checked = true; const deleted = new Set(resolution.deletedSkills); const skillAt = new Map(discovered.map((s, i) => [discoveredLocations[i]!.skillPath, s])); const resolved: ResolvedSkills = { skills: discovered, tempDir, blobResult: null }; const commit = (await getHeadCommit(tempDir)) ?? undefined; for (const skill of skillsForSource) { if (deleted.has(skill.name)) continue; const skillPath = resolution.resolvedPaths.get(skill.name); const current = skillPath && skillAt.get(skillPath); if (!skillPath || !current) continue; // Hash the clone the same way `add` records computedHash, so an // unchanged skill is not reinstalled. const locked = asLocked(current, { name: skill.name, skillName: skill.entry.skillName }); const computedHash = await sourceSkillHash(locked).catch(() => null); const changed = skillPath !== skill.entry.skillPath || computedHash !== skill.entry.computedHash; if (!changed && onDisk.has(skill.name)) { upToDateCount++; // Pin a lock written before commits were recorded, so restores stop following the branch if (commit && !skill.entry.commit && !options.reportOutdated) { await addSkillToLocalLock(skill.name, { ...skill.entry, commit }); } continue; } if (options.reportOutdated) { options.reportOutdated( skill.name, changed ? buildGitHubCompareUrl(cloneSource, skill.entry.commit, commit) : undefined ); continue; } console.log(`${TEXT}Updating ${sanitizeMetadata(skill.name)}…${RESET}`); const results = await installToTargets( resolved, [locked], await placementFor(skill.entry.subagents, skill.entry.installMode) ); const outcome = targetOutcome(results); if (outcome.ok && computedHash) { await addSkillToLocalLock(skill.name, { ...skill.entry, skillPath, computedHash, // Drop a stale commit when the new one cannot be read commit, }); } if (reportInstall(skill.name, outcome)) successCount++; else failCount++; } } catch { console.log(`${DIM}✗ Failed to check for deleted skills from ${source}${RESET}`); if (!checked) failCount += skillsForSource.length; } finally { await cleanupTempDir(tempDir); } } if (upToDateCount > 0) { if ( upToDateCount === updatable.length + downloadItems.length && wkSuccessCount === 0 && wkFailCount === 0 ) { console.log(`${TEXT}✓ All project skills are up to date${RESET}`); } else { console.log(`${DIM}${upToDateCount} project skill(s) already up to date${RESET}`); } } printLegacyProjectSkills(legacy); return { successCount, failCount, foundCount: projectSkills.length }; } /** * Print each project skill whose installed files no longer match its * computedHash and return how many there are. An unreadable lock reports none. */ async function reportModifiedProjectSkills(skillFilter?: string[]): Promise { const cwd = process.cwd(); const lock = await readLocalLock(cwd).catch(() => null); if (!lock) return 0; const entries = Object.entries(lock.skills).filter(([name]) => matchesSkillFilter(name, skillFilter) ); const installedAt = new Map( (await listInstalledSkills({ global: false, cwd })).map((skill) => [ sanitizeName(skill.name), skill.canonicalPath, ]) ); const states = await Promise.all( entries.map(([name, entry]) => getLockedSkillState(name, entry, cwd, installedAt.get(sanitizeName(name))) ) ); const modified = entries.filter((_, index) => states[index] === 'modified'); for (const [name] of modified) { console.log(`${TEXT}✎ ${sanitizeMetadata(name)} has local changes${RESET}`); } return modified.length; } export function printLegacyProjectSkills( legacy: Array<{ name: string; source: string; entry: LocalSkillLockEntry }> ): void { if (legacy.length === 0) return; console.log(); console.log( `${DIM}${legacy.length} project skill(s) cannot be updated automatically (installed before skillPath tracking):${RESET}` ); for (const skill of legacy) { const reinstall = buildLocalUpdateSource(skill.entry); console.log(` ${TEXT}•${RESET} ${sanitizeMetadata(skill.name)}`); if (reinstall) { console.log(` ${DIM}To refresh: ${TEXT}npx skills add ${reinstall} -y${RESET}`); } else { console.log( ` ${DIM}To refresh: reinstall using the original full Git URL; this lock entry only has an ambiguous shorthand.${RESET}` ); } } } export async function runUpdate( args: string[] = [], mode: 'update' | 'check' = 'update' ): Promise { const options = parseUpdateOptions(args); let outdatedCount = 0; let modifiedCount = 0; if (mode === 'check') { // Never prompt: pick the scope automatically and only report upstream deletions. options.yes = true; options.reportOutdated = (name, compareUrl) => { outdatedCount++; console.log(`${TEXT}↑ ${sanitizeMetadata(name)} has an update${RESET}`); if (compareUrl) console.log(` Repository changes: ${compareUrl}`); }; } const scope = await resolveUpdateScope(options); if (options.skills && mode === 'update') { console.log(`${TEXT}Updating ${options.skills.join(', ')}…${RESET}`); } else { console.log(`${TEXT}Checking for skill updates…${RESET}`); } console.log(); let totalSuccess = 0; let totalFail = 0; let totalFound = 0; if (scope === 'global' || scope === 'both') { if (scope === 'both' && !options.skills) { console.log(`${BOLD}Global Skills${RESET}`); } const { successCount, failCount, checkedCount } = await updateGlobalSkills(options); totalSuccess += successCount; totalFail += failCount; totalFound += checkedCount; if (scope === 'both' && !options.skills) { console.log(); } } if (scope === 'project' || scope === 'both') { if (scope === 'both' && !options.skills) { console.log(`${BOLD}Project Skills${RESET}`); } const { successCount, failCount, foundCount } = await updateProjectSkills(options); totalSuccess += successCount; totalFail += failCount; totalFound += foundCount; if (mode === 'check') modifiedCount = await reportModifiedProjectSkills(options.skills); } if (options.skills && totalFound === 0) { console.log(`${DIM}No installed skills found matching: ${options.skills.join(', ')}${RESET}`); } console.log(); if (totalSuccess > 0) { console.log(`${TEXT}✓ Updated ${totalSuccess} skill(s)${RESET}`); } if (totalFail > 0) { console.log(`${DIM}Failed to update ${totalFail} skill(s)${RESET}`); process.exitCode = 1; } if (outdatedCount > 0) { console.log( `${TEXT}${outdatedCount} skill(s) can be updated; run ${BOLD}npx skills update${RESET}${TEXT} to install${RESET}` ); process.exitCode = 1; } if (modifiedCount > 0) { console.log( `${TEXT}${modifiedCount} skill(s) differ from skills-lock.json; run ${BOLD}npx skills install --force${RESET}${TEXT} to restore them${RESET}` ); process.exitCode = 1; } track({ event: 'update', scope, skillCount: String(totalSuccess + totalFail), successCount: String(totalSuccess), failCount: String(totalFail), }); console.log(); }