File size: 11,096 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | import { join } from 'path'
import { getCwd } from '../cwd.js'
import { logForDebugging } from '../debug.js'
import { logError } from '../log.js'
import type { SettingSource } from '../settings/constants.js'
import {
getInitialSettings,
getSettingsForSource,
updateSettingsForSource,
} from '../settings/settings.js'
import { getAddDirEnabledPlugins } from './addDirPluginSettings.js'
import {
getInMemoryInstalledPlugins,
migrateFromEnabledPlugins,
} from './installedPluginsManager.js'
import { getPluginById } from './marketplaceManager.js'
import {
type ExtendedPluginScope,
type PersistablePluginScope,
SETTING_SOURCE_TO_SCOPE,
scopeToSettingSource,
} from './pluginIdentifier.js'
import {
cacheAndRegisterPlugin,
registerPluginInstallation,
} from './pluginInstallationHelpers.js'
import { isLocalPluginSource, type PluginScope } from './schemas.js'
/**
* Checks for enabled plugins across all settings sources, including --add-dir.
*
* Uses getInitialSettings() which merges all sources with policy as
* highest priority, then layers --add-dir plugins underneath. This is the
* authoritative "is this plugin enabled?" check — don't delegate to
* getPluginEditableScopes() which serves a different purpose (scope tracking).
*
* @returns Array of plugin IDs (plugin@marketplace format) that are enabled
*/
export async function checkEnabledPlugins(): Promise<string[]> {
const settings = getInitialSettings()
const enabledPlugins: string[] = []
// Start with --add-dir plugins (lowest priority)
const addDirPlugins = getAddDirEnabledPlugins()
for (const [pluginId, value] of Object.entries(addDirPlugins)) {
if (pluginId.includes('@') && value) {
enabledPlugins.push(pluginId)
}
}
// Merged settings (policy > local > project > user) override --add-dir
if (settings.enabledPlugins) {
for (const [pluginId, value] of Object.entries(settings.enabledPlugins)) {
if (!pluginId.includes('@')) {
continue
}
const idx = enabledPlugins.indexOf(pluginId)
if (value) {
if (idx === -1) {
enabledPlugins.push(pluginId)
}
} else {
// Explicitly disabled — remove even if --add-dir enabled it
if (idx !== -1) {
enabledPlugins.splice(idx, 1)
}
}
}
}
return enabledPlugins
}
/**
* Gets the user-editable scope that "owns" each enabled plugin.
*
* Used for scope tracking: determining where to write back when a user
* enables/disables a plugin. Managed (policy) settings are processed first
* (lowest priority) because the user cannot edit them — the scope should
* resolve to the highest user-controllable source.
*
* NOTE: This is NOT the authoritative "is this plugin enabled?" check.
* Use checkEnabledPlugins() for that — it uses merged settings where
* policy has highest priority and can block user-enabled plugins.
*
* Precedence (lowest to highest):
* 0. addDir (--add-dir directories) - session-only, lowest priority
* 1. managed (policySettings) - not user-editable
* 2. user (userSettings)
* 3. project (projectSettings)
* 4. local (localSettings)
* 5. flag (flagSettings) - session-only, not persisted
*
* @returns Map of plugin ID to the user-editable scope that owns it
*/
export function getPluginEditableScopes(): Map<string, ExtendedPluginScope> {
const result = new Map<string, ExtendedPluginScope>()
// Process --add-dir directories FIRST (lowest priority, overridden by all standard sources)
const addDirPlugins = getAddDirEnabledPlugins()
for (const [pluginId, value] of Object.entries(addDirPlugins)) {
if (!pluginId.includes('@')) {
continue
}
if (value === true) {
result.set(pluginId, 'flag') // 'flag' scope = session-only, no write-back
} else if (value === false) {
result.delete(pluginId)
}
}
// Process standard sources in precedence order (later overrides earlier)
const scopeSources: Array<{
scope: ExtendedPluginScope
source: SettingSource
}> = [
{ scope: 'managed', source: 'policySettings' },
{ scope: 'user', source: 'userSettings' },
{ scope: 'project', source: 'projectSettings' },
{ scope: 'local', source: 'localSettings' },
{ scope: 'flag', source: 'flagSettings' },
]
for (const { scope, source } of scopeSources) {
const settings = getSettingsForSource(source)
if (!settings?.enabledPlugins) {
continue
}
for (const [pluginId, value] of Object.entries(settings.enabledPlugins)) {
// Skip invalid format
if (!pluginId.includes('@')) {
continue
}
// Log when a standard source overrides an --add-dir plugin
if (pluginId in addDirPlugins && addDirPlugins[pluginId] !== value) {
logForDebugging(
`Plugin ${pluginId} from --add-dir (${addDirPlugins[pluginId]}) overridden by ${source} (${value})`,
)
}
if (value === true) {
// Plugin enabled at this scope
result.set(pluginId, scope)
} else if (value === false) {
// Explicitly disabled - remove from result
result.delete(pluginId)
}
// Note: Other values (like version strings for future P2) are ignored for now
}
}
logForDebugging(
`Found ${result.size} enabled plugins with scopes: ${Array.from(
result.entries(),
)
.map(([id, scope]) => `${id}(${scope})`)
.join(', ')}`,
)
return result
}
/**
* Check if a scope is persistable (not session-only).
* @param scope The scope to check
* @returns true if the scope should be persisted to installed_plugins.json
*/
export function isPersistableScope(
scope: ExtendedPluginScope,
): scope is PersistablePluginScope {
return scope !== 'flag'
}
/**
* Convert SettingSource to plugin scope.
* @param source The settings source
* @returns The corresponding plugin scope
*/
export function settingSourceToScope(
source: SettingSource,
): ExtendedPluginScope {
return SETTING_SOURCE_TO_SCOPE[source]
}
/**
* Gets the list of currently installed plugins
* Reads from installed_plugins.json which tracks global installation state.
* Automatically runs migration on first call if needed.
*
* Always uses V2 format and initializes the in-memory session state
* (which triggers V1→V2 migration if needed).
*
* @returns Array of installed plugin IDs
*/
export async function getInstalledPlugins(): Promise<string[]> {
// Trigger sync in background (don't await - don't block startup)
// This syncs enabledPlugins from settings.json to installed_plugins.json
void migrateFromEnabledPlugins().catch(error => {
logError(error)
})
// Always use V2 format - initializes in-memory session state and triggers V1→V2 migration
const v2Data = getInMemoryInstalledPlugins()
const installed = Object.keys(v2Data.plugins)
logForDebugging(`Found ${installed.length} installed plugins`)
return installed
}
/**
* Finds plugins that are enabled but not installed
* @param enabledPlugins Array of enabled plugin IDs
* @returns Array of missing plugin IDs
*/
export async function findMissingPlugins(
enabledPlugins: string[],
): Promise<string[]> {
try {
const installedPlugins = await getInstalledPlugins()
// Filter to not-installed synchronously, then look up all in parallel.
// Results are collected in original enabledPlugins order.
const notInstalled = enabledPlugins.filter(
id => !installedPlugins.includes(id),
)
const lookups = await Promise.all(
notInstalled.map(async pluginId => {
try {
const plugin = await getPluginById(pluginId)
return { pluginId, found: plugin !== null && plugin !== undefined }
} catch (error) {
logForDebugging(
`Failed to check plugin ${pluginId} in marketplace: ${error}`,
)
// Plugin doesn't exist in any marketplace, will be handled as an error
return { pluginId, found: false }
}
}),
)
const missing = lookups
.filter(({ found }) => found)
.map(({ pluginId }) => pluginId)
return missing
} catch (error) {
logError(error)
return []
}
}
/**
* Result of plugin installation attempt
*/
export type PluginInstallResult = {
installed: string[]
failed: Array<{ name: string; error: string }>
}
/**
* Installation scope type for install functions (excludes 'managed' which is read-only)
*/
type InstallableScope = Exclude<PluginScope, 'managed'>
/**
* Installs the selected plugins
* @param pluginsToInstall Array of plugin IDs to install
* @param onProgress Optional callback for installation progress
* @param scope Installation scope: user, project, or local (defaults to 'user')
* @returns Installation results with succeeded and failed plugins
*/
export async function installSelectedPlugins(
pluginsToInstall: string[],
onProgress?: (name: string, index: number, total: number) => void,
scope: InstallableScope = 'user',
): Promise<PluginInstallResult> {
// Get projectPath for non-user scopes
const projectPath = scope !== 'user' ? getCwd() : undefined
// Get the correct settings source for this scope
const settingSource = scopeToSettingSource(scope)
const settings = getSettingsForSource(settingSource)
const updatedEnabledPlugins = { ...settings?.enabledPlugins }
const installed: string[] = []
const failed: Array<{ name: string; error: string }> = []
for (let i = 0; i < pluginsToInstall.length; i++) {
const pluginId = pluginsToInstall[i]
if (!pluginId) continue
if (onProgress) {
onProgress(pluginId, i + 1, pluginsToInstall.length)
}
try {
const pluginInfo = await getPluginById(pluginId)
if (!pluginInfo) {
failed.push({
name: pluginId,
error: 'Plugin not found in any marketplace',
})
continue
}
// Cache the plugin if it's from an external source
const { entry, marketplaceInstallLocation } = pluginInfo
if (!isLocalPluginSource(entry.source)) {
// External plugin - cache and register it with scope
await cacheAndRegisterPlugin(pluginId, entry, scope, projectPath)
} else {
// Local plugin - just register it with the install path and scope
registerPluginInstallation(
{
pluginId,
installPath: join(marketplaceInstallLocation, entry.source),
version: entry.version,
},
scope,
projectPath,
)
}
// Mark as enabled in settings
updatedEnabledPlugins[pluginId] = true
installed.push(pluginId)
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error)
failed.push({ name: pluginId, error: errorMessage })
logError(error)
}
}
// Update settings with newly enabled plugins using the correct settings source
updateSettingsForSource(settingSource, {
...settings,
enabledPlugins: updatedEnabledPlugins,
})
return { installed, failed }
}
|