File size: 6,652 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | import { readdir, rm, stat, unlink, writeFile } from 'fs/promises'
import { join } from 'path'
import { clearCommandsCache } from '../../commands.js'
import { clearAllOutputStylesCache } from '../../constants/outputStyles.js'
import { clearAgentDefinitionsCache } from '../../tools/AgentTool/loadAgentsDir.js'
import { clearPromptCache } from '../../tools/SkillTool/prompt.js'
import { resetSentSkillNames } from '../attachments.js'
import { logForDebugging } from '../debug.js'
import { getErrnoCode } from '../errors.js'
import { logError } from '../log.js'
import { loadInstalledPluginsFromDisk } from './installedPluginsManager.js'
import { clearPluginAgentCache } from './loadPluginAgents.js'
import { clearPluginCommandCache } from './loadPluginCommands.js'
import {
clearPluginHookCache,
pruneRemovedPluginHooks,
} from './loadPluginHooks.js'
import { clearPluginOutputStyleCache } from './loadPluginOutputStyles.js'
import { clearPluginCache, getPluginCachePath } from './pluginLoader.js'
import { clearPluginOptionsCache } from './pluginOptionsStorage.js'
import { isPluginZipCacheEnabled } from './zipCache.js'
const ORPHANED_AT_FILENAME = '.orphaned_at'
const CLEANUP_AGE_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
export function clearAllPluginCaches(): void {
clearPluginCache()
clearPluginCommandCache()
clearPluginAgentCache()
clearPluginHookCache()
// Prune hooks from plugins no longer in the enabled set so uninstalled/
// disabled plugins stop firing immediately (gh-36995). Prune-only: hooks
// from newly-enabled plugins are NOT added here — they wait for
// /reload-plugins like commands/agents/MCP do. Fire-and-forget: old hooks
// stay valid until the prune completes (preserves gh-29767). No-op when
// STATE.registeredHooks is empty (test/preload.ts beforeEach clears it via
// resetStateForTests before reaching here).
pruneRemovedPluginHooks().catch(e => logError(e))
clearPluginOptionsCache()
clearPluginOutputStyleCache()
clearAllOutputStylesCache()
}
export function clearAllCaches(): void {
clearAllPluginCaches()
clearCommandsCache()
clearAgentDefinitionsCache()
clearPromptCache()
resetSentSkillNames()
}
/**
* Mark a plugin version as orphaned.
* Called when a plugin is uninstalled or updated to a new version.
*/
export async function markPluginVersionOrphaned(
versionPath: string,
): Promise<void> {
try {
await writeFile(getOrphanedAtPath(versionPath), `${Date.now()}`, 'utf-8')
} catch (error) {
logForDebugging(`Failed to write .orphaned_at: ${versionPath}: ${error}`)
}
}
/**
* Clean up orphaned plugin versions that have been orphaned for more than 7 days.
*
* Pass 1: Remove .orphaned_at from installed versions (clears stale markers)
* Pass 2: For each cached version not in installed_plugins.json:
* - If no .orphaned_at exists: create it (handles old CC versions, manual edits)
* - If .orphaned_at exists and > 7 days old: delete the version
*/
export async function cleanupOrphanedPluginVersionsInBackground(): Promise<void> {
// Zip cache mode stores plugins as .zip files, not directories. readSubdirs
// filters to directories only, so removeIfEmpty would see plugin dirs as empty
// and delete them (including the ZIPs). Skip cleanup entirely in zip mode.
if (isPluginZipCacheEnabled()) {
return
}
try {
const installedVersions = getInstalledVersionPaths()
if (!installedVersions) return
const cachePath = getPluginCachePath()
const now = Date.now()
// Pass 1: Remove .orphaned_at from installed versions
// This handles cases where a plugin was reinstalled after being orphaned
await Promise.all(
[...installedVersions].map(p => removeOrphanedAtMarker(p)),
)
// Pass 2: Process orphaned versions
for (const marketplace of await readSubdirs(cachePath)) {
const marketplacePath = join(cachePath, marketplace)
for (const plugin of await readSubdirs(marketplacePath)) {
const pluginPath = join(marketplacePath, plugin)
for (const version of await readSubdirs(pluginPath)) {
const versionPath = join(pluginPath, version)
if (installedVersions.has(versionPath)) continue
await processOrphanedPluginVersion(versionPath, now)
}
await removeIfEmpty(pluginPath)
}
await removeIfEmpty(marketplacePath)
}
} catch (error) {
logForDebugging(`Plugin cache cleanup failed: ${error}`)
}
}
function getOrphanedAtPath(versionPath: string): string {
return join(versionPath, ORPHANED_AT_FILENAME)
}
async function removeOrphanedAtMarker(versionPath: string): Promise<void> {
const orphanedAtPath = getOrphanedAtPath(versionPath)
try {
await unlink(orphanedAtPath)
} catch (error) {
const code = getErrnoCode(error)
if (code === 'ENOENT') return
logForDebugging(`Failed to remove .orphaned_at: ${versionPath}: ${error}`)
}
}
function getInstalledVersionPaths(): Set<string> | null {
try {
const paths = new Set<string>()
const diskData = loadInstalledPluginsFromDisk()
for (const installations of Object.values(diskData.plugins)) {
for (const entry of installations) {
paths.add(entry.installPath)
}
}
return paths
} catch (error) {
logForDebugging(`Failed to load installed plugins: ${error}`)
return null
}
}
async function processOrphanedPluginVersion(
versionPath: string,
now: number,
): Promise<void> {
const orphanedAtPath = getOrphanedAtPath(versionPath)
let orphanedAt: number
try {
orphanedAt = (await stat(orphanedAtPath)).mtimeMs
} catch (error) {
const code = getErrnoCode(error)
if (code === 'ENOENT') {
await markPluginVersionOrphaned(versionPath)
return
}
logForDebugging(`Failed to stat orphaned marker: ${versionPath}: ${error}`)
return
}
if (now - orphanedAt > CLEANUP_AGE_MS) {
try {
await rm(versionPath, { recursive: true, force: true })
} catch (error) {
logForDebugging(
`Failed to delete orphaned version: ${versionPath}: ${error}`,
)
}
}
}
async function removeIfEmpty(dirPath: string): Promise<void> {
if ((await readSubdirs(dirPath)).length === 0) {
try {
await rm(dirPath, { recursive: true, force: true })
} catch (error) {
logForDebugging(`Failed to remove empty dir: ${dirPath}: ${error}`)
}
}
}
async function readSubdirs(dirPath: string): Promise<string[]> {
try {
const entries = await readdir(dirPath, { withFileTypes: true })
return entries.filter(d => d.isDirectory()).map(d => d.name)
} catch {
return []
}
}
|