From 22504b0a5bb0f460a5ce3682de1da051b7141b62 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 7 Jan 2026 11:06:17 +0800 Subject: [PATCH 01/30] feat: add extension for gemini and claude --- .gitignore | 1 + packages/cli/src/config/extension.ts | 47 +++ .../extensions/claude-converter.test.ts | 121 +++++++ .../src/config/extensions/claude-converter.ts | 181 +++++++++++ .../extensions/gemini-converter.test.ts | 63 ++++ .../src/config/extensions/gemini-converter.ts | 86 +++++ .../src/config/extensions/marketplace.test.ts | 78 +++++ .../cli/src/config/extensions/marketplace.ts | 259 +++++++++++++++ .../src/config/extensions/settings.test.ts | 138 ++++++++ .../cli/src/config/extensions/settings.ts | 149 +++++++++ .../FileCommandLoader-extension.test.ts | 296 ++++++++++++++++++ .../FileCommandLoader-markdown.test.ts | 117 +++++++ .../src/services/FileCommandLoader.test.ts | 20 +- .../cli/src/services/FileCommandLoader.ts | 274 +++++++++------- packages/cli/src/services/command-factory.ts | 159 ++++++++++ .../services/command-migration-tool.test.ts | 226 +++++++++++++ .../src/services/command-migration-tool.ts | 189 +++++++++++ .../services/markdown-command-parser.test.ts | 144 +++++++++ .../src/services/markdown-command-parser.ts | 64 ++++ .../cli/src/services/test-commands/example.md | 5 + .../toml-to-markdown-converter.test.ts | 103 ++++++ .../services/toml-to-markdown-converter.ts | 74 +++++ .../subagents/manage/AgentSelectionStep.tsx | 2 +- packages/cli/src/ui/hooks/useTomlMigration.ts | 0 .../skills/skill-manager-extension.test.ts | 191 +++++++++++ packages/core/src/skills/skill-manager.ts | 99 +++++- packages/core/src/skills/types.ts | 8 +- .../core/src/subagents/subagent-manager.ts | 12 +- packages/core/src/subagents/types.ts | 17 +- 29 files changed, 2984 insertions(+), 139 deletions(-) create mode 100644 packages/cli/src/config/extensions/claude-converter.test.ts create mode 100644 packages/cli/src/config/extensions/claude-converter.ts create mode 100644 packages/cli/src/config/extensions/gemini-converter.test.ts create mode 100644 packages/cli/src/config/extensions/gemini-converter.ts create mode 100644 packages/cli/src/config/extensions/marketplace.test.ts create mode 100644 packages/cli/src/config/extensions/marketplace.ts create mode 100644 packages/cli/src/config/extensions/settings.test.ts create mode 100644 packages/cli/src/config/extensions/settings.ts create mode 100644 packages/cli/src/services/FileCommandLoader-extension.test.ts create mode 100644 packages/cli/src/services/FileCommandLoader-markdown.test.ts create mode 100644 packages/cli/src/services/command-factory.ts create mode 100644 packages/cli/src/services/command-migration-tool.test.ts create mode 100644 packages/cli/src/services/command-migration-tool.ts create mode 100644 packages/cli/src/services/markdown-command-parser.test.ts create mode 100644 packages/cli/src/services/markdown-command-parser.ts create mode 100644 packages/cli/src/services/test-commands/example.md create mode 100644 packages/cli/src/services/toml-to-markdown-converter.test.ts create mode 100644 packages/cli/src/services/toml-to-markdown-converter.ts create mode 100644 packages/cli/src/ui/hooks/useTomlMigration.ts create mode 100644 packages/core/src/skills/skill-manager-extension.test.ts diff --git a/.gitignore b/.gitignore index fac00d4127f..705216c80c5 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,7 @@ package-lock.json .idea *.iml .cursor +.qoder # OS metadata .DS_Store diff --git a/packages/cli/src/config/extension.ts b/packages/cli/src/config/extension.ts index 2d30cc41f65..e9ed41635a2 100644 --- a/packages/cli/src/config/extension.ts +++ b/packages/cli/src/config/extension.ts @@ -49,6 +49,10 @@ export interface Extension { config: ExtensionConfig; contextFiles: string[]; installMetadata?: ExtensionInstallMetadata | undefined; + /** Absolute paths to skills directories from this extension */ + skillsPaths?: string[]; + /** Absolute paths to agents files from this extension */ + agentsPaths?: string[]; } export interface ExtensionConfig { @@ -57,6 +61,17 @@ export interface ExtensionConfig { mcpServers?: Record; contextFileName?: string | string[]; excludeTools?: string[]; + commands?: string | string[]; + skills?: string | string[]; + agents?: string | string[]; + settings?: ExtensionSetting[]; +} + +export interface ExtensionSetting { + name: string; + description: string; + envVar: string; + sensitive?: boolean; } export interface ExtensionUpdateInfo { @@ -238,11 +253,22 @@ export function loadExtension(context: LoadExtensionContext): Extension | null { ) .filter((contextFilePath) => fs.existsSync(contextFilePath)); + const skillsPaths = collectPathsFromConfig( + config.skills, + effectiveExtensionPath, + ); + const agentsPaths = collectPathsFromConfig( + config.agents, + effectiveExtensionPath, + ); + return { path: effectiveExtensionPath, config, contextFiles, installMetadata, + skillsPaths, + agentsPaths, }; } catch (e) { console.error( @@ -308,6 +334,27 @@ function getContextFileNames(config: ExtensionConfig): string[] { return config.contextFileName; } +function collectPathsFromConfig( + configValue: string | string[] | undefined, + extensionPath: string, +): string[] { + if (!configValue) return []; + + const pathArray = Array.isArray(configValue) ? configValue : [configValue]; + const absolutePaths: string[] = []; + + for (const relativePath of pathArray) { + const absolutePath = path.isAbsolute(relativePath) + ? relativePath + : path.join(extensionPath, relativePath); + + if (fs.existsSync(absolutePath)) { + absolutePaths.push(absolutePath); + } + } + return absolutePaths; +} + /** * Returns an annotated list of extensions. If an extension is listed in enabledExtensionNames, it will be active. * If enabledExtensionNames is empty, an extension is active unless it is disabled. diff --git a/packages/cli/src/config/extensions/claude-converter.test.ts b/packages/cli/src/config/extensions/claude-converter.test.ts new file mode 100644 index 00000000000..4502158c672 --- /dev/null +++ b/packages/cli/src/config/extensions/claude-converter.test.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { + convertClaudeToQwenConfig, + mergeClaudeConfigs, + isClaudePluginConfig, + type ClaudePluginConfig, + type ClaudeMarketplacePluginConfig, +} from './claude-converter.js'; + +describe('convertClaudeToQwenConfig', () => { + it('should convert basic Claude config', () => { + const claudeConfig: ClaudePluginConfig = { + name: 'claude-plugin', + version: '1.0.0', + }; + + const result = convertClaudeToQwenConfig(claudeConfig); + + expect(result.name).toBe('claude-plugin'); + expect(result.version).toBe('1.0.0'); + }); + + it('should convert config with commands and agents', () => { + const claudeConfig: ClaudePluginConfig = { + name: 'full-plugin', + version: '1.0.0', + commands: 'commands', + agents: ['agents/agent1.md'], + skills: ['skills/skill1'], + }; + + const result = convertClaudeToQwenConfig(claudeConfig); + + expect(result.commands).toBe('commands'); + expect(result.agents).toEqual(['agents/agent1.md']); + expect(result.skills).toEqual(['skills/skill1']); + }); + + it('should throw error for missing name', () => { + const invalidConfig = { + version: '1.0.0', + } as ClaudePluginConfig; + + expect(() => convertClaudeToQwenConfig(invalidConfig)).toThrow(); + }); +}); + +describe('mergeClaudeConfigs', () => { + it('should merge marketplace and plugin configs', () => { + const marketplacePlugin: ClaudeMarketplacePluginConfig = { + name: 'marketplace-name', + version: '2.0.0', + source: 'github:org/repo', + description: 'From marketplace', + }; + + const pluginConfig: ClaudePluginConfig = { + name: 'plugin-name', + version: '1.0.0', + commands: 'commands', + }; + + const merged = mergeClaudeConfigs(marketplacePlugin, pluginConfig); + + // Marketplace takes precedence + expect(merged.name).toBe('marketplace-name'); + expect(merged.version).toBe('2.0.0'); + expect(merged.description).toBe('From marketplace'); + // Plugin fields preserved + expect(merged.commands).toBe('commands'); + }); + + it('should work with strict=false and no plugin config', () => { + const marketplacePlugin: ClaudeMarketplacePluginConfig = { + name: 'standalone', + version: '1.0.0', + source: 'local', + strict: false, + commands: 'commands', + }; + + const merged = mergeClaudeConfigs(marketplacePlugin); + + expect(merged.name).toBe('standalone'); + expect(merged.commands).toBe('commands'); + }); + + it('should throw error for strict mode without plugin config', () => { + const marketplacePlugin: ClaudeMarketplacePluginConfig = { + name: 'strict-plugin', + version: '1.0.0', + source: 'github:org/repo', + strict: true, + }; + + expect(() => mergeClaudeConfigs(marketplacePlugin)).toThrow(); + }); +}); + +describe('isClaudePluginConfig', () => { + it('should identify Claude config with agent field', () => { + const config = { + name: 'test', + version: '1.0.0', + agents: ['agent.md'], + }; + + expect(isClaudePluginConfig(config)).toBe(true); + }); + + it('should return false for invalid config', () => { + expect(isClaudePluginConfig(null)).toBe(false); + expect(isClaudePluginConfig({})).toBe(false); + }); +}); diff --git a/packages/cli/src/config/extensions/claude-converter.ts b/packages/cli/src/config/extensions/claude-converter.ts new file mode 100644 index 00000000000..c6022ae6201 --- /dev/null +++ b/packages/cli/src/config/extensions/claude-converter.ts @@ -0,0 +1,181 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Converter for Claude Code plugins to Qwen Code format. + */ + +import type { ExtensionConfig } from '../extension.js'; +import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; + +export interface ClaudePluginConfig { + name: string; + version: string; + description?: string; + author?: { name?: string; email?: string; url?: string }; + homepage?: string; + repository?: string; + license?: string; + keywords?: string[]; + commands?: string | string[]; + agents?: string | string[]; + skills?: string | string[]; + hooks?: string; + mcpServers?: string | Record; + outputStyles?: string | string[]; + lspServers?: string; +} + +export type ClaudePluginSource = + | { source: 'github'; repo: string } + | { source: 'url'; url: string }; + +export interface ClaudeMarketplacePluginConfig extends ClaudePluginConfig { + source: string | ClaudePluginSource; + category?: string; + strict?: boolean; + tags?: string[]; +} + +export interface ClaudeMarketplaceConfig { + name: string; + owner: { name: string; email: string }; + plugins: ClaudeMarketplacePluginConfig[]; + metadata?: { description?: string; version?: string; pluginRoot?: string }; +} + +/** + * Converts a Claude plugin config to Qwen Code format. + * @param claudeConfig Claude plugin configuration + * @returns Qwen ExtensionConfig + */ +export function convertClaudeToQwenConfig( + claudeConfig: ClaudePluginConfig, +): ExtensionConfig { + // Validate required fields + if (!claudeConfig.name || !claudeConfig.version) { + throw new Error('Claude plugin config must have name and version fields'); + } + + // Parse MCP servers + let mcpServers: Record | undefined; + if (claudeConfig.mcpServers) { + if (typeof claudeConfig.mcpServers === 'string') { + // TODO: Load from file path + console.warn( + `[Claude Converter] MCP servers path not yet supported: ${claudeConfig.mcpServers}`, + ); + } else { + mcpServers = claudeConfig.mcpServers; + } + } + + // Warn about unsupported fields + if (claudeConfig.hooks) { + console.warn( + `[Claude Converter] Hooks are not yet supported in ${claudeConfig.name}`, + ); + } + if (claudeConfig.outputStyles) { + console.warn( + `[Claude Converter] Output styles are not yet supported in ${claudeConfig.name}`, + ); + } + if (claudeConfig.lspServers) { + console.warn( + `[Claude Converter] LSP servers are not yet supported in ${claudeConfig.name}`, + ); + } + + // Direct field mapping + return { + name: claudeConfig.name, + version: claudeConfig.version, + mcpServers, + commands: claudeConfig.commands, + skills: claudeConfig.skills, + agents: claudeConfig.agents, + }; +} + +/** + * Merges marketplace plugin config with the actual plugin.json config. + * Marketplace config takes precedence for conflicting fields. + * @param marketplacePlugin Marketplace plugin definition + * @param pluginConfig Actual plugin.json config (optional if strict=false) + * @returns Merged Claude plugin config + */ +export function mergeClaudeConfigs( + marketplacePlugin: ClaudeMarketplacePluginConfig, + pluginConfig?: ClaudePluginConfig, +): ClaudePluginConfig { + if (!pluginConfig && marketplacePlugin.strict !== false) { + throw new Error( + `Plugin ${marketplacePlugin.name} requires plugin.json (strict mode)`, + ); + } + + // Start with plugin.json config (if exists) + const merged: ClaudePluginConfig = pluginConfig + ? { ...pluginConfig } + : { + name: marketplacePlugin.name, + version: '1.0.0', // Default version if not in marketplace + }; + + // Overlay marketplace config (takes precedence) + if (marketplacePlugin.name) merged.name = marketplacePlugin.name; + if (marketplacePlugin.version) merged.version = marketplacePlugin.version; + if (marketplacePlugin.description) + merged.description = marketplacePlugin.description; + if (marketplacePlugin.author) merged.author = marketplacePlugin.author; + if (marketplacePlugin.homepage) merged.homepage = marketplacePlugin.homepage; + if (marketplacePlugin.repository) + merged.repository = marketplacePlugin.repository; + if (marketplacePlugin.license) merged.license = marketplacePlugin.license; + if (marketplacePlugin.keywords) merged.keywords = marketplacePlugin.keywords; + if (marketplacePlugin.commands) merged.commands = marketplacePlugin.commands; + if (marketplacePlugin.agents) merged.agents = marketplacePlugin.agents; + if (marketplacePlugin.skills) merged.skills = marketplacePlugin.skills; + if (marketplacePlugin.hooks) merged.hooks = marketplacePlugin.hooks; + if (marketplacePlugin.mcpServers) + merged.mcpServers = marketplacePlugin.mcpServers; + if (marketplacePlugin.outputStyles) + merged.outputStyles = marketplacePlugin.outputStyles; + if (marketplacePlugin.lspServers) + merged.lspServers = marketplacePlugin.lspServers; + + return merged; +} + +/** + * Checks if a config object is in Claude plugin format. + * @param config Configuration object to check + * @returns true if config appears to be Claude format + */ +export function isClaudePluginConfig( + config: unknown, +): config is ClaudePluginConfig { + if (typeof config !== 'object' || config === null) { + return false; + } + + const obj = config as Record; + + // Must have name and version + if (typeof obj['name'] !== 'string' || typeof obj['version'] !== 'string') { + return false; + } + + // Check for Claude-specific fields + const hasClaudeFields = + 'agents' in obj || + 'hooks' in obj || + 'outputStyles' in obj || + 'lspServers' in obj; + + return hasClaudeFields; +} diff --git a/packages/cli/src/config/extensions/gemini-converter.test.ts b/packages/cli/src/config/extensions/gemini-converter.test.ts new file mode 100644 index 00000000000..94e1f11f57b --- /dev/null +++ b/packages/cli/src/config/extensions/gemini-converter.test.ts @@ -0,0 +1,63 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { + convertGeminiToQwenConfig, + isGeminiExtensionConfig, + type GeminiExtensionConfig, +} from './gemini-converter.js'; + +describe('convertGeminiToQwenConfig', () => { + it('should convert basic Gemini config', () => { + const geminiConfig: GeminiExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = convertGeminiToQwenConfig(geminiConfig); + + expect(result.name).toBe('test-extension'); + expect(result.version).toBe('1.0.0'); + }); + + it('should convert config with commands', () => { + const geminiConfig: GeminiExtensionConfig = { + name: 'cmd-extension', + version: '1.0.0', + commands: 'commands', + }; + + const result = convertGeminiToQwenConfig(geminiConfig); + + expect(result.commands).toBe('commands'); + }); + + it('should throw error for missing name', () => { + const invalidConfig = { + version: '1.0.0', + } as GeminiExtensionConfig; + + expect(() => convertGeminiToQwenConfig(invalidConfig)).toThrow(); + }); +}); + +describe('isGeminiExtensionConfig', () => { + it('should identify Gemini config with settings', () => { + const config = { + name: 'test', + version: '1.0.0', + settings: [{ name: 'Test', envVar: 'TEST', description: 'Test' }], + }; + + expect(isGeminiExtensionConfig(config)).toBe(true); + }); + + it('should return false for invalid config', () => { + expect(isGeminiExtensionConfig(null)).toBe(false); + expect(isGeminiExtensionConfig({})).toBe(false); + }); +}); diff --git a/packages/cli/src/config/extensions/gemini-converter.ts b/packages/cli/src/config/extensions/gemini-converter.ts new file mode 100644 index 00000000000..2ed71c03773 --- /dev/null +++ b/packages/cli/src/config/extensions/gemini-converter.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Converter for Gemini CLI extensions to Qwen Code format. + */ + +import type { ExtensionConfig, ExtensionSetting } from '../extension.js'; + +export interface GeminiExtensionConfig { + name: string; + version: string; + mcpServers?: Record; + contextFileName?: string | string[]; + excludeTools?: string[]; + commands?: string | string[]; + settings?: ExtensionSetting[]; +} + +/** + * Converts a Gemini CLI extension config to Qwen Code format. + * @param geminiConfig Gemini extension configuration + * @returns Qwen ExtensionConfig + */ +export function convertGeminiToQwenConfig( + geminiConfig: GeminiExtensionConfig, +): ExtensionConfig { + // Validate required fields + if (!geminiConfig.name || !geminiConfig.version) { + throw new Error( + 'Gemini extension config must have name and version fields', + ); + } + + const settings: ExtensionSetting[] | undefined = geminiConfig.settings; + + // Direct field mapping + return { + name: geminiConfig.name, + version: geminiConfig.version, + mcpServers: geminiConfig.mcpServers as ExtensionConfig['mcpServers'], + contextFileName: geminiConfig.contextFileName, + excludeTools: geminiConfig.excludeTools, + commands: geminiConfig.commands, + settings, + }; +} + +/** + * Checks if a config object is in Gemini format. + * This is a heuristic check based on typical Gemini extension patterns. + * @param config Configuration object to check + * @returns true if config appears to be Gemini format + */ +export function isGeminiExtensionConfig( + config: unknown, +): config is GeminiExtensionConfig { + if (typeof config !== 'object' || config === null) { + return false; + } + + const obj = config as Record; + + // Must have name and version + if (typeof obj['name'] !== 'string' || typeof obj['version'] !== 'string') { + return false; + } + + // Check for Gemini-specific settings format + if (obj['settings'] && Array.isArray(obj['settings'])) { + const firstSetting = obj['settings'][0]; + if ( + firstSetting && + typeof firstSetting === 'object' && + 'envVar' in firstSetting + ) { + return true; + } + } + + // If it has Gemini-specific fields but not Qwen-specific fields, likely Gemini + return true; +} diff --git a/packages/cli/src/config/extensions/marketplace.test.ts b/packages/cli/src/config/extensions/marketplace.test.ts new file mode 100644 index 00000000000..151aa9efab6 --- /dev/null +++ b/packages/cli/src/config/extensions/marketplace.test.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { parseMarketplaceSource } from './marketplace.js'; + +describe('Marketplace Installation', () => { + describe('parseMarketplaceSource', () => { + it('should parse valid marketplace source with http URL', () => { + const result = parseMarketplaceSource( + 'http://example.com/marketplace:my-plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'http://example.com/marketplace', + pluginName: 'my-plugin', + }); + }); + + it('should parse valid marketplace source with https URL', () => { + const result = parseMarketplaceSource( + 'https://github.com/example/marketplace:awesome-plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://github.com/example/marketplace', + pluginName: 'awesome-plugin', + }); + }); + + it('should handle plugin names with hyphens', () => { + const result = parseMarketplaceSource( + 'https://example.com:my-super-plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://example.com', + pluginName: 'my-super-plugin', + }); + }); + + it('should handle URLs with ports', () => { + const result = parseMarketplaceSource( + 'https://example.com:8080/marketplace:plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://example.com:8080/marketplace', + pluginName: 'plugin', + }); + }); + + it('should return null for source without colon separator', () => { + const result = parseMarketplaceSource('https://example.com/plugin'); + expect(result).toBeNull(); + }); + + it('should return null for source without URL', () => { + const result = parseMarketplaceSource('not-a-url:plugin'); + expect(result).toBeNull(); + }); + + it('should return null for source with empty plugin name', () => { + const result = parseMarketplaceSource('https://example.com:'); + expect(result).toBeNull(); + }); + + it('should use last colon as separator', () => { + // URLs with ports have colons, should use the last one + const result = parseMarketplaceSource( + 'https://example.com:8080:my-plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://example.com:8080', + pluginName: 'my-plugin', + }); + }); + }); +}); diff --git a/packages/cli/src/config/extensions/marketplace.ts b/packages/cli/src/config/extensions/marketplace.ts new file mode 100644 index 00000000000..e254ca41ffa --- /dev/null +++ b/packages/cli/src/config/extensions/marketplace.ts @@ -0,0 +1,259 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * This module handles installation of extensions from Claude marketplaces. + * + * A marketplace URL format: marketplace-url:plugin-name + * Example: https://github.com/example/marketplace:my-plugin + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { ExtensionConfig } from '../extension.js'; +import { + convertClaudeToQwenConfig, + mergeClaudeConfigs, + type ClaudeMarketplaceConfig, + type ClaudeMarketplacePluginConfig, + type ClaudePluginConfig, +} from './claude-converter.js'; +import { cloneFromGit, downloadFromGitHubRelease } from './github.js'; +import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; + +export interface MarketplaceInstallOptions { + marketplaceUrl: string; + pluginName: string; + tempDir: string; + requestConsent: (consent: string) => Promise; +} + +export interface MarketplaceInstallResult { + config: ExtensionConfig; + sourcePath: string; + installMetadata: ExtensionInstallMetadata; +} + +/** + * Parse marketplace install source string. + * Format: marketplace-url:plugin-name + */ +export function parseMarketplaceSource(source: string): { + marketplaceUrl: string; + pluginName: string; +} | null { + // Check if source contains a colon separator + const lastColonIndex = source.lastIndexOf(':'); + if (lastColonIndex === -1) { + return null; + } + + // Split at the last colon to separate URL from plugin name + const marketplaceUrl = source.substring(0, lastColonIndex); + const pluginName = source.substring(lastColonIndex + 1); + + // Validate that marketplace URL looks like a URL + if ( + !marketplaceUrl.startsWith('http://') && + !marketplaceUrl.startsWith('https://') + ) { + return null; + } + + if (!pluginName || pluginName.length === 0) { + return null; + } + + return { marketplaceUrl, pluginName }; +} + +/** + * Install an extension from a Claude marketplace. + * + * Process: + * 1. Download marketplace repository + * 2. Parse marketplace.json + * 3. Find the specified plugin + * 4. Download/copy plugin source + * 5. Merge configurations (if strict mode) + * 6. Convert to Qwen format + */ +export async function installFromMarketplace( + options: MarketplaceInstallOptions, +): Promise { + const { + marketplaceUrl, + pluginName, + tempDir, + requestConsent: _requestConsent, + } = options; + + // Step 1: Download marketplace repository + const marketplaceDir = path.join(tempDir, 'marketplace'); + await fs.promises.mkdir(marketplaceDir, { recursive: true }); + + console.log(`Downloading marketplace from ${marketplaceUrl}...`); + const installMetadata: ExtensionInstallMetadata = { + source: marketplaceUrl, + type: 'git', + }; + + try { + await downloadFromGitHubRelease(installMetadata, marketplaceDir); + } catch { + await cloneFromGit(installMetadata, marketplaceDir); + } + + // Step 2: Parse marketplace.json + const marketplaceConfigPath = path.join(marketplaceDir, 'marketplace.json'); + if (!fs.existsSync(marketplaceConfigPath)) { + throw new Error( + `Marketplace configuration not found at ${marketplaceConfigPath}`, + ); + } + + const marketplaceConfigContent = await fs.promises.readFile( + marketplaceConfigPath, + 'utf-8', + ); + const marketplaceConfig: ClaudeMarketplaceConfig = JSON.parse( + marketplaceConfigContent, + ); + + // Step 3: Find the plugin + const pluginConfig = marketplaceConfig.plugins.find( + (p) => p.name.toLowerCase() === pluginName.toLowerCase(), + ); + + if (!pluginConfig) { + throw new Error( + `Plugin "${pluginName}" not found in marketplace. Available plugins: ${marketplaceConfig.plugins.map((p) => p.name).join(', ')}`, + ); + } + + // Step 4: Download/copy plugin source + const pluginDir = path.join(tempDir, 'plugin'); + await fs.promises.mkdir(pluginDir, { recursive: true }); + + const pluginSource = await resolvePluginSource( + pluginConfig, + marketplaceDir, + pluginDir, + ); + + // Step 5: Merge configurations (if strict mode) + let finalPluginConfig: ClaudePluginConfig; + const strict = pluginConfig.strict ?? true; + + if (strict) { + // Read plugin.json from plugin source + const pluginJsonPath = path.join( + pluginSource, + '.claude-plugin', + 'plugin.json', + ); + if (!fs.existsSync(pluginJsonPath)) { + throw new Error( + `Strict mode requires plugin.json at ${pluginJsonPath}, but file not found`, + ); + } + + const pluginJsonContent = await fs.promises.readFile( + pluginJsonPath, + 'utf-8', + ); + const basePluginConfig: ClaudePluginConfig = JSON.parse(pluginJsonContent); + + // Merge marketplace config with plugin config + finalPluginConfig = mergeClaudeConfigs(pluginConfig, basePluginConfig); + } else { + // Use marketplace config directly + finalPluginConfig = pluginConfig; + } + + // Step 6: Convert to Qwen format + const qwenConfig = convertClaudeToQwenConfig(finalPluginConfig); + + return { + config: qwenConfig, + sourcePath: pluginSource, + installMetadata: { + source: `${marketplaceUrl}:${pluginName}`, + type: 'git', // Marketplace installs are treated as git installs + }, + }; +} + +/** + * Resolve plugin source from marketplace plugin configuration. + * Returns the absolute path to the plugin source directory. + */ +async function resolvePluginSource( + pluginConfig: ClaudeMarketplacePluginConfig, + marketplaceDir: string, + pluginDir: string, +): Promise { + const source = pluginConfig.source; + + // Handle string source (relative path or URL) + if (typeof source === 'string') { + // Check if it's a URL + if (source.startsWith('http://') || source.startsWith('https://')) { + // Download from URL + const installMetadata: ExtensionInstallMetadata = { + source, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + // Relative path within marketplace + const pluginRoot = marketplaceDir; + const sourcePath = path.join(pluginRoot, source); + + if (!fs.existsSync(sourcePath)) { + throw new Error(`Plugin source not found at ${sourcePath}`); + } + + // Copy to plugin directory + await fs.promises.cp(sourcePath, pluginDir, { recursive: true }); + return pluginDir; + } + + // Handle object source (github or url) + if (source.source === 'github') { + const installMetadata: ExtensionInstallMetadata = { + source: `https://github.com/${source.repo}`, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + if (source.source === 'url') { + const installMetadata: ExtensionInstallMetadata = { + source: source.url, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + throw new Error(`Unsupported plugin source type: ${JSON.stringify(source)}`); +} diff --git a/packages/cli/src/config/extensions/settings.test.ts b/packages/cli/src/config/extensions/settings.test.ts new file mode 100644 index 00000000000..cdd9517261d --- /dev/null +++ b/packages/cli/src/config/extensions/settings.test.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { parseEnvFile, generateEnvFile, validateSettings } from './settings.js'; +import type { ExtensionSetting } from '../extension.js'; + +describe('Extension Settings', () => { + describe('parseEnvFile', () => { + it('should parse simple KEY=VALUE pairs', () => { + const content = 'API_KEY=abc123\nSERVER_URL=http://example.com'; + const result = parseEnvFile(content); + expect(result).toEqual({ + API_KEY: 'abc123', + SERVER_URL: 'http://example.com', + }); + }); + + it('should skip empty lines and comments', () => { + const content = ` +# This is a comment +API_KEY=secret + +# Another comment +DEBUG=true +`; + const result = parseEnvFile(content); + expect(result).toEqual({ + API_KEY: 'secret', + DEBUG: 'true', + }); + }); + + it('should handle quoted values', () => { + const content = `API_KEY="my secret key"\nPATH='/usr/local/bin'`; + const result = parseEnvFile(content); + expect(result).toEqual({ + API_KEY: 'my secret key', + PATH: '/usr/local/bin', + }); + }); + + it('should ignore invalid lines', () => { + const content = 'VALID=value\nINVALID LINE\nANOTHER=valid'; + const result = parseEnvFile(content); + expect(result).toEqual({ + VALID: 'value', + ANOTHER: 'valid', + }); + }); + }); + + describe('generateEnvFile', () => { + it('should generate properly formatted .env content', () => { + const settings = { + API_KEY: 'secret123', + DEBUG: 'true', + }; + const result = generateEnvFile(settings); + expect(result).toContain('API_KEY=secret123'); + expect(result).toContain('DEBUG=true'); + expect(result).toContain('# Extension Settings'); + }); + + it('should quote values with spaces', () => { + const settings = { + MESSAGE: 'Hello World', + PATH: '/usr/local/bin', + }; + const result = generateEnvFile(settings); + expect(result).toContain('MESSAGE="Hello World"'); + expect(result).toContain('PATH=/usr/local/bin'); + }); + }); + + describe('validateSettings', () => { + it('should pass validation for valid string settings', () => { + const settingsConfig: ExtensionSetting[] = [ + { + name: 'API Key', + description: 'Your API key for the service', + envVar: 'API_KEY', + }, + ]; + const settings = { API_KEY: 'my-key' }; + const errors = validateSettings(settings, settingsConfig); + expect(errors).toHaveLength(0); + }); + + it('should fail validation for non-string values', () => { + const settingsConfig: ExtensionSetting[] = [ + { + name: 'API Key', + description: 'Your API key for the service', + envVar: 'API_KEY', + }, + ]; + // In TypeScript, this would be caught at compile time, + // but at runtime we check the type + const settings = { API_KEY: 123 as unknown as string }; + const errors = validateSettings(settings, settingsConfig); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain('API Key'); + expect(errors[0]).toContain('string'); + }); + + it('should allow undefined/missing settings (all settings are optional)', () => { + const settingsConfig: ExtensionSetting[] = [ + { + name: 'Optional Setting', + description: 'An optional setting', + envVar: 'OPTIONAL_VAR', + }, + ]; + + const settings = {}; + const errors = validateSettings(settings, settingsConfig); + expect(errors).toHaveLength(0); + }); + + it('should validate sensitive settings the same way', () => { + const settingsConfig: ExtensionSetting[] = [ + { + name: 'Secret Key', + description: 'Your secret key', + envVar: 'SECRET_KEY', + sensitive: true, + }, + ]; + + const validSettings = { SECRET_KEY: 'super-secret' }; + expect(validateSettings(validSettings, settingsConfig)).toHaveLength(0); + }); + }); +}); diff --git a/packages/cli/src/config/extensions/settings.ts b/packages/cli/src/config/extensions/settings.ts new file mode 100644 index 00000000000..baff07338ae --- /dev/null +++ b/packages/cli/src/config/extensions/settings.ts @@ -0,0 +1,149 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * This module handles extension settings management. + * Settings are stored in .env files within extension directories. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { ExtensionSetting } from '../extension.js'; + +/** + * Parse .env file content into key-value pairs. + * Simple parser that handles: + * - KEY=VALUE format + * - Comments starting with # + * - Empty lines + */ +export function parseEnvFile(content: string): Record { + const result: Record = {}; + const lines = content.split('\n'); + + for (const line of lines) { + const trimmed = line.trim(); + + // Skip empty lines and comments + if (!trimmed || trimmed.startsWith('#')) { + continue; + } + + // Parse KEY=VALUE + const equalIndex = trimmed.indexOf('='); + if (equalIndex === -1) { + continue; // Invalid line, skip + } + + const key = trimmed.substring(0, equalIndex).trim(); + const value = trimmed.substring(equalIndex + 1).trim(); + + // Remove quotes if present + let cleanValue = value; + if ( + (value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'")) + ) { + cleanValue = value.substring(1, value.length - 1); + } + + result[key] = cleanValue; + } + + return result; +} + +/** + * Generate .env file content from key-value pairs. + */ +export function generateEnvFile(settings: Record): string { + const lines: string[] = []; + + lines.push('# Extension Settings'); + lines.push('# Generated by Qwen Code'); + lines.push(''); + + for (const [key, value] of Object.entries(settings)) { + // Quote values that contain spaces + const quotedValue = value.includes(' ') ? `"${value}"` : value; + lines.push(`${key}=${quotedValue}`); + } + + return lines.join('\n') + '\n'; +} + +/** + * Load settings from extension .env file. + */ +export async function loadExtensionSettings( + extensionPath: string, +): Promise> { + const envPath = path.join(extensionPath, '.env'); + + try { + const content = await fs.promises.readFile(envPath, 'utf-8'); + return parseEnvFile(content); + } catch (error) { + // If .env file doesn't exist, return empty object + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return {}; + } + throw error; + } +} + +/** + * Save settings to extension .env file. + */ +export async function saveExtensionSettings( + extensionPath: string, + settings: Record, +): Promise { + const envPath = path.join(extensionPath, '.env'); + const content = generateEnvFile(settings); + await fs.promises.writeFile(envPath, content, 'utf-8'); +} + +/** + * Validate settings against configuration. + * Returns array of validation errors (empty if valid). + * + * Note: This validates that environment variables are properly set. + * In Gemini Extension format, all settings are treated as strings. + */ +export function validateSettings( + settings: Record, + settingsConfig: ExtensionSetting[], +): string[] { + const errors: string[] = []; + + for (const config of settingsConfig) { + const value = settings[config.envVar]; + + // Basic validation - check if value exists and is not empty + // Note: All settings are optional in Gemini Extension format + if (value !== undefined && typeof value !== 'string') { + errors.push( + `Setting "${config.name}" (${config.envVar}) must be a string`, + ); + } + } + + return errors; +} + +/** + * Merge extension settings into process environment. + * This allows MCP servers and other extension components to access settings. + */ +export function applySettingsToEnv(settings: Record): void { + for (const [key, value] of Object.entries(settings)) { + // Only set if not already defined in process.env + if (process.env[key] === undefined) { + process.env[key] = value; + } + } +} diff --git a/packages/cli/src/services/FileCommandLoader-extension.test.ts b/packages/cli/src/services/FileCommandLoader-extension.test.ts new file mode 100644 index 00000000000..c579bf20a37 --- /dev/null +++ b/packages/cli/src/services/FileCommandLoader-extension.test.ts @@ -0,0 +1,296 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { FileCommandLoader } from './FileCommandLoader.js'; +import type { Config } from '@qwen-code/qwen-code-core'; +import { Storage } from '@qwen-code/qwen-code-core'; + +describe('FileCommandLoader - Extension Commands Support', () => { + let tempDir: string; + let mockConfig: Partial; + + beforeEach(async () => { + tempDir = await fs.promises.mkdtemp( + path.join(os.tmpdir(), 'file-command-loader-ext-test-'), + ); + + mockConfig = { + getFolderTrustFeature: () => false, + getFolderTrust: () => true, + getProjectRoot: () => tempDir, + storage: new Storage(tempDir), + getExtensions: () => [], + }; + }); + + afterEach(async () => { + await fs.promises.rm(tempDir, { recursive: true, force: true }); + }); + + it('should load commands from extension with config.commands path', async () => { + // Setup extension structure + const extensionDir = path.join(tempDir, '.qwen', 'extensions', 'test-ext'); + const customCommandsDir = path.join(extensionDir, 'custom-cmds'); + await fs.promises.mkdir(customCommandsDir, { recursive: true }); + + // Create extension config with custom commands path + const extensionConfig = { + name: 'test-ext', + version: '1.0.0', + commands: 'custom-cmds', + }; + await fs.promises.writeFile( + path.join(extensionDir, 'qwen-extension.json'), + JSON.stringify(extensionConfig), + ); + + // Create a test command in custom directory + const commandContent = + '---\ndescription: Test command from extension\n---\nDo something'; + await fs.promises.writeFile( + path.join(customCommandsDir, 'test.md'), + commandContent, + ); + + // Mock config to return the extension + mockConfig.getExtensions = () => [ + { + name: 'test-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(1); + expect(commands[0].name).toBe('test-ext:test'); + expect(commands[0].description).toBe( + '[test-ext] Test command from extension', + ); + }); + + it('should load commands from extension with multiple commands paths', async () => { + // Setup extension structure + const extensionDir = path.join(tempDir, '.qwen', 'extensions', 'multi-ext'); + const cmdsDir1 = path.join(extensionDir, 'commands1'); + const cmdsDir2 = path.join(extensionDir, 'commands2'); + await fs.promises.mkdir(cmdsDir1, { recursive: true }); + await fs.promises.mkdir(cmdsDir2, { recursive: true }); + + // Create extension config with multiple commands paths + const extensionConfig = { + name: 'multi-ext', + version: '1.0.0', + commands: ['commands1', 'commands2'], + }; + await fs.promises.writeFile( + path.join(extensionDir, 'qwen-extension.json'), + JSON.stringify(extensionConfig), + ); + + // Create test commands in both directories + await fs.promises.writeFile( + path.join(cmdsDir1, 'cmd1.md'), + '---\n---\nCommand 1', + ); + await fs.promises.writeFile( + path.join(cmdsDir2, 'cmd2.md'), + '---\n---\nCommand 2', + ); + + // Mock config to return the extension + mockConfig.getExtensions = () => [ + { + name: 'multi-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(2); + const commandNames = commands.map((c) => c.name).sort(); + expect(commandNames).toEqual(['multi-ext:cmd1', 'multi-ext:cmd2']); + }); + + it('should fallback to default "commands" directory when config.commands not specified', async () => { + // Setup extension structure with default commands directory + const extensionDir = path.join( + tempDir, + '.qwen', + 'extensions', + 'default-ext', + ); + const defaultCommandsDir = path.join(extensionDir, 'commands'); + await fs.promises.mkdir(defaultCommandsDir, { recursive: true }); + + // Create extension config without commands field + const extensionConfig = { + name: 'default-ext', + version: '1.0.0', + }; + await fs.promises.writeFile( + path.join(extensionDir, 'qwen-extension.json'), + JSON.stringify(extensionConfig), + ); + + // Create a test command in default directory + await fs.promises.writeFile( + path.join(defaultCommandsDir, 'default.md'), + '---\n---\nDefault command', + ); + + // Mock config to return the extension + mockConfig.getExtensions = () => [ + { + name: 'default-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(1); + expect(commands[0].name).toBe('default-ext:default'); + }); + + it('should handle extension without commands directory gracefully', async () => { + // Setup extension structure without commands directory + const extensionDir = path.join( + tempDir, + '.qwen', + 'extensions', + 'no-cmds-ext', + ); + await fs.promises.mkdir(extensionDir, { recursive: true }); + + // Create extension config + const extensionConfig = { + name: 'no-cmds-ext', + version: '1.0.0', + }; + await fs.promises.writeFile( + path.join(extensionDir, 'qwen-extension.json'), + JSON.stringify(extensionConfig), + ); + + // Mock config to return the extension + mockConfig.getExtensions = () => [ + { + name: 'no-cmds-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + // Should not throw and return empty array + expect(commands).toHaveLength(0); + }); + + it('should prefix extension commands with extension name', async () => { + // Setup extension + const extensionDir = path.join( + tempDir, + '.qwen', + 'extensions', + 'prefix-ext', + ); + const commandsDir = path.join(extensionDir, 'commands'); + await fs.promises.mkdir(commandsDir, { recursive: true }); + + const extensionConfig = { + name: 'prefix-ext', + version: '1.0.0', + }; + await fs.promises.writeFile( + path.join(extensionDir, 'qwen-extension.json'), + JSON.stringify(extensionConfig), + ); + + await fs.promises.writeFile( + path.join(commandsDir, 'mycommand.md'), + '---\n---\nMy command', + ); + + mockConfig.getExtensions = () => [ + { + name: 'prefix-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(1); + expect(commands[0].name).toBe('prefix-ext:mycommand'); + }); + + it('should load commands from multiple extensions in alphabetical order', async () => { + // Setup two extensions + const ext1Dir = path.join(tempDir, '.qwen', 'extensions', 'ext-b'); + const ext2Dir = path.join(tempDir, '.qwen', 'extensions', 'ext-a'); + + await fs.promises.mkdir(path.join(ext1Dir, 'commands'), { + recursive: true, + }); + await fs.promises.mkdir(path.join(ext2Dir, 'commands'), { + recursive: true, + }); + + // Extension B + await fs.promises.writeFile( + path.join(ext1Dir, 'qwen-extension.json'), + JSON.stringify({ name: 'ext-b', version: '1.0.0' }), + ); + await fs.promises.writeFile( + path.join(ext1Dir, 'commands', 'cmd.md'), + '---\n---\nCommand B', + ); + + // Extension A + await fs.promises.writeFile( + path.join(ext2Dir, 'qwen-extension.json'), + JSON.stringify({ name: 'ext-a', version: '1.0.0' }), + ); + await fs.promises.writeFile( + path.join(ext2Dir, 'commands', 'cmd.md'), + '---\n---\nCommand A', + ); + + mockConfig.getExtensions = () => [ + { name: 'ext-b', version: '1.0.0', isActive: true, path: ext1Dir }, + { name: 'ext-a', version: '1.0.0', isActive: true, path: ext2Dir }, + ]; + + const loader = new FileCommandLoader(mockConfig as Config); + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(2); + // Extensions are sorted alphabetically, so ext-a comes before ext-b + expect(commands[0].name).toBe('ext-a:cmd'); + expect(commands[1].name).toBe('ext-b:cmd'); + }); +}); diff --git a/packages/cli/src/services/FileCommandLoader-markdown.test.ts b/packages/cli/src/services/FileCommandLoader-markdown.test.ts new file mode 100644 index 00000000000..590f2d100ba --- /dev/null +++ b/packages/cli/src/services/FileCommandLoader-markdown.test.ts @@ -0,0 +1,117 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { FileCommandLoader } from './FileCommandLoader.js'; + +describe('FileCommandLoader - Markdown support', () => { + let tempDir: string; + + beforeAll(async () => { + // Create a temporary directory for test commands + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-md-test-')); + }); + + afterAll(async () => { + // Clean up + await fs.rm(tempDir, { recursive: true, force: true }); + }); + + it('should load markdown commands with frontmatter', async () => { + // Create a test markdown command file + const mdContent = `--- +description: Test markdown command +--- + +This is a test prompt from markdown.`; + + const commandPath = path.join(tempDir, 'test-command.md'); + await fs.writeFile(commandPath, mdContent, 'utf-8'); + + // Create loader with temp dir as command source + const loader = new FileCommandLoader(null); + + // Mock the getCommandDirectories to return our temp dir + const originalMethod = loader['getCommandDirectories']; + loader['getCommandDirectories'] = () => [{ path: tempDir }]; + + try { + const commands = await loader.loadCommands(new AbortController().signal); + + expect(commands).toHaveLength(1); + expect(commands[0].name).toBe('test-command'); + expect(commands[0].description).toBe('Test markdown command'); + } finally { + // Restore original method + loader['getCommandDirectories'] = originalMethod; + } + }); + + it('should load markdown commands without frontmatter', async () => { + // Create a test markdown command file without frontmatter + const mdContent = 'This is a simple prompt without frontmatter.'; + + const commandPath = path.join(tempDir, 'simple-command.md'); + await fs.writeFile(commandPath, mdContent, 'utf-8'); + + const loader = new FileCommandLoader(null); + const originalMethod = loader['getCommandDirectories']; + loader['getCommandDirectories'] = () => [{ path: tempDir }]; + + try { + const commands = await loader.loadCommands(new AbortController().signal); + + const simpleCommand = commands.find( + (cmd) => cmd.name === 'simple-command', + ); + expect(simpleCommand).toBeDefined(); + expect(simpleCommand?.description).toContain('Custom command from'); + } finally { + loader['getCommandDirectories'] = originalMethod; + } + }); + + it('should load both toml and markdown commands', async () => { + // Create both TOML and Markdown files + const tomlContent = `prompt = "TOML prompt" +description = "TOML command"`; + + const mdContent = `--- +description: Markdown command +--- + +Markdown prompt`; + + await fs.writeFile( + path.join(tempDir, 'toml-cmd.toml'), + tomlContent, + 'utf-8', + ); + await fs.writeFile(path.join(tempDir, 'md-cmd.md'), mdContent, 'utf-8'); + + const loader = new FileCommandLoader(null); + const originalMethod = loader['getCommandDirectories']; + loader['getCommandDirectories'] = () => [{ path: tempDir }]; + + try { + const commands = await loader.loadCommands(new AbortController().signal); + + const tomlCommand = commands.find((cmd) => cmd.name === 'toml-cmd'); + const mdCommand = commands.find((cmd) => cmd.name === 'md-cmd'); + + expect(tomlCommand).toBeDefined(); + expect(tomlCommand?.description).toBe('TOML command'); + + expect(mdCommand).toBeDefined(); + expect(mdCommand?.description).toBe('Markdown command'); + } finally { + loader['getCommandDirectories'] = originalMethod; + } + }); +}); diff --git a/packages/cli/src/services/FileCommandLoader.test.ts b/packages/cli/src/services/FileCommandLoader.test.ts index 50c85e66f25..e9c49127440 100644 --- a/packages/cli/src/services/FileCommandLoader.test.ts +++ b/packages/cli/src/services/FileCommandLoader.test.ts @@ -568,9 +568,9 @@ describe('FileCommandLoader', () => { expect(commands).toHaveLength(3); const commandNames = commands.map((cmd) => cmd.name); - expect(commandNames).toEqual(['user', 'project', 'ext']); + expect(commandNames).toEqual(['user', 'project', 'test-ext:ext']); - const extCommand = commands.find((cmd) => cmd.name === 'ext'); + const extCommand = commands.find((cmd) => cmd.name === 'test-ext:ext'); expect(extCommand?.extensionName).toBe('test-ext'); expect(extCommand?.description).toMatch(/^\[test-ext\]/); }); @@ -656,14 +656,14 @@ describe('FileCommandLoader', () => { expect(result1.content).toEqual([{ text: 'Project deploy command' }]); } - expect(commands[2].name).toBe('deploy'); + expect(commands[2].name).toBe('test-ext:deploy'); expect(commands[2].extensionName).toBe('test-ext'); expect(commands[2].description).toMatch(/^\[test-ext\]/); const result2 = await commands[2].action?.( createMockCommandContext({ invocation: { - raw: '/deploy', - name: 'deploy', + raw: '/test-ext:deploy', + name: 'test-ext:deploy', args: '', }, }), @@ -729,7 +729,7 @@ describe('FileCommandLoader', () => { const commands = await loader.loadCommands(signal); expect(commands).toHaveLength(1); - expect(commands[0].name).toBe('active'); + expect(commands[0].name).toBe('active-ext:active'); expect(commands[0].extensionName).toBe('active-ext'); expect(commands[0].description).toMatch(/^\[active-ext\]/); }); @@ -803,17 +803,17 @@ describe('FileCommandLoader', () => { expect(commands).toHaveLength(3); const commandNames = commands.map((cmd) => cmd.name).sort(); - expect(commandNames).toEqual(['b:c', 'b:d:e', 'simple']); + expect(commandNames).toEqual(['a:b:c', 'a:b:d:e', 'a:simple']); - const nestedCmd = commands.find((cmd) => cmd.name === 'b:c'); + const nestedCmd = commands.find((cmd) => cmd.name === 'a:b:c'); expect(nestedCmd?.extensionName).toBe('a'); expect(nestedCmd?.description).toMatch(/^\[a\]/); expect(nestedCmd).toBeDefined(); const result = await nestedCmd!.action?.( createMockCommandContext({ invocation: { - raw: '/b:c', - name: 'b:c', + raw: '/a:b:c', + name: 'a:b:c', args: '', }, }), diff --git a/packages/cli/src/services/FileCommandLoader.ts b/packages/cli/src/services/FileCommandLoader.ts index 5527aa809cb..38ae44ab196 100644 --- a/packages/cli/src/services/FileCommandLoader.ts +++ b/packages/cli/src/services/FileCommandLoader.ts @@ -5,6 +5,7 @@ */ import { promises as fs } from 'node:fs'; +import * as fsSync from 'node:fs'; import path from 'node:path'; import toml from '@iarna/toml'; import { glob } from 'glob'; @@ -12,27 +13,16 @@ import { z } from 'zod'; import type { Config } from '@qwen-code/qwen-code-core'; import { Storage } from '@qwen-code/qwen-code-core'; import type { ICommandLoader } from './types.js'; -import type { - CommandContext, - SlashCommand, - SlashCommandActionReturn, -} from '../ui/commands/types.js'; -import { CommandKind } from '../ui/commands/types.js'; -import { DefaultArgumentProcessor } from './prompt-processors/argumentProcessor.js'; -import type { - IPromptProcessor, - PromptPipelineContent, -} from './prompt-processors/types.js'; import { - SHORTHAND_ARGS_PLACEHOLDER, - SHELL_INJECTION_TRIGGER, - AT_FILE_INJECTION_TRIGGER, -} from './prompt-processors/types.js'; + parseMarkdownCommand, + MarkdownCommandDefSchema, +} from './markdown-command-parser.js'; import { - ConfirmationRequiredError, - ShellProcessor, -} from './prompt-processors/shellProcessor.js'; -import { AtFileProcessor } from './prompt-processors/atFileProcessor.js'; + createSlashCommandFromDefinition, + type CommandDefinition, +} from './command-factory.js'; +import type { SlashCommand } from '../ui/commands/types.js'; +import { EXTENSIONS_CONFIG_FILENAME } from '../config/extension.js'; interface CommandDirectory { path: string; @@ -96,7 +86,12 @@ export class FileCommandLoader implements ICommandLoader { const commandDirs = this.getCommandDirectories(); for (const dirInfo of commandDirs) { try { - const files = await glob('**/*.toml', { + // Scan both .toml and .md files + const tomlFiles = await glob('**/*.toml', { + ...globOptions, + cwd: dirInfo.path, + }); + const mdFiles = await glob('**/*.md', { ...globOptions, cwd: dirInfo.path, }); @@ -105,18 +100,28 @@ export class FileCommandLoader implements ICommandLoader { return []; } - const commandPromises = files.map((file) => - this.parseAndAdaptFile( + // Process TOML files + const tomlCommandPromises = tomlFiles.map((file) => + this.parseAndAdaptTomlFile( path.join(dirInfo.path, file), dirInfo.path, dirInfo.extensionName, ), ); - const commands = (await Promise.all(commandPromises)).filter( - (cmd): cmd is SlashCommand => cmd !== null, + // Process Markdown files + const mdCommandPromises = mdFiles.map((file) => + this.parseAndAdaptMarkdownFile( + path.join(dirInfo.path, file), + dirInfo.path, + dirInfo.extensionName, + ), ); + const commands = ( + await Promise.all([...tomlCommandPromises, ...mdCommandPromises]) + ).filter((cmd): cmd is SlashCommand => cmd !== null); + // Add all commands without deduplication allCommands.push(...commands); } catch (error) { @@ -159,17 +164,73 @@ export class FileCommandLoader implements ICommandLoader { .filter((ext) => ext.isActive) .sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically for deterministic loading - const extensionCommandDirs = activeExtensions.map((ext) => ({ - path: path.join(ext.path, 'commands'), - extensionName: ext.name, - })); + // Collect command directories from each extension + for (const ext of activeExtensions) { + // Get commands paths from extension config + const commandsPaths = this.getExtensionCommandsPaths(ext); - dirs.push(...extensionCommandDirs); + for (const cmdPath of commandsPaths) { + dirs.push({ + path: cmdPath, + extensionName: ext.name, + }); + } + } } return dirs; } + /** + * Get commands paths from an extension. + * Returns paths from config.commands if specified, otherwise defaults to 'commands' directory. + */ + private getExtensionCommandsPaths(ext: { + path: string; + name: string; + }): string[] { + // Try to get extension config + try { + const configPath = path.join(ext.path, EXTENSIONS_CONFIG_FILENAME); + if (fsSync.existsSync(configPath)) { + const configContent = fsSync.readFileSync(configPath, 'utf-8'); + const config = JSON.parse(configContent); + + if (config.commands) { + const commandsArray = Array.isArray(config.commands) + ? config.commands + : [config.commands]; + + return commandsArray + .map((cmdPath: string) => + path.isAbsolute(cmdPath) ? cmdPath : path.join(ext.path, cmdPath), + ) + .filter((cmdPath: string) => { + try { + return fsSync.existsSync(cmdPath); + } catch { + return false; + } + }); + } + } + } catch (error) { + console.warn(`Failed to read extension config for ${ext.name}:`, error); + } + + // Default fallback: use 'commands' directory + const defaultPath = path.join(ext.path, 'commands'); + try { + if (fsSync.existsSync(defaultPath)) { + return [defaultPath]; + } + } catch { + // Ignore + } + + return []; + } + /** * Parses a single .toml file and transforms it into a SlashCommand object. * @param filePath The absolute path to the .toml file. @@ -177,7 +238,7 @@ export class FileCommandLoader implements ICommandLoader { * @param extensionName Optional extension name to prefix commands with. * @returns A promise resolving to a SlashCommand, or null if the file is invalid. */ - private async parseAndAdaptFile( + private async parseAndAdaptTomlFile( filePath: string, baseDir: string, extensionName?: string, @@ -216,104 +277,79 @@ export class FileCommandLoader implements ICommandLoader { const validDef = validationResult.data; - const relativePathWithExt = path.relative(baseDir, filePath); - const relativePath = relativePathWithExt.substring( - 0, - relativePathWithExt.length - 5, // length of '.toml' - ); - const baseCommandName = relativePath - .split(path.sep) - // Sanitize each path segment to prevent ambiguity. Since ':' is our - // namespace separator, we replace any literal colons in filenames - // with underscores to avoid naming conflicts. - .map((segment) => segment.replaceAll(':', '_')) - .join(':'); - - // Add extension name tag for extension commands - const defaultDescription = `Custom command from ${path.basename(filePath)}`; - let description = validDef.description || defaultDescription; - if (extensionName) { - description = `[${extensionName}] ${description}`; - } - - const processors: IPromptProcessor[] = []; - const usesArgs = validDef.prompt.includes(SHORTHAND_ARGS_PLACEHOLDER); - const usesShellInjection = validDef.prompt.includes( - SHELL_INJECTION_TRIGGER, - ); - const usesAtFileInjection = validDef.prompt.includes( - AT_FILE_INJECTION_TRIGGER, + // Use factory to create command + return createSlashCommandFromDefinition( + filePath, + baseDir, + validDef, + extensionName, + '.toml', ); + } - // 1. @-File Injection (Security First). - // This runs first to ensure we're not executing shell commands that - // could dynamically generate malicious @-paths. - if (usesAtFileInjection) { - processors.push(new AtFileProcessor(baseCommandName)); + /** + * Parses a single .md file and transforms it into a SlashCommand object. + * @param filePath The absolute path to the .md file. + * @param baseDir The root command directory for name calculation. + * @param extensionName Optional extension name to prefix commands with. + * @returns A promise resolving to a SlashCommand, or null if the file is invalid. + */ + private async parseAndAdaptMarkdownFile( + filePath: string, + baseDir: string, + extensionName?: string, + ): Promise { + let fileContent: string; + try { + fileContent = await fs.readFile(filePath, 'utf-8'); + } catch (error: unknown) { + console.error( + `[FileCommandLoader] Failed to read file ${filePath}:`, + error instanceof Error ? error.message : String(error), + ); + return null; } - // 2. Argument and Shell Injection. - // This runs after file content has been safely injected. - if (usesShellInjection || usesArgs) { - processors.push(new ShellProcessor(baseCommandName)); + let parsed: ReturnType; + try { + parsed = parseMarkdownCommand(fileContent); + } catch (error: unknown) { + console.error( + `[FileCommandLoader] Failed to parse Markdown file ${filePath}:`, + error instanceof Error ? error.message : String(error), + ); + return null; } - // 3. Default Argument Handling. - // Appends the raw invocation if no explicit {{args}} are used. - if (!usesArgs) { - processors.push(new DefaultArgumentProcessor()); + const validationResult = MarkdownCommandDefSchema.safeParse(parsed); + + if (!validationResult.success) { + console.error( + `[FileCommandLoader] Skipping invalid command file: ${filePath}. Validation errors:`, + validationResult.error.flatten(), + ); + return null; } - return { - name: baseCommandName, - description, - kind: CommandKind.FILE, - extensionName, - action: async ( - context: CommandContext, - _args: string, - ): Promise => { - if (!context.invocation) { - console.error( - `[FileCommandLoader] Critical error: Command '${baseCommandName}' was executed without invocation context.`, - ); - return { - type: 'submit_prompt', - content: [{ text: validDef.prompt }], // Fallback to unprocessed prompt - }; - } + const validDef = validationResult.data; - try { - let processedContent: PromptPipelineContent = [ - { text: validDef.prompt }, - ]; - for (const processor of processors) { - processedContent = await processor.process( - processedContent, - context, - ); - } - - return { - type: 'submit_prompt', - content: processedContent, - }; - } catch (e) { - // Check if it's our specific error type - if (e instanceof ConfirmationRequiredError) { - // Halt and request confirmation from the UI layer. - return { - type: 'confirm_shell_commands', - commandsToConfirm: e.commandsToConfirm, - originalInvocation: { - raw: context.invocation.raw, - }, - }; - } - // Re-throw other errors to be handled by the global error handler. - throw e; - } - }, + // Convert to CommandDefinition format + const definition: CommandDefinition = { + prompt: validDef.prompt, + description: + validDef.frontmatter?.description && + typeof validDef.frontmatter.description === 'string' + ? validDef.frontmatter.description + : undefined, }; + + // Use factory to create command + return createSlashCommandFromDefinition( + filePath, + baseDir, + definition, + extensionName, + '.md', + ); } } diff --git a/packages/cli/src/services/command-factory.ts b/packages/cli/src/services/command-factory.ts new file mode 100644 index 00000000000..fbe2da5c50f --- /dev/null +++ b/packages/cli/src/services/command-factory.ts @@ -0,0 +1,159 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * This file contains helper functions for FileCommandLoader to create SlashCommand + * objects from parsed command definitions (TOML or Markdown). + */ + +import path from 'node:path'; +import type { + CommandContext, + SlashCommand, + SlashCommandActionReturn, +} from '../ui/commands/types.js'; +import { CommandKind } from '../ui/commands/types.js'; +import { DefaultArgumentProcessor } from './prompt-processors/argumentProcessor.js'; +import type { + IPromptProcessor, + PromptPipelineContent, +} from './prompt-processors/types.js'; +import { + SHORTHAND_ARGS_PLACEHOLDER, + SHELL_INJECTION_TRIGGER, + AT_FILE_INJECTION_TRIGGER, +} from './prompt-processors/types.js'; +import { + ConfirmationRequiredError, + ShellProcessor, +} from './prompt-processors/shellProcessor.js'; +import { AtFileProcessor } from './prompt-processors/atFileProcessor.js'; + +export interface CommandDefinition { + prompt: string; + description?: string; +} + +/** + * Creates a SlashCommand from a parsed command definition. + * This function is used by both TOML and Markdown command loaders. + * + * @param filePath The absolute path to the command file + * @param baseDir The root command directory for name calculation + * @param definition The parsed command definition (prompt and optional description) + * @param extensionName Optional extension name to prefix commands with + * @param fileExtension The file extension (e.g., '.toml' or '.md') + * @returns A SlashCommand object + */ +export function createSlashCommandFromDefinition( + filePath: string, + baseDir: string, + definition: CommandDefinition, + extensionName: string | undefined, + fileExtension: string, +): SlashCommand { + const relativePathWithExt = path.relative(baseDir, filePath); + const relativePath = relativePathWithExt.substring( + 0, + relativePathWithExt.length - fileExtension.length, + ); + const baseCommandName = relativePath + .split(path.sep) + // Sanitize each path segment to prevent ambiguity. Since ':' is our + // namespace separator, we replace any literal colons in filenames + // with underscores to avoid naming conflicts. + .map((segment) => segment.replaceAll(':', '_')) + .join(':'); + + // Prefix command name with extension name if provided + const commandName = extensionName + ? `${extensionName}:${baseCommandName}` + : baseCommandName; + + // Add extension name tag for extension commands + const defaultDescription = `Custom command from ${path.basename(filePath)}`; + let description = definition.description || defaultDescription; + if (extensionName) { + description = `[${extensionName}] ${description}`; + } + + const processors: IPromptProcessor[] = []; + const usesArgs = definition.prompt.includes(SHORTHAND_ARGS_PLACEHOLDER); + const usesShellInjection = definition.prompt.includes( + SHELL_INJECTION_TRIGGER, + ); + const usesAtFileInjection = definition.prompt.includes( + AT_FILE_INJECTION_TRIGGER, + ); + + // 1. @-File Injection (Security First). + // This runs first to ensure we're not executing shell commands that + // could dynamically generate malicious @-paths. + if (usesAtFileInjection) { + processors.push(new AtFileProcessor(baseCommandName)); + } + + // 2. Argument and Shell Injection. + // This runs after file content has been safely injected. + if (usesShellInjection || usesArgs) { + processors.push(new ShellProcessor(baseCommandName)); + } + + // 3. Default Argument Handling. + // Appends the raw invocation if no explicit {{args}} are used. + if (!usesArgs) { + processors.push(new DefaultArgumentProcessor()); + } + + return { + name: commandName, + description, + kind: CommandKind.FILE, + extensionName, + action: async ( + context: CommandContext, + _args: string, + ): Promise => { + if (!context.invocation) { + console.error( + `[FileCommandLoader] Critical error: Command '${commandName}' was executed without invocation context.`, + ); + return { + type: 'submit_prompt', + content: [{ text: definition.prompt }], // Fallback to unprocessed prompt + }; + } + + try { + let processedContent: PromptPipelineContent = [ + { text: definition.prompt }, + ]; + for (const processor of processors) { + processedContent = await processor.process(processedContent, context); + } + + return { + type: 'submit_prompt', + content: processedContent, + }; + } catch (e) { + // Check if it's our specific error type + if (e instanceof ConfirmationRequiredError) { + // Halt and request confirmation from the UI layer. + return { + type: 'confirm_shell_commands', + commandsToConfirm: e.commandsToConfirm, + originalInvocation: { + raw: context.invocation.raw, + }, + }; + } + // Re-throw other errors to be handled by the global error handler. + throw e; + } + }, + }; +} diff --git a/packages/cli/src/services/command-migration-tool.test.ts b/packages/cli/src/services/command-migration-tool.test.ts new file mode 100644 index 00000000000..de459d746a9 --- /dev/null +++ b/packages/cli/src/services/command-migration-tool.test.ts @@ -0,0 +1,226 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { + detectTomlCommands, + migrateTomlCommands, + generateMigrationPrompt, +} from './command-migration-tool.js'; + +describe('command-migration-tool', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-migration-test-')); + }); + + afterEach(async () => { + await fs.rm(tempDir, { recursive: true, force: true }); + }); + + describe('detectTomlCommands', () => { + it('should detect TOML files in directory', async () => { + // Create some TOML files + await fs.writeFile( + path.join(tempDir, 'cmd1.toml'), + 'prompt = "test"', + 'utf-8', + ); + await fs.writeFile( + path.join(tempDir, 'cmd2.toml'), + 'prompt = "test"', + 'utf-8', + ); + + const tomlFiles = await detectTomlCommands(tempDir); + + expect(tomlFiles).toHaveLength(2); + expect(tomlFiles).toContain('cmd1.toml'); + expect(tomlFiles).toContain('cmd2.toml'); + }); + + it('should detect TOML files in subdirectories', async () => { + const subdir = path.join(tempDir, 'subdir'); + await fs.mkdir(subdir); + await fs.writeFile( + path.join(subdir, 'nested.toml'), + 'prompt = "test"', + 'utf-8', + ); + + const tomlFiles = await detectTomlCommands(tempDir); + + expect(tomlFiles).toContain('subdir/nested.toml'); + }); + + it('should return empty array for non-existent directory', async () => { + const nonExistent = path.join(tempDir, 'does-not-exist'); + + const tomlFiles = await detectTomlCommands(nonExistent); + + expect(tomlFiles).toEqual([]); + }); + + it('should not detect non-TOML files', async () => { + await fs.writeFile(path.join(tempDir, 'file.txt'), 'text', 'utf-8'); + await fs.writeFile(path.join(tempDir, 'file.md'), 'markdown', 'utf-8'); + + const tomlFiles = await detectTomlCommands(tempDir); + + expect(tomlFiles).toHaveLength(0); + }); + }); + + describe('migrateTomlCommands', () => { + it('should migrate TOML file to Markdown', async () => { + const tomlContent = `prompt = "Test prompt" +description = "Test description"`; + + await fs.writeFile(path.join(tempDir, 'test.toml'), tomlContent, 'utf-8'); + + const result = await migrateTomlCommands({ + commandDir: tempDir, + createBackup: true, + deleteOriginal: false, + }); + + expect(result.success).toBe(true); + expect(result.convertedFiles).toContain('test.toml'); + expect(result.failedFiles).toHaveLength(0); + + // Check Markdown file was created + const mdPath = path.join(tempDir, 'test.md'); + const mdContent = await fs.readFile(mdPath, 'utf-8'); + expect(mdContent).toContain('description: Test description'); + expect(mdContent).toContain('Test prompt'); + + // Check backup was created + expect(result.backupDir).toBeDefined(); + const backupPath = path.join(result.backupDir!, 'test.toml'); + const backupExists = await fs + .access(backupPath) + .then(() => true) + .catch(() => false); + expect(backupExists).toBe(true); + }); + + it('should delete original TOML when deleteOriginal is true', async () => { + await fs.writeFile( + path.join(tempDir, 'delete-me.toml'), + 'prompt = "Test"', + 'utf-8', + ); + + await migrateTomlCommands({ + commandDir: tempDir, + createBackup: true, + deleteOriginal: true, + }); + + // Original should be deleted + const tomlExists = await fs + .access(path.join(tempDir, 'delete-me.toml')) + .then(() => true) + .catch(() => false); + expect(tomlExists).toBe(false); + + // Markdown should exist + const mdExists = await fs + .access(path.join(tempDir, 'delete-me.md')) + .then(() => true) + .catch(() => false); + expect(mdExists).toBe(true); + }); + + it('should fail if Markdown file already exists', async () => { + await fs.writeFile( + path.join(tempDir, 'existing.toml'), + 'prompt = "Test"', + 'utf-8', + ); + await fs.writeFile( + path.join(tempDir, 'existing.md'), + 'Already exists', + 'utf-8', + ); + + const result = await migrateTomlCommands({ + commandDir: tempDir, + createBackup: false, + }); + + expect(result.success).toBe(false); + expect(result.failedFiles).toHaveLength(1); + expect(result.failedFiles[0].file).toBe('existing.toml'); + expect(result.failedFiles[0].error).toContain('already exists'); + }); + + it('should handle migration without backup', async () => { + await fs.writeFile( + path.join(tempDir, 'no-backup.toml'), + 'prompt = "Test"', + 'utf-8', + ); + + const result = await migrateTomlCommands({ + commandDir: tempDir, + createBackup: false, + }); + + expect(result.success).toBe(true); + expect(result.backupDir).toBeUndefined(); + }); + + it('should return success with empty results for no TOML files', async () => { + const result = await migrateTomlCommands({ + commandDir: tempDir, + }); + + expect(result.success).toBe(true); + expect(result.convertedFiles).toHaveLength(0); + expect(result.failedFiles).toHaveLength(0); + }); + }); + + describe('generateMigrationPrompt', () => { + it('should generate prompt for few files', () => { + const files = ['cmd1.toml', 'cmd2.toml']; + + const prompt = generateMigrationPrompt(files); + + expect(prompt).toContain('Found 2 command files'); + expect(prompt).toContain('cmd1.toml'); + expect(prompt).toContain('cmd2.toml'); + expect(prompt).toContain('qwen-code migrate-commands'); + }); + + it('should truncate file list for many files', () => { + const files = Array.from({ length: 10 }, (_, i) => `cmd${i}.toml`); + + const prompt = generateMigrationPrompt(files); + + expect(prompt).toContain('Found 10 command files'); + expect(prompt).toContain('... and 7 more'); + }); + + it('should return empty string for no files', () => { + const prompt = generateMigrationPrompt([]); + + expect(prompt).toBe(''); + }); + + it('should use singular form for single file', () => { + const prompt = generateMigrationPrompt(['single.toml']); + + expect(prompt).toContain('Found 1 command file'); + // Don't check for plural since "files" appears in other parts of the message + }); + }); +}); diff --git a/packages/cli/src/services/command-migration-tool.ts b/packages/cli/src/services/command-migration-tool.ts new file mode 100644 index 00000000000..7ff68ebabd3 --- /dev/null +++ b/packages/cli/src/services/command-migration-tool.ts @@ -0,0 +1,189 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Tool for migrating TOML commands to Markdown format. + */ + +import { promises as fs } from 'node:fs'; +import path from 'node:path'; +import { glob } from 'glob'; +import { convertTomlToMarkdown } from './toml-to-markdown-converter.js'; + +export interface MigrationResult { + success: boolean; + convertedFiles: string[]; + failedFiles: Array<{ file: string; error: string }>; + backupDir?: string; +} + +export interface MigrationOptions { + /** Directory containing command files */ + commandDir: string; + /** Whether to create backups (default: true) */ + createBackup?: boolean; + /** Whether to delete original TOML files after migration (default: false) */ + deleteOriginal?: boolean; + /** Backup directory suffix (default: '.backup') */ + backupSuffix?: string; +} + +/** + * Scans a directory for TOML command files. + * @param commandDir Directory to scan + * @returns Array of TOML file paths (relative to commandDir) + */ +export async function detectTomlCommands( + commandDir: string, +): Promise { + try { + await fs.access(commandDir); + } catch { + // Directory doesn't exist + return []; + } + + const tomlFiles = await glob('**/*.toml', { + cwd: commandDir, + nodir: true, + dot: false, + }); + + return tomlFiles; +} + +/** + * Migrates TOML command files to Markdown format. + * @param options Migration options + * @returns Migration result with details + */ +export async function migrateTomlCommands( + options: MigrationOptions, +): Promise { + const { + commandDir, + createBackup = true, + deleteOriginal = false, + backupSuffix = '.backup', + } = options; + + const result: MigrationResult = { + success: true, + convertedFiles: [], + failedFiles: [], + }; + + // Detect TOML files + const tomlFiles = await detectTomlCommands(commandDir); + + if (tomlFiles.length === 0) { + return result; + } + + // Create backup directory if needed + let backupDir: string | undefined; + if (createBackup) { + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + backupDir = path.join(commandDir, `${backupSuffix}-${timestamp}`); + await fs.mkdir(backupDir, { recursive: true }); + result.backupDir = backupDir; + } + + // Process each TOML file + for (const relativeFile of tomlFiles) { + const tomlPath = path.join(commandDir, relativeFile); + + try { + // Read TOML file + const tomlContent = await fs.readFile(tomlPath, 'utf-8'); + + // Convert to Markdown + const markdownContent = convertTomlToMarkdown(tomlContent); + + // Generate Markdown file path (same location, .md extension) + const markdownPath = tomlPath.replace(/\.toml$/, '.md'); + + // Check if Markdown file already exists + try { + await fs.access(markdownPath); + throw new Error( + `Markdown file already exists: ${path.basename(markdownPath)}`, + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + // File doesn't exist, continue + } + + // Write Markdown file + await fs.writeFile(markdownPath, markdownContent, 'utf-8'); + + // Backup original if requested + if (backupDir) { + const backupPath = path.join(backupDir, relativeFile); + await fs.mkdir(path.dirname(backupPath), { recursive: true }); + await fs.copyFile(tomlPath, backupPath); + } + + // Delete original if requested + if (deleteOriginal) { + await fs.unlink(tomlPath); + } + + result.convertedFiles.push(relativeFile); + } catch (error) { + result.success = false; + result.failedFiles.push({ + file: relativeFile, + error: error instanceof Error ? error.message : String(error), + }); + } + } + + return result; +} + +/** + * Generates a migration report message. + * @param tomlFiles List of TOML files found + * @returns Human-readable migration prompt message + */ +export function generateMigrationPrompt(tomlFiles: string[]): string { + if (tomlFiles.length === 0) { + return ''; + } + + const count = tomlFiles.length; + const fileList = + tomlFiles.length <= 5 + ? tomlFiles.map((f) => ` - ${f}`).join('\n') + : ` - ${tomlFiles.slice(0, 3).join('\n - ')}\n - ... and ${tomlFiles.length - 3} more`; + + return ` +⚠️ TOML Command Format Deprecation Notice + +Found ${count} command file${count > 1 ? 's' : ''} in TOML format: +${fileList} + +The TOML format for commands is being deprecated in favor of Markdown format. +Markdown format is more readable and easier to edit. + +You can migrate these files automatically using: + qwen-code migrate-commands + +Or manually convert each file: + - TOML: prompt = "..." / description = "..." + - Markdown: YAML frontmatter + content + +The migration tool will: + ✓ Convert TOML files to Markdown + ✓ Create backups of original files + ✓ Preserve all command functionality + +TOML format will continue to work for now, but migration is recommended. +`.trim(); +} diff --git a/packages/cli/src/services/markdown-command-parser.test.ts b/packages/cli/src/services/markdown-command-parser.test.ts new file mode 100644 index 00000000000..4de35f0ea8f --- /dev/null +++ b/packages/cli/src/services/markdown-command-parser.test.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { + parseMarkdownCommand, + MarkdownCommandDefSchema, +} from './markdown-command-parser.js'; + +describe('parseMarkdownCommand', () => { + it('should parse markdown with YAML frontmatter', () => { + const content = `--- +description: Test command +--- + +This is the prompt content.`; + + const result = parseMarkdownCommand(content); + + expect(result).toEqual({ + frontmatter: { + description: 'Test command', + }, + prompt: 'This is the prompt content.', + }); + }); + + it('should parse markdown without frontmatter', () => { + const content = 'This is just a prompt without frontmatter.'; + + const result = parseMarkdownCommand(content); + + expect(result).toEqual({ + prompt: 'This is just a prompt without frontmatter.', + }); + }); + + it('should handle multi-line prompts', () => { + const content = `--- +description: Multi-line test +--- + +First line of prompt. +Second line of prompt. +Third line of prompt.`; + + const result = parseMarkdownCommand(content); + + expect(result.prompt).toBe( + 'First line of prompt.\nSecond line of prompt.\nThird line of prompt.', + ); + }); + + it('should trim whitespace from prompt', () => { + const content = `--- +description: Whitespace test +--- + + Prompt with leading and trailing spaces +`; + + const result = parseMarkdownCommand(content); + + expect(result.prompt).toBe('Prompt with leading and trailing spaces'); + }); + + it('should handle empty frontmatter', () => { + const content = `--- +--- + +Prompt content after empty frontmatter.`; + + const result = parseMarkdownCommand(content); + + // Empty YAML frontmatter returns undefined, not {} + expect(result.frontmatter).toBeUndefined(); + expect(result.prompt).toBe('Prompt content after empty frontmatter.'); + }); + + it('should handle invalid YAML frontmatter gracefully', () => { + // The YAML parser we use is quite tolerant, so most "invalid" YAML + // actually parses successfully. This test verifies that behavior. + const content = `--- +description: test +--- + +Prompt content.`; + + const result = parseMarkdownCommand(content); + + expect(result.frontmatter).toBeDefined(); + expect(result.prompt).toBe('Prompt content.'); + }); +}); + +describe('MarkdownCommandDefSchema', () => { + it('should validate valid markdown command def', () => { + const validDef = { + frontmatter: { + description: 'Test description', + }, + prompt: 'Test prompt', + }; + + const result = MarkdownCommandDefSchema.safeParse(validDef); + + expect(result.success).toBe(true); + }); + + it('should validate markdown command def without frontmatter', () => { + const validDef = { + prompt: 'Test prompt', + }; + + const result = MarkdownCommandDefSchema.safeParse(validDef); + + expect(result.success).toBe(true); + }); + + it('should reject command def without prompt', () => { + const invalidDef = { + frontmatter: { + description: 'Test description', + }, + }; + + const result = MarkdownCommandDefSchema.safeParse(invalidDef); + + expect(result.success).toBe(false); + }); + + it('should reject command def with non-string prompt', () => { + const invalidDef = { + prompt: 123, + }; + + const result = MarkdownCommandDefSchema.safeParse(invalidDef); + + expect(result.success).toBe(false); + }); +}); diff --git a/packages/cli/src/services/markdown-command-parser.ts b/packages/cli/src/services/markdown-command-parser.ts new file mode 100644 index 00000000000..92e0d9573af --- /dev/null +++ b/packages/cli/src/services/markdown-command-parser.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { z } from 'zod'; +import { parse as parseYaml } from '@qwen-code/qwen-code-core/src/utils/yaml-parser.js'; + +/** + * Defines the Zod schema for a Markdown command definition file. + * The frontmatter contains optional metadata, and the body is the prompt. + */ +export const MarkdownCommandDefSchema = z.object({ + frontmatter: z + .object({ + description: z.string().optional(), + }) + .optional(), + prompt: z.string({ + required_error: 'The prompt content is required.', + invalid_type_error: 'The prompt content must be a string.', + }), +}); + +export type MarkdownCommandDef = z.infer; + +/** + * Parses a Markdown command file with optional YAML frontmatter. + * @param content The file content + * @returns Parsed command definition with frontmatter and prompt + */ +export function parseMarkdownCommand(content: string): MarkdownCommandDef { + // Match YAML frontmatter pattern: ---\n...\n---\n + // Allow empty frontmatter: ---\n---\n // Use (?:[\s\S]*?) to make the frontmatter content optional + const frontmatterRegex = /^---\n([\s\S]*?)---\n([\s\S]*)$/; + const match = content.match(frontmatterRegex); + + if (!match) { + // No frontmatter, entire content is the prompt + return { + prompt: content.trim(), + }; + } + + const [, frontmatterYaml, body] = match; + + // Parse YAML frontmatter if not empty + let frontmatter: Record | undefined; + if (frontmatterYaml.trim()) { + try { + frontmatter = parseYaml(frontmatterYaml) as Record; + } catch (error) { + throw new Error( + `Failed to parse YAML frontmatter: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + return { + frontmatter, + prompt: body.trim(), + }; +} diff --git a/packages/cli/src/services/test-commands/example.md b/packages/cli/src/services/test-commands/example.md new file mode 100644 index 00000000000..c876a670029 --- /dev/null +++ b/packages/cli/src/services/test-commands/example.md @@ -0,0 +1,5 @@ +--- +description: Example markdown command +--- + +This is an example prompt from a markdown file. diff --git a/packages/cli/src/services/toml-to-markdown-converter.test.ts b/packages/cli/src/services/toml-to-markdown-converter.test.ts new file mode 100644 index 00000000000..8adc811f921 --- /dev/null +++ b/packages/cli/src/services/toml-to-markdown-converter.test.ts @@ -0,0 +1,103 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { + convertTomlToMarkdown, + isTomlFormat, +} from './toml-to-markdown-converter.js'; + +describe('convertTomlToMarkdown', () => { + it('should convert TOML with description to Markdown', () => { + const tomlContent = `prompt = "This is a test prompt" +description = "Test command"`; + + const result = convertTomlToMarkdown(tomlContent); + + expect(result).toBe(`--- +description: Test command +--- + +This is a test prompt +`); + }); + + it('should convert TOML without description to Markdown', () => { + const tomlContent = `prompt = "Simple prompt"`; + + const result = convertTomlToMarkdown(tomlContent); + + expect(result).toBe('Simple prompt\n'); + }); + + it('should handle multi-line prompts', () => { + const tomlContent = `prompt = """ +This is a multi-line +prompt with several +lines of text. +""" +description = "Multi-line test"`; + + const result = convertTomlToMarkdown(tomlContent); + + expect(result).toContain('This is a multi-line'); + expect(result).toContain('description: Multi-line test'); + }); + + it('should throw error for invalid TOML', () => { + const invalidToml = 'this is not valid toml {[}]'; + + expect(() => convertTomlToMarkdown(invalidToml)).toThrow( + 'Failed to parse TOML', + ); + }); + + it('should throw error if prompt field is missing', () => { + const tomlWithoutPrompt = 'description = "No prompt here"'; + + expect(() => convertTomlToMarkdown(tomlWithoutPrompt)).toThrow( + 'TOML must contain a "prompt" field', + ); + }); + + it('should handle special characters in description', () => { + const tomlContent = `prompt = "Test prompt" +description = "Command with: special, characters!"`; + + const result = convertTomlToMarkdown(tomlContent); + + expect(result).toContain('description: Command with: special, characters!'); + }); +}); + +describe('isTomlFormat', () => { + it('should return true for valid TOML', () => { + const validToml = `prompt = "Test" +description = "Description"`; + + expect(isTomlFormat(validToml)).toBe(true); + }); + + it('should return false for invalid TOML', () => { + const invalidToml = '{ this is not toml }'; + + expect(isTomlFormat(invalidToml)).toBe(false); + }); + + it('should return true for empty TOML', () => { + expect(isTomlFormat('')).toBe(true); + }); + + it('should return false for Markdown format', () => { + const markdown = `--- +description: Test +--- + +Prompt content`; + + expect(isTomlFormat(markdown)).toBe(false); + }); +}); diff --git a/packages/cli/src/services/toml-to-markdown-converter.ts b/packages/cli/src/services/toml-to-markdown-converter.ts new file mode 100644 index 00000000000..92f7778c068 --- /dev/null +++ b/packages/cli/src/services/toml-to-markdown-converter.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Converts TOML command files to Markdown format. + */ + +import toml from '@iarna/toml'; + +export interface TomlCommandFormat { + prompt: string; + description?: string; +} + +/** + * Converts a TOML command content to Markdown format. + * @param tomlContent The TOML file content + * @returns The equivalent Markdown content + * @throws Error if TOML parsing fails + */ +export function convertTomlToMarkdown(tomlContent: string): string { + let parsed: unknown; + try { + parsed = toml.parse(tomlContent); + } catch (error) { + throw new Error( + `Failed to parse TOML: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + if (typeof parsed !== 'object' || parsed === null) { + throw new Error('TOML content must be an object'); + } + + const obj = parsed as Record; + + if (typeof obj['prompt'] !== 'string') { + throw new Error('TOML must contain a "prompt" field'); + } + + const prompt = obj['prompt']; + const description = + typeof obj['description'] === 'string' ? obj['description'] : undefined; + + // Generate Markdown + if (description) { + return `--- +description: ${description} +--- + +${prompt} +`; + } else { + // No frontmatter if no description + return `${prompt}\n`; + } +} + +/** + * Checks if a file content is in TOML format by attempting to parse it. + * @param content File content to check + * @returns true if content is valid TOML + */ +export function isTomlFormat(content: string): boolean { + try { + toml.parse(content); + return true; + } catch { + return false; + } +} diff --git a/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx b/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx index add3dcb5861..a3a0c9af419 100644 --- a/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx +++ b/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx @@ -218,7 +218,7 @@ export const AgentSelectionStep = ({ const renderAgentItem = ( agent: { name: string; - level: 'project' | 'user' | 'builtin' | 'session'; + level: 'project' | 'user' | 'builtin' | 'session' | 'extension'; isBuiltin?: boolean; }, index: number, diff --git a/packages/cli/src/ui/hooks/useTomlMigration.ts b/packages/cli/src/ui/hooks/useTomlMigration.ts new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/core/src/skills/skill-manager-extension.test.ts b/packages/core/src/skills/skill-manager-extension.test.ts new file mode 100644 index 00000000000..142872cbfe5 --- /dev/null +++ b/packages/core/src/skills/skill-manager-extension.test.ts @@ -0,0 +1,191 @@ +/** + * @license + * Copyright 2025 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { SkillManager, type Extension } from './skill-manager.js'; +import type { Config } from '../config/config.js'; +import * as fs from 'fs/promises'; +import * as path from 'path'; +import * as os from 'os'; + +describe('SkillManager - Extension Support', () => { + let manager: SkillManager; + let mockConfig: Config; + let tmpDir: string; + + beforeEach(async () => { + // Create a temporary directory for testing + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'skill-manager-test-')); + + mockConfig = { + getProjectRoot: () => tmpDir, + } as Config; + + manager = new SkillManager(mockConfig); + }); + + describe('listSkillsFromExtensions', () => { + it('should return empty array when no extensions provided', async () => { + const skills = await manager.listSkillsFromExtensions([]); + expect(skills).toEqual([]); + }); + + it('should return empty array when extensions have no skills paths', async () => { + const extensions: Extension[] = [ + { + path: '/path/to/extension', + config: { name: 'test', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [], + }, + ]; + + const skills = await manager.listSkillsFromExtensions(extensions); + expect(skills).toEqual([]); + }); + + it('should load skills from extension directories', async () => { + // Create test extension with a skill + const extensionDir = path.join(tmpDir, 'test-extension'); + const skillsDir = path.join(extensionDir, 'skills'); + const skillDir = path.join(skillsDir, 'test-skill'); + await fs.mkdir(skillDir, { recursive: true }); + + const skillContent = `--- +name: test-skill +description: A test skill from extension +--- + +This is a test skill from an extension.`; + + await fs.writeFile(path.join(skillDir, 'SKILL.md'), skillContent); + + const extensions: Extension[] = [ + { + path: extensionDir, + config: { name: 'test-extension', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [skillsDir], + }, + ]; + + const skills = await manager.listSkillsFromExtensions(extensions); + expect(skills).toHaveLength(1); + expect(skills[0].name).toBe('test-skill'); + expect(skills[0].description).toBe('A test skill from extension'); + expect(skills[0].level).toBe('extension'); + expect(skills[0].extensionName).toBe('test-extension'); + }); + + it('should load skills from multiple extensions', async () => { + // Create first extension + const ext1Dir = path.join(tmpDir, 'ext1'); + const skill1Dir = path.join(ext1Dir, 'skills', 'skill1'); + await fs.mkdir(skill1Dir, { recursive: true }); + await fs.writeFile( + path.join(skill1Dir, 'SKILL.md'), + '---\nname: skill1\ndescription: Skill 1\n---\nContent 1', + ); + + // Create second extension + const ext2Dir = path.join(tmpDir, 'ext2'); + const skill2Dir = path.join(ext2Dir, 'skills', 'skill2'); + await fs.mkdir(skill2Dir, { recursive: true }); + await fs.writeFile( + path.join(skill2Dir, 'SKILL.md'), + '---\nname: skill2\ndescription: Skill 2\n---\nContent 2', + ); + + const extensions: Extension[] = [ + { + path: ext1Dir, + config: { name: 'ext1', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [path.join(ext1Dir, 'skills')], + }, + { + path: ext2Dir, + config: { name: 'ext2', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [path.join(ext2Dir, 'skills')], + }, + ]; + + const skills = await manager.listSkillsFromExtensions(extensions); + expect(skills).toHaveLength(2); + expect(skills.map((s) => s.name)).toContain('skill1'); + expect(skills.map((s) => s.name)).toContain('skill2'); + }); + + it('should handle invalid skill files gracefully', async () => { + const extensionDir = path.join(tmpDir, 'test-extension'); + const skillsDir = path.join(extensionDir, 'skills'); + const skillDir = path.join(skillsDir, 'invalid-skill'); + await fs.mkdir(skillDir, { recursive: true }); + + // Create invalid skill file (missing name) + await fs.writeFile( + path.join(skillDir, 'SKILL.md'), + '---\ndescription: Invalid\n---\nContent', + ); + + const extensions: Extension[] = [ + { + path: extensionDir, + config: { name: 'test-extension', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [skillsDir], + }, + ]; + + const skills = await manager.listSkillsFromExtensions(extensions); + // Should skip invalid skill + expect(skills).toHaveLength(0); + }); + }); + + describe('listSkills with extensions', () => { + it('should include extension skills in list with correct precedence', async () => { + // Create project-level skill + const projectSkillsDir = path.join(tmpDir, '.qwen', 'skills'); + const projectSkillDir = path.join(projectSkillsDir, 'project-skill'); + await fs.mkdir(projectSkillDir, { recursive: true }); + await fs.writeFile( + path.join(projectSkillDir, 'SKILL.md'), + '---\nname: shared-skill\ndescription: Project skill\n---\nProject', + ); + + // Create extension skill with same name (should be overridden) + const extensionDir = path.join(tmpDir, 'test-extension'); + const extSkillsDir = path.join(extensionDir, 'skills'); + const extSkillDir = path.join(extSkillsDir, 'ext-skill'); + await fs.mkdir(extSkillDir, { recursive: true }); + await fs.writeFile( + path.join(extSkillDir, 'SKILL.md'), + '---\nname: shared-skill\ndescription: Extension skill\n---\nExtension', + ); + + const extensions: Extension[] = [ + { + path: extensionDir, + config: { name: 'test-extension', version: '1.0.0' }, + contextFiles: [], + skillsPaths: [extSkillsDir], + }, + ]; + + // Pass extensions to listSkills + manager.setExtensions(extensions); + const skills = await manager.listSkills(); + + // Project skill should take precedence + const sharedSkill = skills.find((s) => s.name === 'shared-skill'); + expect(sharedSkill).toBeDefined(); + expect(sharedSkill?.description).toBe('Project skill'); + expect(sharedSkill?.level).toBe('project'); + }); + }); +}); diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 77cec15fded..3aae504ad6e 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -21,6 +21,21 @@ const QWEN_CONFIG_DIR = '.qwen'; const SKILLS_CONFIG_DIR = 'skills'; const SKILL_MANIFEST_FILE = 'SKILL.md'; +/** + * Simplified Extension interface for SkillManager. + * Avoids circular dependency with cli package. + */ +export interface Extension { + path: string; + config: { + name: string; + version: string; + }; + /** Absolute paths to skills directories from this extension */ + skillsPaths?: string[]; + contextFiles?: string[]; +} + /** * Manages skill configurations stored as directories containing SKILL.md files. * Provides discovery, parsing, validation, and caching for skills. @@ -29,9 +44,20 @@ export class SkillManager { private skillsCache: Map | null = null; private readonly changeListeners: Set<() => void> = new Set(); private parseErrors: Map = new Map(); + private extensions: Extension[] = []; constructor(private readonly config: Config) {} + /** + * Sets the extensions to load skills from. + * Should be called before listSkills() to include extension skills. + */ + setExtensions(extensions: Extension[]): void { + this.extensions = extensions; + // Invalidate cache when extensions change + this.skillsCache = null; + } + /** * Adds a listener that will be called when skills change. * @returns A function to remove the listener. @@ -76,7 +102,7 @@ export class SkillManager { const levelsToCheck: SkillLevel[] = options.level ? [options.level] - : ['project', 'user']; + : ['project', 'user', 'extension']; // Check if we should use cache or force refresh const shouldUseCache = !options.force && this.skillsCache !== null; @@ -86,12 +112,12 @@ export class SkillManager { await this.refreshCache(); } - // Collect skills from each level (project takes precedence over user) + // Collect skills from each level (project takes precedence over user over extension) for (const level of levelsToCheck) { const levelSkills = this.skillsCache?.get(level) || []; for (const skill of levelSkills) { - // Skip if we've already seen this name (precedence: project > user) + // Skip if we've already seen this name (precedence: project > user > extension) if (seenNames.has(skill.name)) { continue; } @@ -217,10 +243,77 @@ export class SkillManager { skillsCache.set(level, levelSkills); } + // Load extension skills + const extensionSkills = await this.listSkillsFromExtensions( + this.extensions, + ); + skillsCache.set('extension', extensionSkills); + this.skillsCache = skillsCache; this.notifyChangeListeners(); } + /** + * Lists skills from all extensions. + * + * @param extensions - Array of extensions to load skills from + * @returns Array of skill configurations from extensions + */ + async listSkillsFromExtensions( + extensions: Extension[], + ): Promise { + const skills: SkillConfig[] = []; + + for (const extension of extensions) { + if (!extension.skillsPaths || extension.skillsPaths.length === 0) { + continue; + } + + for (const skillsPath of extension.skillsPaths) { + try { + const entries = await fs.readdir(skillsPath, { withFileTypes: true }); + + for (const entry of entries) { + // Only process directories (each skill is a directory) + if (!entry.isDirectory()) continue; + + const skillDir = path.join(skillsPath, entry.name); + const skillManifest = path.join(skillDir, SKILL_MANIFEST_FILE); + + try { + // Check if SKILL.md exists + await fs.access(skillManifest); + + const config = await this.parseSkillFileInternal( + skillManifest, + 'extension', + ); + config.extensionName = extension.config.name; + skills.push(config); + } catch (error) { + // Skip directories without valid SKILL.md + if (error instanceof SkillError) { + // Parse error was already recorded + console.warn( + `Failed to parse skill at ${skillDir}: ${error.message}`, + ); + } + continue; + } + } + } catch (error) { + // Directory doesn't exist or can't be read, skip this path + console.warn( + `Failed to read skills from extension ${extension.config.name} at ${skillsPath}: ${error instanceof Error ? error.message : 'Unknown error'}`, + ); + continue; + } + } + } + + return skills; + } + /** * Parses a SKILL.md file and returns the configuration. * diff --git a/packages/core/src/skills/types.ts b/packages/core/src/skills/types.ts index 75dfe014ac3..8227e9ea802 100644 --- a/packages/core/src/skills/types.ts +++ b/packages/core/src/skills/types.ts @@ -8,8 +8,9 @@ * Represents the storage level for a skill configuration. * - 'project': Stored in `.qwen/skills/` within the project directory * - 'user': Stored in `~/.qwen/skills/` in the user's home directory + * - 'extension': Provided by an installed extension */ -export type SkillLevel = 'project' | 'user'; +export type SkillLevel = 'project' | 'user' | 'extension'; /** * Core configuration for a skill as stored in SKILL.md files. @@ -43,6 +44,11 @@ export interface SkillConfig { * The markdown body content from SKILL.md (after the frontmatter) */ body: string; + + /** + * For extension-level skills: the name of the providing extension + */ + extensionName?: string; } /** diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index baf49fa9219..abe9b3a1851 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -389,8 +389,16 @@ export class SubagentManager { break; case 'level': { // Project comes before user, user comes before builtin, session comes last - const levelOrder = { project: 0, user: 1, builtin: 2, session: 3 }; - comparison = levelOrder[a.level] - levelOrder[b.level]; + const levelOrder = { + project: 0, + user: 1, + builtin: 2, + session: 3, + extension: 4, + }; + comparison = + levelOrder[a.level as SubagentLevel] - + levelOrder[b.level as SubagentLevel]; break; } default: diff --git a/packages/core/src/subagents/types.ts b/packages/core/src/subagents/types.ts index accfb18fb39..efa73a7e4d2 100644 --- a/packages/core/src/subagents/types.ts +++ b/packages/core/src/subagents/types.ts @@ -8,12 +8,18 @@ import type { Content, FunctionDeclaration } from '@google/genai'; /** * Represents the storage level for a subagent configuration. + * - 'session': Session-level agents provided at runtime, read-only (highest priority) * - 'project': Stored in `.qwen/agents/` within the project directory * - 'user': Stored in `~/.qwen/agents/` in the user's home directory - * - 'builtin': Built-in agents embedded in the codebase, always available - * - 'session': Session-level agents provided at runtime, read-only + * - 'extension': Provided by an installed extension + * - 'builtin': Built-in agents embedded in the codebase, always available (lowest priority) */ -export type SubagentLevel = 'project' | 'user' | 'builtin' | 'session'; +export type SubagentLevel = + | 'session' + | 'project' + | 'user' + | 'extension' + | 'builtin'; /** * Core configuration for a subagent as stored in Markdown files. @@ -68,6 +74,11 @@ export interface SubagentConfig { * Built-in agents cannot be modified or deleted. */ readonly isBuiltin?: boolean; + + /** + * For extension-level subagents: the name of the providing extension + */ + extensionName?: string; } /** From 50dac93c802d3495657b134b3c6447df5087103b Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 7 Jan 2026 13:43:00 +0800 Subject: [PATCH 02/30] feat: migrate command format --- .../services/command-migration-tool.test.ts | 37 ++++++- .../src/services/command-migration-tool.ts | 34 ++---- packages/cli/src/ui/AppContainer.tsx | 104 ++++++++++++++++++ .../src/ui/CommandFormatMigrationNudge.tsx | 90 +++++++++++++++ .../cli/src/ui/components/DialogManager.tsx | 9 ++ .../cli/src/ui/contexts/UIActionsContext.tsx | 2 + .../cli/src/ui/contexts/UIStateContext.tsx | 2 + .../cli/src/ui/hooks/useCommandMigration.ts | 51 +++++++++ 8 files changed, 297 insertions(+), 32 deletions(-) create mode 100644 packages/cli/src/ui/CommandFormatMigrationNudge.tsx create mode 100644 packages/cli/src/ui/hooks/useCommandMigration.ts diff --git a/packages/cli/src/services/command-migration-tool.test.ts b/packages/cli/src/services/command-migration-tool.test.ts index de459d746a9..128755b3c78 100644 --- a/packages/cli/src/services/command-migration-tool.test.ts +++ b/packages/cli/src/services/command-migration-tool.test.ts @@ -101,14 +101,20 @@ description = "Test description"`; expect(mdContent).toContain('description: Test description'); expect(mdContent).toContain('Test prompt'); - // Check backup was created - expect(result.backupDir).toBeDefined(); - const backupPath = path.join(result.backupDir!, 'test.toml'); + // Check backup was created (original renamed to .toml.backup) + const backupPath = path.join(tempDir, 'test.toml.backup'); const backupExists = await fs .access(backupPath) .then(() => true) .catch(() => false); expect(backupExists).toBe(true); + + // Original .toml file should not exist (renamed to .backup) + const tomlExists = await fs + .access(path.join(tempDir, 'test.toml')) + .then(() => true) + .catch(() => false); + expect(tomlExists).toBe(false); }); it('should delete original TOML when deleteOriginal is true', async () => { @@ -120,7 +126,7 @@ description = "Test description"`; await migrateTomlCommands({ commandDir: tempDir, - createBackup: true, + createBackup: false, deleteOriginal: true, }); @@ -137,6 +143,13 @@ description = "Test description"`; .then(() => true) .catch(() => false); expect(mdExists).toBe(true); + + // Backup should not exist (createBackup was false) + const backupExists = await fs + .access(path.join(tempDir, 'delete-me.toml.backup')) + .then(() => true) + .catch(() => false); + expect(backupExists).toBe(false); }); it('should fail if Markdown file already exists', async () => { @@ -172,10 +185,24 @@ description = "Test description"`; const result = await migrateTomlCommands({ commandDir: tempDir, createBackup: false, + deleteOriginal: false, }); expect(result.success).toBe(true); - expect(result.backupDir).toBeUndefined(); + + // Original TOML file should still exist (no backup, no delete) + const tomlExists = await fs + .access(path.join(tempDir, 'no-backup.toml')) + .then(() => true) + .catch(() => false); + expect(tomlExists).toBe(true); + + // Backup should not exist + const backupExists = await fs + .access(path.join(tempDir, 'no-backup.toml.backup')) + .then(() => true) + .catch(() => false); + expect(backupExists).toBe(false); }); it('should return success with empty results for no TOML files', async () => { diff --git a/packages/cli/src/services/command-migration-tool.ts b/packages/cli/src/services/command-migration-tool.ts index 7ff68ebabd3..1bb4b8e134c 100644 --- a/packages/cli/src/services/command-migration-tool.ts +++ b/packages/cli/src/services/command-migration-tool.ts @@ -17,7 +17,6 @@ export interface MigrationResult { success: boolean; convertedFiles: string[]; failedFiles: Array<{ file: string; error: string }>; - backupDir?: string; } export interface MigrationOptions { @@ -27,8 +26,6 @@ export interface MigrationOptions { createBackup?: boolean; /** Whether to delete original TOML files after migration (default: false) */ deleteOriginal?: boolean; - /** Backup directory suffix (default: '.backup') */ - backupSuffix?: string; } /** @@ -63,12 +60,7 @@ export async function detectTomlCommands( export async function migrateTomlCommands( options: MigrationOptions, ): Promise { - const { - commandDir, - createBackup = true, - deleteOriginal = false, - backupSuffix = '.backup', - } = options; + const { commandDir, createBackup = true, deleteOriginal = false } = options; const result: MigrationResult = { success: true, @@ -83,15 +75,6 @@ export async function migrateTomlCommands( return result; } - // Create backup directory if needed - let backupDir: string | undefined; - if (createBackup) { - const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); - backupDir = path.join(commandDir, `${backupSuffix}-${timestamp}`); - await fs.mkdir(backupDir, { recursive: true }); - result.backupDir = backupDir; - } - // Process each TOML file for (const relativeFile of tomlFiles) { const tomlPath = path.join(commandDir, relativeFile); @@ -122,15 +105,12 @@ export async function migrateTomlCommands( // Write Markdown file await fs.writeFile(markdownPath, markdownContent, 'utf-8'); - // Backup original if requested - if (backupDir) { - const backupPath = path.join(backupDir, relativeFile); - await fs.mkdir(path.dirname(backupPath), { recursive: true }); - await fs.copyFile(tomlPath, backupPath); - } - - // Delete original if requested - if (deleteOriginal) { + // Backup original if requested (rename to .toml.backup) + if (createBackup) { + const backupPath = `${tomlPath}.backup`; + await fs.rename(tomlPath, backupPath); + } else if (deleteOriginal) { + // Delete original if requested and no backup await fs.unlink(tomlPath); } diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 7921b20394e..de4c9189d5e 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -38,6 +38,7 @@ import { getErrorMessage, getAllGeminiMdFilenames, ShellExecutionService, + Storage, } from '@qwen-code/qwen-code-core'; import { buildResumedHistoryItems } from './utils/resumeHistoryUtils.js'; import { validateAuthMethod } from '../config/auth.js'; @@ -76,6 +77,9 @@ import { useLoadingIndicator } from './hooks/useLoadingIndicator.js'; import { useFolderTrust } from './hooks/useFolderTrust.js'; import { useIdeTrustListener } from './hooks/useIdeTrustListener.js'; import { type IdeIntegrationNudgeResult } from './IdeIntegrationNudge.js'; +import { type CommandMigrationNudgeResult } from './CommandFormatMigrationNudge.js'; +import { useCommandMigration } from './hooks/useCommandMigration.js'; +import { migrateTomlCommands } from '../services/command-migration-tool.js'; import { appEvents, AppEvent } from '../utils/events.js'; import { type UpdateObject } from './utils/updateCheck.js'; import { setUpdateHandler } from '../utils/handleAutoUpdate.js'; @@ -845,6 +849,13 @@ export const AppContainer = (props: AppContainerProps) => { !idePromptAnswered, ); + // Command migration nudge + const { + showMigrationNudge: shouldShowCommandMigrationNudge, + tomlFiles: commandMigrationTomlFiles, + setShowMigrationNudge: setShowCommandMigrationNudge, + } = useCommandMigration(settings, config.storage); + const [showErrorDetails, setShowErrorDetails] = useState(false); const [showToolDescriptions, setShowToolDescriptions] = useState(false); @@ -935,6 +946,92 @@ export const AppContainer = (props: AppContainerProps) => { [handleSlashCommand, settings], ); + const handleCommandMigrationComplete = useCallback( + async (result: CommandMigrationNudgeResult) => { + setShowCommandMigrationNudge(false); + + if (result.userSelection === 'yes') { + // Perform migration for both workspace and user levels + try { + const results = []; + + // Migrate workspace commands + const workspaceCommandsDir = config.storage.getProjectCommandsDir(); + const workspaceResult = await migrateTomlCommands({ + commandDir: workspaceCommandsDir, + createBackup: true, + deleteOriginal: false, + }); + if ( + workspaceResult.convertedFiles.length > 0 || + workspaceResult.failedFiles.length > 0 + ) { + results.push({ level: 'workspace', result: workspaceResult }); + } + + // Migrate user commands + const userCommandsDir = Storage.getUserCommandsDir(); + const userResult = await migrateTomlCommands({ + commandDir: userCommandsDir, + createBackup: true, + deleteOriginal: false, + }); + if ( + userResult.convertedFiles.length > 0 || + userResult.failedFiles.length > 0 + ) { + results.push({ level: 'user', result: userResult }); + } + + // Report results + for (const { level, result: migrationResult } of results) { + if ( + migrationResult.success && + migrationResult.convertedFiles.length > 0 + ) { + historyManager.addItem( + { + type: MessageType.INFO, + text: `✅ [${level}] Successfully migrated ${migrationResult.convertedFiles.length} command file${migrationResult.convertedFiles.length > 1 ? 's' : ''} to Markdown format. Original files backed up as .toml.backup`, + }, + Date.now(), + ); + } + + if (migrationResult.failedFiles.length > 0) { + historyManager.addItem( + { + type: MessageType.ERROR, + text: `⚠️ [${level}] Failed to migrate ${migrationResult.failedFiles.length} file${migrationResult.failedFiles.length > 1 ? 's' : ''}:\n${migrationResult.failedFiles.map((f) => ` • ${f.file}: ${f.error}`).join('\n')}`, + }, + Date.now(), + ); + } + } + + if (results.length === 0) { + historyManager.addItem( + { + type: MessageType.INFO, + text: 'ℹ️ No TOML files found to migrate.', + }, + Date.now(), + ); + } + } catch (error) { + historyManager.addItem( + { + type: MessageType.ERROR, + text: `❌ Migration failed: ${getErrorMessage(error)}`, + }, + Date.now(), + ); + } + } + }, + [historyManager, setShowCommandMigrationNudge, config.storage], + ); + const { elapsedTime, currentLoadingPhrase } = useLoadingIndicator( streamingState, settings.merged.ui?.customWittyPhrases, @@ -1179,6 +1276,7 @@ export const AppContainer = (props: AppContainerProps) => { showWelcomeBackDialog || showWorkspaceMigrationDialog || shouldShowIdePrompt || + shouldShowCommandMigrationNudge || isFolderTrustDialogOpen || !!shellConfirmationRequest || !!confirmationRequest || @@ -1244,6 +1342,8 @@ export const AppContainer = (props: AppContainerProps) => { suggestionsWidth, isInputActive, shouldShowIdePrompt, + shouldShowCommandMigrationNudge, + commandMigrationTomlFiles, isFolderTrustDialogOpen: isFolderTrustDialogOpen ?? false, isTrustedFolder, constrainHeight, @@ -1333,6 +1433,8 @@ export const AppContainer = (props: AppContainerProps) => { suggestionsWidth, isInputActive, shouldShowIdePrompt, + shouldShowCommandMigrationNudge, + commandMigrationTomlFiles, isFolderTrustDialogOpen, isTrustedFolder, constrainHeight, @@ -1404,6 +1506,7 @@ export const AppContainer = (props: AppContainerProps) => { setShellModeActive, vimHandleInput, handleIdePromptComplete, + handleCommandMigrationComplete, handleFolderTrustSelect, setConstrainHeight, onEscapePromptChange: handleEscapePromptChange, @@ -1441,6 +1544,7 @@ export const AppContainer = (props: AppContainerProps) => { setShellModeActive, vimHandleInput, handleIdePromptComplete, + handleCommandMigrationComplete, handleFolderTrustSelect, setConstrainHeight, handleEscapePromptChange, diff --git a/packages/cli/src/ui/CommandFormatMigrationNudge.tsx b/packages/cli/src/ui/CommandFormatMigrationNudge.tsx new file mode 100644 index 00000000000..214193b54db --- /dev/null +++ b/packages/cli/src/ui/CommandFormatMigrationNudge.tsx @@ -0,0 +1,90 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { Box, Text } from 'ink'; +import type { RadioSelectItem } from './components/shared/RadioButtonSelect.js'; +import { RadioButtonSelect } from './components/shared/RadioButtonSelect.js'; +import { useKeypress } from './hooks/useKeypress.js'; +import { theme } from './semantic-colors.js'; + +export type CommandMigrationNudgeResult = { + userSelection: 'yes' | 'no'; +}; + +interface CommandFormatMigrationNudgeProps { + tomlFiles: string[]; + onComplete: (result: CommandMigrationNudgeResult) => void; +} + +export function CommandFormatMigrationNudge({ + tomlFiles, + onComplete, +}: CommandFormatMigrationNudgeProps) { + useKeypress( + (key) => { + if (key.name === 'escape') { + onComplete({ + userSelection: 'no', + }); + } + }, + { isActive: true }, + ); + + const OPTIONS: Array> = [ + { + label: 'Yes', + value: { + userSelection: 'yes', + }, + key: 'Yes', + }, + { + label: 'No (esc)', + value: { + userSelection: 'no', + }, + key: 'No (esc)', + }, + ]; + + const count = tomlFiles.length; + const fileList = + count <= 3 + ? tomlFiles.map((f) => ` • ${f}`).join('\n') + : ` • ${tomlFiles.slice(0, 2).join('\n • ')}\n • ... and ${count - 2} more`; + + return ( + + + + {'⚠️ '} + Command Format Migration + + + {`Found ${count} TOML command file${count > 1 ? 's' : ''}:`} + + {fileList} + {''} + + The TOML format is deprecated. Would you like to migrate them to + Markdown format? + + + (Backups will be created and original files will be preserved) + + + + + ); +} diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index c3e1a128cea..a87192ab2a3 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -6,6 +6,7 @@ import { Box, Text } from 'ink'; import { IdeIntegrationNudge } from '../IdeIntegrationNudge.js'; +import { CommandFormatMigrationNudge } from '../CommandFormatMigrationNudge.js'; import { LoopDetectionConfirmation } from './LoopDetectionConfirmation.js'; import { FolderTrustDialog } from './FolderTrustDialog.js'; import { ShellConfirmationDialog } from './ShellConfirmationDialog.js'; @@ -94,6 +95,14 @@ export const DialogManager = ({ /> ); } + if (uiState.shouldShowCommandMigrationNudge) { + return ( + + ); + } if (uiState.isFolderTrustDialogOpen) { return ( void; vimHandleInput: (key: Key) => boolean; handleIdePromptComplete: (result: IdeIntegrationNudgeResult) => void; + handleCommandMigrationComplete: (result: CommandMigrationNudgeResult) => void; handleFolderTrustSelect: (choice: FolderTrustChoice) => void; setConstrainHeight: (value: boolean) => void; onEscapePromptChange: (show: boolean) => void; diff --git a/packages/cli/src/ui/contexts/UIStateContext.tsx b/packages/cli/src/ui/contexts/UIStateContext.tsx index 806cf09ba75..d795a6089c7 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -72,6 +72,8 @@ export interface UIState { suggestionsWidth: number; isInputActive: boolean; shouldShowIdePrompt: boolean; + shouldShowCommandMigrationNudge: boolean; + commandMigrationTomlFiles: string[]; isFolderTrustDialogOpen: boolean; isTrustedFolder: boolean | undefined; constrainHeight: boolean; diff --git a/packages/cli/src/ui/hooks/useCommandMigration.ts b/packages/cli/src/ui/hooks/useCommandMigration.ts new file mode 100644 index 00000000000..191694089ba --- /dev/null +++ b/packages/cli/src/ui/hooks/useCommandMigration.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { useEffect, useState } from 'react'; +import { Storage } from '@qwen-code/qwen-code-core'; +import { detectTomlCommands } from '../../services/command-migration-tool.js'; +import type { LoadedSettings } from '../../config/settings.js'; + +/** + * Hook to detect TOML command files and manage migration nudge visibility. + * Checks all command directories: workspace, user, and global levels. + */ +export function useCommandMigration( + settings: LoadedSettings, + storage: Storage, +) { + const [showMigrationNudge, setShowMigrationNudge] = useState(false); + const [tomlFiles, setTomlFiles] = useState([]); + + useEffect(() => { + const checkTomlCommands = async () => { + const allFiles: string[] = []; + + // Check workspace commands directory (.qwen/commands) + const workspaceCommandsDir = storage.getProjectCommandsDir(); + const workspaceFiles = await detectTomlCommands(workspaceCommandsDir); + allFiles.push(...workspaceFiles.map((f) => `workspace: ${f}`)); + + // Check user commands directory (~/.qwen/commands) + const userCommandsDir = Storage.getUserCommandsDir(); + const userFiles = await detectTomlCommands(userCommandsDir); + allFiles.push(...userFiles.map((f) => `user: ${f}`)); + + if (allFiles.length > 0) { + setTomlFiles(allFiles); + setShowMigrationNudge(true); + } + }; + + checkTomlCommands(); + }, [storage]); + + return { + showMigrationNudge, + tomlFiles, + setShowMigrationNudge, + }; +} From 18713ef2b09fb20e23c32742443507567cdc189a Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 7 Jan 2026 19:17:34 +0800 Subject: [PATCH 03/30] feat: install from gemini --- .../cli/src/commands/extensions/install.ts | 22 +- packages/cli/src/config/extension.ts | 124 +++++++++- .../src/config/extensions/converter.test.ts | 228 ++++++++++++++++++ .../extensions/gemini-converter.test.ts | 152 ++++++++++-- .../src/config/extensions/gemini-converter.ts | 149 +++++++++++- packages/cli/src/ui/AppContainer.tsx | 6 +- packages/core/src/config/config.ts | 2 +- packages/core/src/skills/skill-manager.ts | 39 +++ 8 files changed, 681 insertions(+), 41 deletions(-) create mode 100644 packages/cli/src/config/extensions/converter.test.ts diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index 2f1675ff938..a7333b704c3 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -12,6 +12,7 @@ import { import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; import { getErrorMessage } from '../../utils/errors.js'; import { stat } from 'node:fs/promises'; +import { parseMarketplaceSource } from '../../config/extensions/marketplace.js'; interface InstallArgs { source: string; @@ -23,7 +24,20 @@ export async function handleInstall(args: InstallArgs) { try { let installMetadata: ExtensionInstallMetadata; const { source } = args; - if ( + + // Check if it's a marketplace source (format: marketplace-url:plugin-name) + const marketplaceParsed = parseMarketplaceSource(source); + if (marketplaceParsed) { + if (args.ref || args.autoUpdate) { + throw new Error( + '--ref and --auto-update are not applicable for marketplace extensions.', + ); + } + installMetadata = { + source, + type: 'marketplace', + }; + } else if ( source.startsWith('http://') || source.startsWith('https://') || source.startsWith('git@') || @@ -65,11 +79,13 @@ export async function handleInstall(args: InstallArgs) { export const installCommand: CommandModule = { command: 'install ', - describe: 'Installs an extension from a git repository URL or a local path.', + describe: + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).', builder: (yargs) => yargs .positional('source', { - describe: 'The github URL or local path of the extension to install.', + describe: + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.', type: 'string', demandOption: true, }) diff --git a/packages/cli/src/config/extension.ts b/packages/cli/src/config/extension.ts index e9ed41635a2..8942e2e9bd9 100644 --- a/packages/cli/src/config/extension.ts +++ b/packages/cli/src/config/extension.ts @@ -38,6 +38,16 @@ import type { LoadExtensionContext } from './extensions/variableSchema.js'; import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; import chalk from 'chalk'; import type { ConfirmationRequest } from '../ui/types.js'; +import { + installFromMarketplace, + parseMarketplaceSource, +} from './extensions/marketplace.js'; +import { isClaudePluginConfig } from './extensions/claude-converter.js'; +import { + isGeminiExtensionConfig, + convertGeminiExtensionPackage, +} from './extensions/gemini-converter.js'; +import { glob } from 'glob'; export const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); @@ -493,7 +503,27 @@ export async function installExtension( let tempDir: string | undefined; - if ( + // Handle marketplace installation + if (installMetadata.type === 'marketplace') { + const marketplaceParsed = parseMarketplaceSource(installMetadata.source); + if (!marketplaceParsed) { + throw new Error( + `Invalid marketplace source format: ${installMetadata.source}. Expected format: marketplace-url:plugin-name`, + ); + } + + tempDir = await ExtensionStorage.createTmpDir(); + const marketplaceResult = await installFromMarketplace({ + marketplaceUrl: marketplaceParsed.marketplaceUrl, + pluginName: marketplaceParsed.pluginName, + tempDir, + requestConsent, + }); + + newExtensionConfig = marketplaceResult.config; + localSourcePath = marketplaceResult.sourcePath; + installMetadata = marketplaceResult.installMetadata; + } else if ( installMetadata.type === 'git' || installMetadata.type === 'github-release' ) { @@ -520,10 +550,14 @@ export async function installExtension( } try { - newExtensionConfig = loadExtensionConfig({ - extensionDir: localSourcePath, - workspaceDir: cwd, - }); + localSourcePath = await convertGeminiOrClaudeExtension(localSourcePath); + // Load extension config if not already loaded (from marketplace) + if (!newExtensionConfig) { + newExtensionConfig = loadExtensionConfig({ + extensionDir: localSourcePath, + workspaceDir: cwd, + }); + } const newExtensionName = newExtensionConfig.name; const extensionStorage = new ExtensionStorage(newExtensionName); @@ -539,9 +573,16 @@ export async function installExtension( `Extension "${newExtensionName}" is already installed. Please uninstall it first.`, ); } + + const commands = await loadCommandsFromDir( + `${localSourcePath}/commands`, + newExtensionConfig.name, + ); + await maybeRequestConsentOrFail( newExtensionConfig, requestConsent, + commands, previousExtensionConfig, ); await fs.promises.mkdir(destinationPath, { recursive: true }); @@ -564,6 +605,9 @@ export async function installExtension( if (tempDir) { await fs.promises.rm(tempDir, { recursive: true, force: true }); } + if (localSourcePath !== tempDir) { + await fs.promises.rm(localSourcePath, { recursive: true, force: true }); + } } logExtensionInstallEvent( @@ -608,7 +652,10 @@ export async function installExtension( * Builds a consent string for installing an extension based on it's * extensionConfig. */ -function extensionConsentString(extensionConfig: ExtensionConfig): string { +function extensionConsentString( + extensionConfig: ExtensionConfig, + commands?: string[], +): string { const output: string[] = []; const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); output.push(`Installing extension "${extensionConfig.name}".`); @@ -626,6 +673,11 @@ function extensionConsentString(extensionConfig: ExtensionConfig): string { output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); } } + if (commands && commands.length > 0) { + output.push( + `This extension will add the following commands: ${commands.join(', ')}.`, + ); + } if (extensionConfig.contextFileName) { output.push( `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, @@ -651,9 +703,10 @@ function extensionConsentString(extensionConfig: ExtensionConfig): string { async function maybeRequestConsentOrFail( extensionConfig: ExtensionConfig, requestConsent: (consent: string) => Promise, + commands: string[], previousExtensionConfig?: ExtensionConfig, ) { - const extensionConsent = extensionConsentString(extensionConfig); + const extensionConsent = extensionConsentString(extensionConfig, commands); if (previousExtensionConfig) { const previousExtensionConsent = extensionConsentString( previousExtensionConfig, @@ -667,6 +720,49 @@ async function maybeRequestConsentOrFail( } } +async function loadCommandsFromDir( + dir: string, + extensionName: string, +): Promise { + const globOptions = { + nodir: true, + dot: true, + follow: true, + }; + + try { + const mdFiles = await glob('**/*.md', { + ...globOptions, + cwd: dir, + }); + + const commandNames = mdFiles.map((file) => { + const relativePathWithExt = path.relative(dir, path.join(dir, file)); + const relativePath = relativePathWithExt.substring( + 0, + relativePathWithExt.length - 3, + ); + const baseCommandName = relativePath + .split(path.sep) + .map((segment) => segment.replaceAll(':', '_')) + .join(':'); + + const commandName = `${extensionName}:${baseCommandName}`; + return commandName; + }); + + return commandNames; + } catch (error) { + // Ignore ENOENT (directory doesn't exist) and AbortError (operation was cancelled) + const isEnoent = (error as NodeJS.ErrnoException).code === 'ENOENT'; + const isAbortError = error instanceof Error && error.name === 'AbortError'; + if (!isEnoent && !isAbortError) { + console.error(`Error loading commands from ${dir}:`, error); + } + return []; + } +} + export function validateName(name: string) { if (!/^[a-zA-Z0-9-]+$/.test(name)) { throw new Error( @@ -675,6 +771,20 @@ export function validateName(name: string) { } } +async function convertGeminiOrClaudeExtension(extensionDir: string) { + let newExtensionDir = extensionDir; + const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); + if (fs.existsSync(configFilePath)) { + newExtensionDir = extensionDir; + } else if (isGeminiExtensionConfig(extensionDir)) { + newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)) + .convertedDir; + } else if (isClaudePluginConfig(extensionDir)) { + // claude + } + return newExtensionDir; +} + export function loadExtensionConfig( context: LoadExtensionContext, ): ExtensionConfig { diff --git a/packages/cli/src/config/extensions/converter.test.ts b/packages/cli/src/config/extensions/converter.test.ts new file mode 100644 index 00000000000..67c3cc2d13b --- /dev/null +++ b/packages/cli/src/config/extensions/converter.test.ts @@ -0,0 +1,228 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { + isClaudePluginConfig, + convertClaudeToQwenConfig, + mergeClaudeConfigs, + type ClaudePluginConfig, + type ClaudeMarketplacePluginConfig, +} from './claude-converter.js'; +import { + isGeminiExtensionConfig, + convertGeminiToQwenConfig, + type GeminiExtensionConfig, +} from './gemini-converter.js'; +import { parseMarketplaceSource } from './marketplace.js'; + +describe('Claude Converter', () => { + describe('isClaudePluginConfig', () => { + it('should detect Claude plugin config', () => { + const config = { + name: 'test-plugin', + version: '1.0.0', + agents: 'agents/', + hooks: 'hooks.js', + }; + expect(isClaudePluginConfig(config)).toBe(true); + }); + + it('should return false for non-Claude config', () => { + const config = { + name: 'test-plugin', + version: '1.0.0', + commands: 'commands/', + }; + expect(isClaudePluginConfig(config)).toBe(false); + }); + + it('should return false for invalid config', () => { + expect(isClaudePluginConfig(null)).toBe(false); + expect(isClaudePluginConfig('string')).toBe(false); + expect(isClaudePluginConfig({})).toBe(false); + }); + }); + + describe('convertClaudeToQwenConfig', () => { + it('should convert basic Claude config', () => { + const claudeConfig: ClaudePluginConfig = { + name: 'claude-plugin', + version: '1.0.0', + commands: 'commands/', + agents: 'agents/', + }; + + const qwenConfig = convertClaudeToQwenConfig(claudeConfig); + + expect(qwenConfig.name).toBe('claude-plugin'); + expect(qwenConfig.version).toBe('1.0.0'); + expect(qwenConfig.commands).toBe('commands/'); + expect(qwenConfig.agents).toBe('agents/'); + }); + + it('should throw error for invalid config', () => { + expect(() => convertClaudeToQwenConfig({} as ClaudePluginConfig)).toThrow( + 'Claude plugin config must have name and version fields', + ); + }); + }); + + describe('mergeClaudeConfigs', () => { + it('should merge marketplace and plugin configs', () => { + const marketplaceConfig: ClaudeMarketplacePluginConfig = { + name: 'plugin', + version: '2.0.0', + source: 'https://github.com/example/plugin', + description: 'Updated description', + }; + + const pluginConfig: ClaudePluginConfig = { + name: 'plugin', + version: '1.0.0', + description: 'Original description', + commands: 'commands/', + }; + + const merged = mergeClaudeConfigs(marketplaceConfig, pluginConfig); + + expect(merged.name).toBe('plugin'); + expect(merged.version).toBe('2.0.0'); + expect(merged.description).toBe('Updated description'); + expect(merged.commands).toBe('commands/'); + }); + + it('should throw error in strict mode without plugin config', () => { + const marketplaceConfig: ClaudeMarketplacePluginConfig = { + name: 'plugin', + version: '1.0.0', + source: 'https://github.com/example/plugin', + strict: true, + }; + + expect(() => mergeClaudeConfigs(marketplaceConfig)).toThrow( + 'Plugin plugin requires plugin.json (strict mode)', + ); + }); + }); +}); + +describe('Gemini Converter', () => { + describe('isGeminiExtensionConfig', () => { + it('should detect Gemini extension config with settings', () => { + const config = { + name: 'test-extension', + version: '1.0.0', + settings: [ + { + name: 'API Key', + description: 'Your API key', + envVar: 'MY_API_KEY', + }, + ], + }; + expect(isGeminiExtensionConfig(config)).toBe(true); + }); + + it('should return true for basic Gemini config without settings', () => { + const config = { + name: 'test-extension', + version: '1.0.0', + contextFileName: 'QWEN.md', + }; + expect(isGeminiExtensionConfig(config)).toBe(true); + }); + + it('should return false for invalid config', () => { + expect(isGeminiExtensionConfig(null)).toBe(false); + expect(isGeminiExtensionConfig('string')).toBe(false); + expect(isGeminiExtensionConfig({})).toBe(false); + }); + }); + + describe('convertGeminiToQwenConfig', () => { + it('should convert basic Gemini config', () => { + const geminiConfig: GeminiExtensionConfig = { + name: 'gemini-extension', + version: '1.0.0', + commands: 'commands/', + excludeTools: ['tool1', 'tool2'], + }; + + const qwenConfig = convertGeminiToQwenConfig(geminiConfig); + + expect(qwenConfig.name).toBe('gemini-extension'); + expect(qwenConfig.version).toBe('1.0.0'); + expect(qwenConfig.commands).toBe('commands/'); + expect(qwenConfig.excludeTools).toEqual(['tool1', 'tool2']); + }); + + it('should convert config with settings', () => { + const geminiConfig: GeminiExtensionConfig = { + name: 'gemini-extension', + version: '1.0.0', + settings: [ + { + name: 'API Key', + description: 'Your API key', + envVar: 'MY_API_KEY', + sensitive: true, + }, + ], + }; + + const qwenConfig = convertGeminiToQwenConfig(geminiConfig); + + expect(qwenConfig.settings).toEqual(geminiConfig.settings); + }); + + it('should throw error for invalid config', () => { + expect(() => + convertGeminiToQwenConfig({} as GeminiExtensionConfig), + ).toThrow('Gemini extension config must have name and version fields'); + }); + }); +}); + +describe('Marketplace Parser', () => { + describe('parseMarketplaceSource', () => { + it('should parse valid marketplace source', () => { + const result = parseMarketplaceSource( + 'https://github.com/example/marketplace:my-plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://github.com/example/marketplace', + pluginName: 'my-plugin', + }); + }); + + it('should parse HTTP marketplace source', () => { + const result = parseMarketplaceSource( + 'http://example.com/marketplace:plugin-name', + ); + expect(result).toEqual({ + marketplaceUrl: 'http://example.com/marketplace', + pluginName: 'plugin-name', + }); + }); + + it('should handle multiple colons in URL', () => { + const result = parseMarketplaceSource( + 'https://github.com:8080/repo:plugin', + ); + expect(result).toEqual({ + marketplaceUrl: 'https://github.com:8080/repo', + pluginName: 'plugin', + }); + }); + + it('should return null for invalid sources', () => { + expect(parseMarketplaceSource('not-a-url:plugin')).toBeNull(); + expect(parseMarketplaceSource('https://github.com/repo')).toBeNull(); + expect(parseMarketplaceSource('https://github.com/repo:')).toBeNull(); + }); + }); +}); diff --git a/packages/cli/src/config/extensions/gemini-converter.test.ts b/packages/cli/src/config/extensions/gemini-converter.test.ts index 94e1f11f57b..b53b2ccaa50 100644 --- a/packages/cli/src/config/extensions/gemini-converter.test.ts +++ b/packages/cli/src/config/extensions/gemini-converter.test.ts @@ -4,60 +4,176 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import { convertGeminiToQwenConfig, isGeminiExtensionConfig, type GeminiExtensionConfig, } from './gemini-converter.js'; +// Mock fs module +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + existsSync: vi.fn(), + readFileSync: vi.fn(), + }; +}); + describe('convertGeminiToQwenConfig', () => { - it('should convert basic Gemini config', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should convert basic Gemini config from directory', () => { + const mockDir = '/mock/extension/dir'; const geminiConfig: GeminiExtensionConfig = { name: 'test-extension', version: '1.0.0', }; - const result = convertGeminiToQwenConfig(geminiConfig); + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(geminiConfig)); + + const result = convertGeminiToQwenConfig(mockDir); expect(result.name).toBe('test-extension'); expect(result.version).toBe('1.0.0'); + expect(fs.readFileSync).toHaveBeenCalledWith( + path.join(mockDir, 'gemini-extension.json'), + 'utf-8', + ); }); - it('should convert config with commands', () => { - const geminiConfig: GeminiExtensionConfig = { - name: 'cmd-extension', - version: '1.0.0', - commands: 'commands', + it('should convert config with all optional fields', () => { + const mockDir = '/mock/extension/dir'; + const geminiConfig = { + name: 'full-extension', + version: '2.0.0', + mcpServers: { server1: {} }, + contextFileName: 'context.txt', + excludeTools: ['tool1', 'tool2'], + settings: [ + { name: 'Setting1', envVar: 'VAR1', description: 'Test setting' }, + ], }; - const result = convertGeminiToQwenConfig(geminiConfig); + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(geminiConfig)); - expect(result.commands).toBe('commands'); + const result = convertGeminiToQwenConfig(mockDir); + + expect(result.name).toBe('full-extension'); + expect(result.version).toBe('2.0.0'); + expect(result.mcpServers).toEqual({ server1: {} }); + expect(result.contextFileName).toBe('context.txt'); + expect(result.excludeTools).toEqual(['tool1', 'tool2']); + expect(result.settings).toHaveLength(1); + expect(result.settings?.[0].name).toBe('Setting1'); }); it('should throw error for missing name', () => { + const mockDir = '/mock/extension/dir'; const invalidConfig = { version: '1.0.0', - } as GeminiExtensionConfig; + }; + + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(invalidConfig)); - expect(() => convertGeminiToQwenConfig(invalidConfig)).toThrow(); + expect(() => convertGeminiToQwenConfig(mockDir)).toThrow( + 'Gemini extension config must have name and version fields', + ); + }); + + it('should throw error for missing version', () => { + const mockDir = '/mock/extension/dir'; + const invalidConfig = { + name: 'test-extension', + }; + + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(invalidConfig)); + + expect(() => convertGeminiToQwenConfig(mockDir)).toThrow( + 'Gemini extension config must have name and version fields', + ); }); }); describe('isGeminiExtensionConfig', () => { - it('should identify Gemini config with settings', () => { - const config = { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should identify Gemini extension directory with valid config', () => { + const mockDir = '/mock/extension/dir'; + const mockConfig = { name: 'test', version: '1.0.0', settings: [{ name: 'Test', envVar: 'TEST', description: 'Test' }], }; - expect(isGeminiExtensionConfig(config)).toBe(true); + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(mockConfig)); + + expect(isGeminiExtensionConfig(mockDir)).toBe(true); + + expect(fs.existsSync).toHaveBeenCalledWith( + path.join(mockDir, 'gemini-extension.json'), + ); + }); + + it('should return false when gemini-extension.json does not exist', () => { + const mockDir = '/mock/nonexistent/dir'; + + vi.mocked(fs.existsSync).mockReturnValue(false); + + expect(isGeminiExtensionConfig(mockDir)).toBe(false); }); - it('should return false for invalid config', () => { - expect(isGeminiExtensionConfig(null)).toBe(false); - expect(isGeminiExtensionConfig({})).toBe(false); + it('should return false for invalid config content', () => { + const mockDir = '/mock/invalid/dir'; + + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue('null'); + + expect(isGeminiExtensionConfig(mockDir)).toBe(false); + }); + + it('should return false for config missing required fields', () => { + const mockDir = '/mock/invalid/dir'; + const invalidConfig = { + name: 'test', + // missing version + }; + + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(invalidConfig)); + + expect(isGeminiExtensionConfig(mockDir)).toBe(false); + }); + + it('should return true for basic config without settings', () => { + const mockDir = '/mock/extension/dir'; + const basicConfig = { + name: 'test', + version: '1.0.0', + }; + + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(basicConfig)); + + expect(isGeminiExtensionConfig(mockDir)).toBe(true); }); }); + +// Note: convertGeminiExtensionPackage() is tested through integration tests +// as it requires real file system operations diff --git a/packages/cli/src/config/extensions/gemini-converter.ts b/packages/cli/src/config/extensions/gemini-converter.ts index 2ed71c03773..2aa0b7a749c 100644 --- a/packages/cli/src/config/extensions/gemini-converter.ts +++ b/packages/cli/src/config/extensions/gemini-converter.ts @@ -8,7 +8,12 @@ * Converter for Gemini CLI extensions to Qwen Code format. */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { glob } from 'glob'; import type { ExtensionConfig, ExtensionSetting } from '../extension.js'; +import { ExtensionStorage } from '../extension.js'; +import { convertTomlToMarkdown } from '../../services/toml-to-markdown-converter.js'; export interface GeminiExtensionConfig { name: string; @@ -16,18 +21,20 @@ export interface GeminiExtensionConfig { mcpServers?: Record; contextFileName?: string | string[]; excludeTools?: string[]; - commands?: string | string[]; settings?: ExtensionSetting[]; } /** * Converts a Gemini CLI extension config to Qwen Code format. - * @param geminiConfig Gemini extension configuration + * @param extensionDir Path to the Gemini extension directory * @returns Qwen ExtensionConfig */ export function convertGeminiToQwenConfig( - geminiConfig: GeminiExtensionConfig, + extensionDir: string, ): ExtensionConfig { + const configFilePath = path.join(extensionDir, 'gemini-extension.json'); + const configContent = fs.readFileSync(configFilePath, 'utf-8'); + const geminiConfig: GeminiExtensionConfig = JSON.parse(configContent); // Validate required fields if (!geminiConfig.name || !geminiConfig.version) { throw new Error( @@ -44,25 +51,149 @@ export function convertGeminiToQwenConfig( mcpServers: geminiConfig.mcpServers as ExtensionConfig['mcpServers'], contextFileName: geminiConfig.contextFileName, excludeTools: geminiConfig.excludeTools, - commands: geminiConfig.commands, settings, }; } +/** + * Converts a complete Gemini extension package to Qwen Code format. + * Creates a new temporary directory with: + * 1. Converted qwen-extension.json + * 2. Commands converted from TOML to MD + * 3. All other files/folders preserved + * + * @param extensionDir Path to the Gemini extension directory + * @returns Object containing converted config and the temporary directory path + */ +export async function convertGeminiExtensionPackage( + extensionDir: string, +): Promise<{ config: ExtensionConfig; convertedDir: string }> { + const geminiConfig = convertGeminiToQwenConfig(extensionDir); + + // Create temporary directory for converted extension + const tmpDir = await ExtensionStorage.createTmpDir(); + + try { + // Step 1: Copy all files and directories to temporary directory + await copyDirectory(extensionDir, tmpDir); + + // Step 2: Convert TOML commands to Markdown in commands folder + const commandsDir = path.join(tmpDir, 'commands'); + if (fs.existsSync(commandsDir)) { + await convertCommandsDirectory(commandsDir); + } + + // Step 3: Create qwen-extension.json with converted config + const qwenConfigPath = path.join(tmpDir, 'qwen-extension.json'); + fs.writeFileSync( + qwenConfigPath, + JSON.stringify(geminiConfig, null, 2), + 'utf-8', + ); + + return { + config: geminiConfig, + convertedDir: tmpDir, + }; + } catch (error) { + // Clean up temporary directory on error + try { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } catch { + // Ignore cleanup errors + } + throw error; + } +} + +/** + * Recursively copies a directory and its contents. + * @param source Source directory path + * @param destination Destination directory path + */ +async function copyDirectory( + source: string, + destination: string, +): Promise { + // Create destination directory if it doesn't exist + if (!fs.existsSync(destination)) { + fs.mkdirSync(destination, { recursive: true }); + } + + const entries = fs.readdirSync(source, { withFileTypes: true }); + + for (const entry of entries) { + const sourcePath = path.join(source, entry.name); + const destPath = path.join(destination, entry.name); + + if (entry.isDirectory()) { + await copyDirectory(sourcePath, destPath); + } else { + fs.copyFileSync(sourcePath, destPath); + } + } +} + +/** + * Converts all TOML command files in a directory to Markdown format. + * @param commandsDir Path to the commands directory + */ +async function convertCommandsDirectory(commandsDir: string): Promise { + // Find all .toml files in the commands directory + const tomlFiles = await glob('**/*.toml', { + cwd: commandsDir, + nodir: true, + dot: false, + }); + + // Convert each TOML file to Markdown + for (const relativeFile of tomlFiles) { + const tomlPath = path.join(commandsDir, relativeFile); + + try { + // Read TOML file + const tomlContent = fs.readFileSync(tomlPath, 'utf-8'); + + // Convert to Markdown + const markdownContent = convertTomlToMarkdown(tomlContent); + + // Generate Markdown file path (same location, .md extension) + const markdownPath = tomlPath.replace(/\.toml$/, '.md'); + + // Write Markdown file + fs.writeFileSync(markdownPath, markdownContent, 'utf-8'); + + // Delete original TOML file + fs.unlinkSync(tomlPath); + } catch (error) { + console.warn( + `Warning: Failed to convert command file ${relativeFile}: ${error instanceof Error ? error.message : String(error)}`, + ); + // Continue with other files even if one fails + } + } +} + /** * Checks if a config object is in Gemini format. * This is a heuristic check based on typical Gemini extension patterns. * @param config Configuration object to check * @returns true if config appears to be Gemini format */ -export function isGeminiExtensionConfig( - config: unknown, -): config is GeminiExtensionConfig { - if (typeof config !== 'object' || config === null) { +export function isGeminiExtensionConfig(extensionDir: string) { + const configFilePath = path.join(extensionDir, 'gemini-extension.json'); + if (!fs.existsSync(configFilePath)) { + return false; + } + + const configContent = fs.readFileSync(configFilePath, 'utf-8'); + const parsedConfig = JSON.parse(configContent); + + if (typeof parsedConfig !== 'object' || parsedConfig === null) { return false; } - const obj = config as Record; + const obj = parsedConfig as Record; // Must have name and version if (typeof obj['name'] !== 'string' || typeof obj['version'] !== 'string') { diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index de4c9189d5e..d76a4fd69a8 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -992,7 +992,7 @@ export const AppContainer = (props: AppContainerProps) => { historyManager.addItem( { type: MessageType.INFO, - text: `✅ [${level}] Successfully migrated ${migrationResult.convertedFiles.length} command file${migrationResult.convertedFiles.length > 1 ? 's' : ''} to Markdown format. Original files backed up as .toml.backup`, + text: `[${level}] Successfully migrated ${migrationResult.convertedFiles.length} command file${migrationResult.convertedFiles.length > 1 ? 's' : ''} to Markdown format. Original files backed up as .toml.backup`, }, Date.now(), ); @@ -1002,7 +1002,7 @@ export const AppContainer = (props: AppContainerProps) => { historyManager.addItem( { type: MessageType.ERROR, - text: `⚠️ [${level}] Failed to migrate ${migrationResult.failedFiles.length} file${migrationResult.failedFiles.length > 1 ? 's' : ''}:\n${migrationResult.failedFiles.map((f) => ` • ${f.file}: ${f.error}`).join('\n')}`, + text: `[${level}] Failed to migrate ${migrationResult.failedFiles.length} file${migrationResult.failedFiles.length > 1 ? 's' : ''}:\n${migrationResult.failedFiles.map((f) => ` • ${f.file}: ${f.error}`).join('\n')}`, }, Date.now(), ); @@ -1013,7 +1013,7 @@ export const AppContainer = (props: AppContainerProps) => { historyManager.addItem( { type: MessageType.INFO, - text: 'ℹ️ No TOML files found to migrate.', + text: 'No TOML files found to migrate.', }, Date.now(), ); diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 34dbb464958..3f5c4c63f2f 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -202,7 +202,7 @@ export interface GeminiCLIExtension { export interface ExtensionInstallMetadata { source: string; - type: 'git' | 'local' | 'link' | 'github-release'; + type: 'git' | 'local' | 'link' | 'github-release' | 'marketplace'; releaseTag?: string; // Only present for github-release installs. ref?: string; autoUpdate?: boolean; diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 3aae504ad6e..7a693add39c 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -314,6 +314,45 @@ export class SkillManager { return skills; } + /** + * Lists skills from directory. + * + * @param dir - provided directory + * @returns Array of skill configurations + */ + async parseSkillsFromDir(dir: string): Promise { + const discoveredSkills: SkillConfig[] = []; + + try { + const absoluteSearchPath = path.resolve(dir); + const stats = await fs.stat(absoluteSearchPath).catch(() => null); + if (!stats || !stats.isDirectory()) { + return []; + } + + const skillFiles = await glob('*/SKILL.md', { + cwd: absoluteSearchPath, + absolute: true, + nodir: true, + }); + + for (const skillFile of skillFiles) { + const metadata = await this.parseSkillFile(skillFile, 'extension'); + if (metadata) { + discoveredSkills.push(metadata); + } + } + } catch (error) { + coreEvents.emitFeedback( + 'warning', + `Error discovering skills in ${dir}:`, + error, + ); + } + + return discoveredSkills; + } + /** * Parses a SKILL.md file and returns the configuration. * From 74013bd8b2d377ad0fe7187e3177bc6f95c58f3c Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Thu, 8 Jan 2026 13:49:59 +0800 Subject: [PATCH 04/30] feat: settings extension --- package-lock.json | 41 + packages/cli/package.json | 2 + packages/cli/src/acp-integration/acpAgent.ts | 3 +- .../cli/src/commands/extensions/update.ts | 3 +- packages/cli/src/commands/mcp/list.test.ts | 3 +- packages/cli/src/commands/mcp/list.ts | 3 +- packages/cli/src/config/config.test.ts | 3 +- packages/cli/src/config/extension.test.ts | 8 +- packages/cli/src/config/extension.ts | 156 ++-- packages/cli/src/config/extensions/consent.ts | 157 ++++ .../src/config/extensions/converter.test.ts | 228 ------ .../extensions/extensionSettings.test.ts | 725 ++++++++++++++++++ .../config/extensions/extensionSettings.ts | 298 +++++++ .../src/config/extensions/gemini-converter.ts | 2 +- packages/cli/src/config/extensions/github.ts | 3 +- .../cli/src/config/extensions/storage.test.ts | 101 +++ packages/cli/src/config/extensions/storage.ts | 40 + .../cli/src/config/extensions/update.test.ts | 7 +- packages/cli/src/config/extensions/update.ts | 3 +- .../cli/src/config/extensions/variables.ts | 7 + packages/cli/src/gemini.test.tsx | 8 +- packages/cli/src/gemini.tsx | 3 +- .../cli/src/services/FileCommandLoader.ts | 2 +- .../cli/src/test-utils/createExtension.ts | 8 +- .../src/ui/hooks/useExtensionUpdates.test.ts | 2 +- packages/core/src/index.ts | 1 + .../token-storage/keychain-token-storage.ts | 66 +- packages/core/src/skills/skill-manager.ts | 64 +- 28 files changed, 1551 insertions(+), 396 deletions(-) create mode 100644 packages/cli/src/config/extensions/consent.ts delete mode 100644 packages/cli/src/config/extensions/converter.test.ts create mode 100644 packages/cli/src/config/extensions/extensionSettings.test.ts create mode 100644 packages/cli/src/config/extensions/extensionSettings.ts create mode 100644 packages/cli/src/config/extensions/storage.test.ts create mode 100644 packages/cli/src/config/extensions/storage.ts diff --git a/package-lock.json b/package-lock.json index 330b90e08c7..9ff9cc0190b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3875,6 +3875,17 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/prompts": { + "version": "2.4.9", + "resolved": "https://registry.npmjs.org/@types/prompts/-/prompts-2.4.9.tgz", + "integrity": "sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "kleur": "^3.0.3" + } + }, "node_modules/@types/prop-types": { "version": "15.7.15", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", @@ -10984,6 +10995,15 @@ "json-buffer": "3.0.1" } }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/ky": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/ky/-/ky-1.8.1.tgz", @@ -13393,6 +13413,19 @@ "dev": true, "license": "MIT" }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -14753,6 +14786,12 @@ "url": "https://github.com/steveukx/git-js?sponsor=1" } }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, "node_modules/slash": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", @@ -17338,6 +17377,7 @@ "ink-spinner": "^5.0.0", "lowlight": "^3.3.0", "open": "^10.1.2", + "prompts": "^2.4.2", "qrcode-terminal": "^0.12.0", "react": "^19.1.0", "read-package-up": "^11.0.0", @@ -17366,6 +17406,7 @@ "@types/diff": "^7.0.2", "@types/dotenv": "^6.1.1", "@types/node": "^20.11.24", + "@types/prompts": "^2.4.9", "@types/react": "^19.1.8", "@types/react-dom": "^19.1.6", "@types/semver": "^7.7.0", diff --git a/packages/cli/package.json b/packages/cli/package.json index f2083fe1993..daffd165902 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -46,6 +46,7 @@ "comment-json": "^4.2.5", "diff": "^7.0.0", "dotenv": "^17.1.0", + "prompts": "^2.4.2", "fzf": "^0.5.2", "glob": "^10.5.0", "highlight.js": "^11.11.1", @@ -79,6 +80,7 @@ "@types/command-exists": "^1.2.3", "@types/diff": "^7.0.2", "@types/dotenv": "^6.1.1", + "@types/prompts": "^2.4.9", "@types/node": "^20.11.24", "@types/react": "^19.1.8", "@types/react-dom": "^19.1.6", diff --git a/packages/cli/src/acp-integration/acpAgent.ts b/packages/cli/src/acp-integration/acpAgent.ts index d56d196db21..e5f27636b11 100644 --- a/packages/cli/src/acp-integration/acpAgent.ts +++ b/packages/cli/src/acp-integration/acpAgent.ts @@ -27,7 +27,8 @@ import { Readable, Writable } from 'node:stream'; import type { LoadedSettings } from '../config/settings.js'; import { SettingScope } from '../config/settings.js'; import { z } from 'zod'; -import { ExtensionStorage, type Extension } from '../config/extension.js'; +import { ExtensionStorage } from '../config/extensions/storage.js'; +import type { Extension } from '../config/extension.js'; import type { CliArgs } from '../config/config.js'; import { loadCliConfig } from '../config/config.js'; import { ExtensionEnablementManager } from '../config/extensions/extensionEnablement.js'; diff --git a/packages/cli/src/commands/extensions/update.ts b/packages/cli/src/commands/extensions/update.ts index bb200e58f9e..e882fa1b3b7 100644 --- a/packages/cli/src/commands/extensions/update.ts +++ b/packages/cli/src/commands/extensions/update.ts @@ -8,9 +8,10 @@ import type { CommandModule } from 'yargs'; import { loadExtensions, annotateActiveExtensions, - ExtensionStorage, requestConsentNonInteractive, } from '../../config/extension.js'; +import { ExtensionStorage } from '../../config/extensions/storage.js'; + import { updateAllUpdatableExtensions, type ExtensionUpdateInfo, diff --git a/packages/cli/src/commands/mcp/list.test.ts b/packages/cli/src/commands/mcp/list.test.ts index 4d9bb083f87..bf186c729ce 100644 --- a/packages/cli/src/commands/mcp/list.test.ts +++ b/packages/cli/src/commands/mcp/list.test.ts @@ -7,7 +7,8 @@ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { listMcpServers } from './list.js'; import { loadSettings } from '../../config/settings.js'; -import { ExtensionStorage, loadExtensions } from '../../config/extension.js'; +import { loadExtensions } from '../../config/extension.js'; +import { ExtensionStorage } from '../../config/extensions/storage.js'; import { createTransport } from '@qwen-code/qwen-code-core'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; diff --git a/packages/cli/src/commands/mcp/list.ts b/packages/cli/src/commands/mcp/list.ts index 09d9bf6394c..46b8806324e 100644 --- a/packages/cli/src/commands/mcp/list.ts +++ b/packages/cli/src/commands/mcp/list.ts @@ -10,7 +10,8 @@ import { loadSettings } from '../../config/settings.js'; import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; import { MCPServerStatus, createTransport } from '@qwen-code/qwen-code-core'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { ExtensionStorage, loadExtensions } from '../../config/extension.js'; +import { loadExtensions } from '../../config/extension.js'; +import { ExtensionStorage } from '../../config/extensions/storage.js'; import { ExtensionEnablementManager } from '../../config/extensions/extensionEnablement.js'; const COLOR_GREEN = '\u001b[32m'; diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 0b95f7857c9..9927438bfaa 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -16,7 +16,8 @@ import { } from '@qwen-code/qwen-code-core'; import { loadCliConfig, parseArguments, type CliArgs } from './config.js'; import type { Settings } from './settings.js'; -import { ExtensionStorage, type Extension } from './extension.js'; +import type { Extension } from './extension.js'; +import { ExtensionStorage } from './extensions/storage.js'; import * as ServerConfig from '@qwen-code/qwen-code-core'; import { isWorkspaceTrusted } from './trustedFolders.js'; import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; diff --git a/packages/cli/src/config/extension.test.ts b/packages/cli/src/config/extension.test.ts index 2bae9c1ec8a..a3a85ee40e5 100644 --- a/packages/cli/src/config/extension.test.ts +++ b/packages/cli/src/config/extension.test.ts @@ -9,9 +9,6 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { - EXTENSIONS_CONFIG_FILENAME, - ExtensionStorage, - INSTALL_METADATA_FILENAME, annotateActiveExtensions, disableExtension, enableExtension, @@ -24,6 +21,11 @@ import { uninstallExtension, type Extension, } from './extension.js'; +import { + INSTALL_METADATA_FILENAME, + EXTENSIONS_CONFIG_FILENAME, +} from './extensions/variables.js'; +import { ExtensionStorage } from './extensions/storage.js'; import { QWEN_DIR, type GeminiCLIExtension, diff --git a/packages/cli/src/config/extension.ts b/packages/cli/src/config/extension.ts index 8942e2e9bd9..32f4a655724 100644 --- a/packages/cli/src/config/extension.ts +++ b/packages/cli/src/config/extension.ts @@ -10,7 +10,6 @@ import type { ExtensionInstallMetadata, } from '@qwen-code/qwen-code-core'; import { - QWEN_DIR, Storage, Config, ExtensionInstallEvent, @@ -27,12 +26,17 @@ import * as path from 'node:path'; import * as os from 'node:os'; import { SettingScope, loadSettings } from '../config/settings.js'; import { getErrorMessage } from '../utils/errors.js'; -import { recursivelyHydrateStrings } from './extensions/variables.js'; +import { + EXTENSIONS_CONFIG_FILENAME, + INSTALL_METADATA_FILENAME, + recursivelyHydrateStrings, +} from './extensions/variables.js'; import { isWorkspaceTrusted } from './trustedFolders.js'; import { resolveEnvVarsInObject } from '../utils/envVarResolver.js'; import { cloneFromGit, downloadFromGitHubRelease, + parseGitHubRepoForReleases, } from './extensions/github.js'; import type { LoadExtensionContext } from './extensions/variableSchema.js'; import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; @@ -48,11 +52,13 @@ import { convertGeminiExtensionPackage, } from './extensions/gemini-converter.js'; import { glob } from 'glob'; - -export const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); - -export const EXTENSIONS_CONFIG_FILENAME = 'qwen-extension.json'; -export const INSTALL_METADATA_FILENAME = '.qwen-extension-install.json'; +import { createHash } from 'node:crypto'; +import { maybeRequestConsentOrFail } from './extensions/consent.js'; +import { ExtensionStorage } from './extensions/storage.js'; +import { + maybePromptForSettings, + promptForSetting, +} from './extensions/extensionSettings.js'; export interface Extension { path: string; @@ -90,34 +96,6 @@ export interface ExtensionUpdateInfo { updatedVersion: string; } -export class ExtensionStorage { - private readonly extensionName: string; - - constructor(extensionName: string) { - this.extensionName = extensionName; - } - - getExtensionDir(): string { - return path.join( - ExtensionStorage.getUserExtensionsDir(), - this.extensionName, - ); - } - - getConfigPath(): string { - return path.join(this.getExtensionDir(), EXTENSIONS_CONFIG_FILENAME); - } - - static getUserExtensionsDir(): string { - const storage = new Storage(os.homedir()); - return storage.getExtensionsDir(); - } - - static async createTmpDir(): Promise { - return await fs.promises.mkdtemp(path.join(os.tmpdir(), 'qwen-extension')); - } -} - export function getWorkspaceExtensions(workspaceDir: string): Extension[] { // If the workspace dir is the user extensions dir, there are no workspace extensions. if (path.resolve(workspaceDir) === path.resolve(os.homedir())) { @@ -585,8 +563,15 @@ export async function installExtension( commands, previousExtensionConfig, ); + const extensionId = getExtensionId(newExtensionConfig, installMetadata); await fs.promises.mkdir(destinationPath, { recursive: true }); + await maybePromptForSettings( + newExtensionConfig, + extensionId, + promptForSetting, + ); + if ( installMetadata.type === 'local' || installMetadata.type === 'git' || @@ -648,78 +633,6 @@ export async function installExtension( } } -/** - * Builds a consent string for installing an extension based on it's - * extensionConfig. - */ -function extensionConsentString( - extensionConfig: ExtensionConfig, - commands?: string[], -): string { - const output: string[] = []; - const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); - output.push(`Installing extension "${extensionConfig.name}".`); - output.push( - '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', - ); - - if (mcpServerEntries.length) { - output.push('This extension will run the following MCP servers:'); - for (const [key, mcpServer] of mcpServerEntries) { - const isLocal = !!mcpServer.command; - const source = - mcpServer.httpUrl ?? - `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; - output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); - } - } - if (commands && commands.length > 0) { - output.push( - `This extension will add the following commands: ${commands.join(', ')}.`, - ); - } - if (extensionConfig.contextFileName) { - output.push( - `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, - ); - } - if (extensionConfig.excludeTools) { - output.push( - `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, - ); - } - return output.join('\n'); -} - -/** - * Requests consent from the user to install an extension (extensionConfig), if - * there is any difference between the consent string for `extensionConfig` and - * `previousExtensionConfig`. - * - * Always requests consent if previousExtensionConfig is null. - * - * Throws if the user does not consent. - */ -async function maybeRequestConsentOrFail( - extensionConfig: ExtensionConfig, - requestConsent: (consent: string) => Promise, - commands: string[], - previousExtensionConfig?: ExtensionConfig, -) { - const extensionConsent = extensionConsentString(extensionConfig, commands); - if (previousExtensionConfig) { - const previousExtensionConsent = extensionConsentString( - previousExtensionConfig, - ); - if (previousExtensionConsent === extensionConsent) { - return; - } - } - if (!(await requestConsent(extensionConsent))) { - throw new Error(`Installation cancelled for "${extensionConfig.name}".`); - } -} - async function loadCommandsFromDir( dir: string, extensionName: string, @@ -801,6 +714,7 @@ export function loadExtensionConfig( '/': path.sep, pathSeparator: path.sep, }) as unknown as ExtensionConfig; + if (!config.name || !config.version) { throw new Error( `Invalid configuration in ${configFilePath}: missing ${!config.name ? '"name"' : '"version"'}`, @@ -941,3 +855,31 @@ export function enableExtension( const config = getTelemetryConfig(cwd); logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); } + +export function getExtensionId( + config: ExtensionConfig, + installMetadata?: ExtensionInstallMetadata, +): string { + // IDs are created by hashing details of the installation source in order to + // deduplicate extensions with conflicting names and also obfuscate any + // potentially sensitive information such as private git urls, system paths, + // or project names. + let idValue = config.name; + const githubUrlParts = + installMetadata && + (installMetadata.type === 'git' || + installMetadata.type === 'github-release') + ? parseGitHubRepoForReleases(installMetadata.source) + : null; + if (githubUrlParts) { + // For github repos, we use the https URI to the repo as the ID. + idValue = `https://github.com/${githubUrlParts.owner}/${githubUrlParts.repo}`; + } else { + idValue = installMetadata?.source ?? config.name; + } + return hashValue(idValue); +} + +export function hashValue(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} diff --git a/packages/cli/src/config/extensions/consent.ts b/packages/cli/src/config/extensions/consent.ts new file mode 100644 index 00000000000..a686188ea1e --- /dev/null +++ b/packages/cli/src/config/extensions/consent.ts @@ -0,0 +1,157 @@ +import type { ConfirmationRequest } from '../../ui/types.js'; +import type { ExtensionConfig } from '../extension.js'; + +/** + * Requests consent from the user to perform an action, by reading a Y/n + * character from stdin. + * + * This should not be called from interactive mode as it will break the CLI. + * + * @param consentDescription The description of the thing they will be consenting to. + * @returns boolean, whether they consented or not. + */ +export async function requestConsentNonInteractive(): Promise { + const result = await promptForConsentNonInteractive( + 'Do you want to continue? [Y/n]: ', + ); + return result; +} + +/** + * Requests consent from the user to perform an action, in interactive mode. + * + * This should not be called from non-interactive mode as it will not work. + * + * @param consentDescription The description of the thing they will be consenting to. + * @param addExtensionUpdateConfirmationRequest A function to actually add a prompt to the UI. + * @returns boolean, whether they consented or not. + */ +export async function requestConsentInteractive( + consentDescription: string, + addExtensionUpdateConfirmationRequest: (value: ConfirmationRequest) => void, +): Promise { + return promptForConsentInteractive( + consentDescription + '\n\nDo you want to continue?', + addExtensionUpdateConfirmationRequest, + ); +} + +/** + * Asks users a prompt and awaits for a y/n response on stdin. + * + * This should not be called from interactive mode as it will break the CLI. + * + * @param prompt A yes/no prompt to ask the user + * @returns Whether or not the user answers 'y' (yes). Defaults to 'yes' on enter. + */ +async function promptForConsentNonInteractive( + prompt: string, +): Promise { + const readline = await import('node:readline'); + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + return new Promise((resolve) => { + rl.question(prompt, (answer) => { + rl.close(); + resolve(['y', ''].includes(answer.trim().toLowerCase())); + }); + }); +} + +/** + * Asks users an interactive yes/no prompt. + * + * This should not be called from non-interactive mode as it will break the CLI. + * + * @param prompt A markdown prompt to ask the user + * @param addExtensionUpdateConfirmationRequest Function to update the UI state with the confirmation request. + * @returns Whether or not the user answers yes. + */ +async function promptForConsentInteractive( + prompt: string, + addExtensionUpdateConfirmationRequest: (value: ConfirmationRequest) => void, +): Promise { + return new Promise((resolve) => { + addExtensionUpdateConfirmationRequest({ + prompt, + onConfirm: (resolvedConfirmed) => { + resolve(resolvedConfirmed); + }, + }); + }); +} + +/** + * Builds a consent string for installing an extension based on it's + * extensionConfig. + */ +export function extensionConsentString( + extensionConfig: ExtensionConfig, + commands?: string[], +): string { + const output: string[] = []; + const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); + output.push(`Installing extension "${extensionConfig.name}".`); + output.push( + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + ); + + if (mcpServerEntries.length) { + output.push('This extension will run the following MCP servers:'); + for (const [key, mcpServer] of mcpServerEntries) { + const isLocal = !!mcpServer.command; + const source = + mcpServer.httpUrl ?? + `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; + output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); + } + } + if (commands && commands.length > 0) { + output.push( + `This extension will add the following commands: ${commands.join(', ')}.`, + ); + } + if (extensionConfig.contextFileName) { + output.push( + `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, + ); + } + if (extensionConfig.excludeTools) { + output.push( + `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, + ); + } + return output.join('\n'); +} + +/** + * Requests consent from the user to install an extension (extensionConfig), if + * there is any difference between the consent string for `extensionConfig` and + * `previousExtensionConfig`. + * + * Always requests consent if previousExtensionConfig is null. + * + * Throws if the user does not consent. + */ +export async function maybeRequestConsentOrFail( + extensionConfig: ExtensionConfig, + requestConsent: (consent: string) => Promise, + commands: string[], + previousExtensionConfig?: ExtensionConfig, +) { + const extensionConsent = extensionConsentString(extensionConfig, commands); + if (previousExtensionConfig) { + const previousExtensionConsent = extensionConsentString( + previousExtensionConfig, + ); + if (previousExtensionConsent === extensionConsent) { + return; + } + } + if (!(await requestConsent(extensionConsent))) { + throw new Error(`Installation cancelled for "${extensionConfig.name}".`); + } +} diff --git a/packages/cli/src/config/extensions/converter.test.ts b/packages/cli/src/config/extensions/converter.test.ts deleted file mode 100644 index 67c3cc2d13b..00000000000 --- a/packages/cli/src/config/extensions/converter.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import { describe, it, expect } from 'vitest'; -import { - isClaudePluginConfig, - convertClaudeToQwenConfig, - mergeClaudeConfigs, - type ClaudePluginConfig, - type ClaudeMarketplacePluginConfig, -} from './claude-converter.js'; -import { - isGeminiExtensionConfig, - convertGeminiToQwenConfig, - type GeminiExtensionConfig, -} from './gemini-converter.js'; -import { parseMarketplaceSource } from './marketplace.js'; - -describe('Claude Converter', () => { - describe('isClaudePluginConfig', () => { - it('should detect Claude plugin config', () => { - const config = { - name: 'test-plugin', - version: '1.0.0', - agents: 'agents/', - hooks: 'hooks.js', - }; - expect(isClaudePluginConfig(config)).toBe(true); - }); - - it('should return false for non-Claude config', () => { - const config = { - name: 'test-plugin', - version: '1.0.0', - commands: 'commands/', - }; - expect(isClaudePluginConfig(config)).toBe(false); - }); - - it('should return false for invalid config', () => { - expect(isClaudePluginConfig(null)).toBe(false); - expect(isClaudePluginConfig('string')).toBe(false); - expect(isClaudePluginConfig({})).toBe(false); - }); - }); - - describe('convertClaudeToQwenConfig', () => { - it('should convert basic Claude config', () => { - const claudeConfig: ClaudePluginConfig = { - name: 'claude-plugin', - version: '1.0.0', - commands: 'commands/', - agents: 'agents/', - }; - - const qwenConfig = convertClaudeToQwenConfig(claudeConfig); - - expect(qwenConfig.name).toBe('claude-plugin'); - expect(qwenConfig.version).toBe('1.0.0'); - expect(qwenConfig.commands).toBe('commands/'); - expect(qwenConfig.agents).toBe('agents/'); - }); - - it('should throw error for invalid config', () => { - expect(() => convertClaudeToQwenConfig({} as ClaudePluginConfig)).toThrow( - 'Claude plugin config must have name and version fields', - ); - }); - }); - - describe('mergeClaudeConfigs', () => { - it('should merge marketplace and plugin configs', () => { - const marketplaceConfig: ClaudeMarketplacePluginConfig = { - name: 'plugin', - version: '2.0.0', - source: 'https://github.com/example/plugin', - description: 'Updated description', - }; - - const pluginConfig: ClaudePluginConfig = { - name: 'plugin', - version: '1.0.0', - description: 'Original description', - commands: 'commands/', - }; - - const merged = mergeClaudeConfigs(marketplaceConfig, pluginConfig); - - expect(merged.name).toBe('plugin'); - expect(merged.version).toBe('2.0.0'); - expect(merged.description).toBe('Updated description'); - expect(merged.commands).toBe('commands/'); - }); - - it('should throw error in strict mode without plugin config', () => { - const marketplaceConfig: ClaudeMarketplacePluginConfig = { - name: 'plugin', - version: '1.0.0', - source: 'https://github.com/example/plugin', - strict: true, - }; - - expect(() => mergeClaudeConfigs(marketplaceConfig)).toThrow( - 'Plugin plugin requires plugin.json (strict mode)', - ); - }); - }); -}); - -describe('Gemini Converter', () => { - describe('isGeminiExtensionConfig', () => { - it('should detect Gemini extension config with settings', () => { - const config = { - name: 'test-extension', - version: '1.0.0', - settings: [ - { - name: 'API Key', - description: 'Your API key', - envVar: 'MY_API_KEY', - }, - ], - }; - expect(isGeminiExtensionConfig(config)).toBe(true); - }); - - it('should return true for basic Gemini config without settings', () => { - const config = { - name: 'test-extension', - version: '1.0.0', - contextFileName: 'QWEN.md', - }; - expect(isGeminiExtensionConfig(config)).toBe(true); - }); - - it('should return false for invalid config', () => { - expect(isGeminiExtensionConfig(null)).toBe(false); - expect(isGeminiExtensionConfig('string')).toBe(false); - expect(isGeminiExtensionConfig({})).toBe(false); - }); - }); - - describe('convertGeminiToQwenConfig', () => { - it('should convert basic Gemini config', () => { - const geminiConfig: GeminiExtensionConfig = { - name: 'gemini-extension', - version: '1.0.0', - commands: 'commands/', - excludeTools: ['tool1', 'tool2'], - }; - - const qwenConfig = convertGeminiToQwenConfig(geminiConfig); - - expect(qwenConfig.name).toBe('gemini-extension'); - expect(qwenConfig.version).toBe('1.0.0'); - expect(qwenConfig.commands).toBe('commands/'); - expect(qwenConfig.excludeTools).toEqual(['tool1', 'tool2']); - }); - - it('should convert config with settings', () => { - const geminiConfig: GeminiExtensionConfig = { - name: 'gemini-extension', - version: '1.0.0', - settings: [ - { - name: 'API Key', - description: 'Your API key', - envVar: 'MY_API_KEY', - sensitive: true, - }, - ], - }; - - const qwenConfig = convertGeminiToQwenConfig(geminiConfig); - - expect(qwenConfig.settings).toEqual(geminiConfig.settings); - }); - - it('should throw error for invalid config', () => { - expect(() => - convertGeminiToQwenConfig({} as GeminiExtensionConfig), - ).toThrow('Gemini extension config must have name and version fields'); - }); - }); -}); - -describe('Marketplace Parser', () => { - describe('parseMarketplaceSource', () => { - it('should parse valid marketplace source', () => { - const result = parseMarketplaceSource( - 'https://github.com/example/marketplace:my-plugin', - ); - expect(result).toEqual({ - marketplaceUrl: 'https://github.com/example/marketplace', - pluginName: 'my-plugin', - }); - }); - - it('should parse HTTP marketplace source', () => { - const result = parseMarketplaceSource( - 'http://example.com/marketplace:plugin-name', - ); - expect(result).toEqual({ - marketplaceUrl: 'http://example.com/marketplace', - pluginName: 'plugin-name', - }); - }); - - it('should handle multiple colons in URL', () => { - const result = parseMarketplaceSource( - 'https://github.com:8080/repo:plugin', - ); - expect(result).toEqual({ - marketplaceUrl: 'https://github.com:8080/repo', - pluginName: 'plugin', - }); - }); - - it('should return null for invalid sources', () => { - expect(parseMarketplaceSource('not-a-url:plugin')).toBeNull(); - expect(parseMarketplaceSource('https://github.com/repo')).toBeNull(); - expect(parseMarketplaceSource('https://github.com/repo:')).toBeNull(); - }); - }); -}); diff --git a/packages/cli/src/config/extensions/extensionSettings.test.ts b/packages/cli/src/config/extensions/extensionSettings.test.ts new file mode 100644 index 00000000000..01fc631352b --- /dev/null +++ b/packages/cli/src/config/extensions/extensionSettings.test.ts @@ -0,0 +1,725 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { + getEnvContents, + maybePromptForSettings, + promptForSetting, + type ExtensionSetting, + updateSetting, + ExtensionSettingScope, + getScopedEnvContents, +} from './extensionSettings.js'; +import type { ExtensionConfig } from '../extension.js'; +import { ExtensionStorage } from './storage.js'; +import prompts from 'prompts'; +import * as fsPromises from 'node:fs/promises'; +import * as fs from 'node:fs'; +import { KeychainTokenStorage } from '@qwen-code/qwen-code-core'; +import { EXTENSION_SETTINGS_FILENAME } from './variables.js'; + +vi.mock('prompts'); +vi.mock('os', async (importOriginal) => { + const mockedOs = await importOriginal(); + return { + ...mockedOs, + homedir: vi.fn(), + }; +}); + +vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + KeychainTokenStorage: vi.fn(), + }; +}); + +describe('extensionSettings', () => { + let tempHomeDir: string; + let tempWorkspaceDir: string; + let extensionDir: string; + let mockKeychainData: Record>; + + beforeEach(() => { + vi.clearAllMocks(); + mockKeychainData = {}; + vi.mocked(KeychainTokenStorage).mockImplementation( + (serviceName: string) => { + if (!mockKeychainData[serviceName]) { + mockKeychainData[serviceName] = {}; + } + const keychainData = mockKeychainData[serviceName]; + return { + getSecret: vi + .fn() + .mockImplementation( + async (key: string) => keychainData[key] || null, + ), + setSecret: vi + .fn() + .mockImplementation(async (key: string, value: string) => { + keychainData[key] = value; + }), + deleteSecret: vi.fn().mockImplementation(async (key: string) => { + delete keychainData[key]; + }), + listSecrets: vi + .fn() + .mockImplementation(async () => Object.keys(keychainData)), + isAvailable: vi.fn().mockResolvedValue(true), + } as unknown as KeychainTokenStorage; + }, + ); + tempHomeDir = os.tmpdir() + path.sep + `gemini-cli-test-home-${Date.now()}`; + tempWorkspaceDir = path.join( + os.tmpdir(), + `gemini-cli-test-workspace-${Date.now()}`, + ); + extensionDir = path.join(tempHomeDir, '.gemini', 'extensions', 'test-ext'); + // Spy and mock the method, but also create the directory so we can write to it. + vi.spyOn(ExtensionStorage.prototype, 'getExtensionDir').mockReturnValue( + extensionDir, + ); + fs.mkdirSync(extensionDir, { recursive: true }); + fs.mkdirSync(tempWorkspaceDir, { recursive: true }); + vi.mocked(os.homedir).mockReturnValue(tempHomeDir); + vi.spyOn(process, 'cwd').mockReturnValue(tempWorkspaceDir); + vi.mocked(prompts).mockClear(); + }); + + afterEach(() => { + fs.rmSync(tempHomeDir, { recursive: true, force: true }); + fs.rmSync(tempWorkspaceDir, { recursive: true, force: true }); + vi.restoreAllMocks(); + }); + + describe('maybePromptForSettings', () => { + const mockRequestSetting = vi.fn( + async (setting: ExtensionSetting) => `mock-${setting.envVar}`, + ); + + beforeEach(() => { + mockRequestSetting.mockClear(); + }); + + it('should do nothing if settings are undefined', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + await maybePromptForSettings( + config, + '12345', + mockRequestSetting, + undefined, + undefined, + ); + expect(mockRequestSetting).not.toHaveBeenCalled(); + }); + + it('should do nothing if settings are empty', async () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [], + }; + await maybePromptForSettings( + config, + '12345', + mockRequestSetting, + undefined, + undefined, + ); + expect(mockRequestSetting).not.toHaveBeenCalled(); + }); + + it('should prompt for all settings if there is no previous config', async () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2' }, + ], + }; + await maybePromptForSettings( + config, + '12345', + mockRequestSetting, + undefined, + undefined, + ); + expect(mockRequestSetting).toHaveBeenCalledTimes(2); + expect(mockRequestSetting).toHaveBeenCalledWith(config.settings![0]); + expect(mockRequestSetting).toHaveBeenCalledWith(config.settings![1]); + }); + + it('should only prompt for new settings', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [{ name: 's1', description: 'd1', envVar: 'VAR1' }], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2' }, + ], + }; + const previousSettings = { VAR1: 'previous-VAR1' }; + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(mockRequestSetting).toHaveBeenCalledTimes(1); + expect(mockRequestSetting).toHaveBeenCalledWith(newConfig.settings![1]); + + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + const expectedContent = 'VAR1=previous-VAR1\nVAR2=mock-VAR2\n'; + expect(actualContent).toBe(expectedContent); + }); + + it('should clear settings if new config has no settings', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { + name: 's2', + description: 'd2', + envVar: 'SENSITIVE_VAR', + sensitive: true, + }, + ], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [], + }; + const previousSettings = { + VAR1: 'previous-VAR1', + SENSITIVE_VAR: 'secret', + }; + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345`, + ); + await userKeychain.setSecret('SENSITIVE_VAR', 'secret'); + const envPath = path.join(extensionDir, '.env'); + await fsPromises.writeFile(envPath, 'VAR1=previous-VAR1'); + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(mockRequestSetting).not.toHaveBeenCalled(); + const actualContent = await fsPromises.readFile(envPath, 'utf-8'); + expect(actualContent).toBe(''); + expect(await userKeychain.getSecret('SENSITIVE_VAR')).toBeNull(); + }); + + it('should remove sensitive settings from keychain', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { + name: 's1', + description: 'd1', + envVar: 'SENSITIVE_VAR', + sensitive: true, + }, + ], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [], + }; + const previousSettings = { SENSITIVE_VAR: 'secret' }; + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345`, + ); + await userKeychain.setSecret('SENSITIVE_VAR', 'secret'); + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(await userKeychain.getSecret('SENSITIVE_VAR')).toBeNull(); + }); + + it('should remove settings that are no longer in the config', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2' }, + ], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [{ name: 's1', description: 'd1', envVar: 'VAR1' }], + }; + const previousSettings = { + VAR1: 'previous-VAR1', + VAR2: 'previous-VAR2', + }; + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(mockRequestSetting).not.toHaveBeenCalled(); + + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + const expectedContent = 'VAR1=previous-VAR1\n'; + expect(actualContent).toBe(expectedContent); + }); + + it('should reprompt if a setting changes sensitivity', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1', sensitive: false }, + ], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1', sensitive: true }, + ], + }; + const previousSettings = { VAR1: 'previous-VAR1' }; + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(mockRequestSetting).toHaveBeenCalledTimes(1); + expect(mockRequestSetting).toHaveBeenCalledWith(newConfig.settings![0]); + + // The value should now be in keychain, not the .env file. + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + expect(actualContent).toBe(''); + }); + + it('should not prompt if settings are identical', async () => { + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2' }, + ], + }; + const newConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2' }, + ], + }; + const previousSettings = { + VAR1: 'previous-VAR1', + VAR2: 'previous-VAR2', + }; + + await maybePromptForSettings( + newConfig, + '12345', + mockRequestSetting, + previousConfig, + previousSettings, + ); + + expect(mockRequestSetting).not.toHaveBeenCalled(); + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + const expectedContent = 'VAR1=previous-VAR1\nVAR2=previous-VAR2\n'; + expect(actualContent).toBe(expectedContent); + }); + + it('should wrap values with spaces in quotes', async () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [{ name: 's1', description: 'd1', envVar: 'VAR1' }], + }; + mockRequestSetting.mockResolvedValue('a value with spaces'); + + await maybePromptForSettings( + config, + '12345', + mockRequestSetting, + undefined, + undefined, + ); + + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + expect(actualContent).toBe('VAR1="a value with spaces"\n'); + }); + + it('should not attempt to clear secrets if keychain is unavailable', async () => { + // Arrange + const mockIsAvailable = vi.fn().mockResolvedValue(false); + const mockListSecrets = vi.fn(); + + vi.mocked(KeychainTokenStorage).mockImplementation( + () => + ({ + isAvailable: mockIsAvailable, + listSecrets: mockListSecrets, + deleteSecret: vi.fn(), + getSecret: vi.fn(), + setSecret: vi.fn(), + }) as unknown as KeychainTokenStorage, + ); + + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [], // Empty settings triggers clearSettings + }; + + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [{ name: 's1', description: 'd1', envVar: 'VAR1' }], + }; + + // Act + await maybePromptForSettings( + config, + '12345', + mockRequestSetting, + previousConfig, + undefined, + ); + + // Assert + expect(mockIsAvailable).toHaveBeenCalled(); + expect(mockListSecrets).not.toHaveBeenCalled(); + }); + }); + + describe('promptForSetting', () => { + it.each([ + { + description: + 'should use prompts with type "password" for sensitive settings', + setting: { + name: 'API Key', + description: 'Your secret key', + envVar: 'API_KEY', + sensitive: true, + }, + expectedType: 'password', + promptValue: 'secret-key', + }, + { + description: + 'should use prompts with type "text" for non-sensitive settings', + setting: { + name: 'Username', + description: 'Your public username', + envVar: 'USERNAME', + sensitive: false, + }, + expectedType: 'text', + promptValue: 'test-user', + }, + { + description: 'should default to "text" if sensitive is undefined', + setting: { + name: 'Username', + description: 'Your public username', + envVar: 'USERNAME', + }, + expectedType: 'text', + promptValue: 'test-user', + }, + ])('$description', async ({ setting, expectedType, promptValue }) => { + vi.mocked(prompts).mockResolvedValue({ value: promptValue }); + + const result = await promptForSetting(setting as ExtensionSetting); + + expect(prompts).toHaveBeenCalledWith({ + type: expectedType, + name: 'value', + message: `${setting.name}\n${setting.description}`, + }); + expect(result).toBe(promptValue); + }); + + it('should return undefined if the user cancels the prompt', async () => { + vi.mocked(prompts).mockResolvedValue({ value: undefined }); + const result = await promptForSetting({ + name: 'Test', + description: 'Test desc', + envVar: 'TEST_VAR', + }); + expect(result).toBeUndefined(); + }); + }); + + describe('getScopedEnvContents', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { + name: 's2', + description: 'd2', + envVar: 'SENSITIVE_VAR', + sensitive: true, + }, + ], + }; + const extensionId = '12345'; + + it('should return combined contents from user .env and keychain for USER scope', async () => { + const userEnvPath = path.join(extensionDir, EXTENSION_SETTINGS_FILENAME); + await fsPromises.writeFile(userEnvPath, 'VAR1=user-value1'); + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345`, + ); + await userKeychain.setSecret('SENSITIVE_VAR', 'user-secret'); + + const contents = await getScopedEnvContents( + config, + extensionId, + ExtensionSettingScope.USER, + ); + + expect(contents).toEqual({ + VAR1: 'user-value1', + SENSITIVE_VAR: 'user-secret', + }); + }); + + it('should return combined contents from workspace .env and keychain for WORKSPACE scope', async () => { + const workspaceEnvPath = path.join( + tempWorkspaceDir, + EXTENSION_SETTINGS_FILENAME, + ); + await fsPromises.writeFile(workspaceEnvPath, 'VAR1=workspace-value1'); + const workspaceKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345 ${tempWorkspaceDir}`, + ); + await workspaceKeychain.setSecret('SENSITIVE_VAR', 'workspace-secret'); + + const contents = await getScopedEnvContents( + config, + extensionId, + ExtensionSettingScope.WORKSPACE, + ); + + expect(contents).toEqual({ + VAR1: 'workspace-value1', + SENSITIVE_VAR: 'workspace-secret', + }); + }); + }); + + describe('getEnvContents (merged)', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2', sensitive: true }, + { name: 's3', description: 'd3', envVar: 'VAR3' }, + ], + }; + const extensionId = '12345'; + + it('should merge user and workspace settings, with workspace taking precedence', async () => { + // User settings + const userEnvPath = path.join(extensionDir, EXTENSION_SETTINGS_FILENAME); + await fsPromises.writeFile( + userEnvPath, + 'VAR1=user-value1\nVAR3=user-value3', + ); + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext ${extensionId}`, + ); + await userKeychain.setSecret('VAR2', 'user-secret2'); + + // Workspace settings + const workspaceEnvPath = path.join( + tempWorkspaceDir, + EXTENSION_SETTINGS_FILENAME, + ); + await fsPromises.writeFile(workspaceEnvPath, 'VAR1=workspace-value1'); + const workspaceKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext ${extensionId} ${tempWorkspaceDir}`, + ); + await workspaceKeychain.setSecret('VAR2', 'workspace-secret2'); + + const contents = await getEnvContents(config, extensionId); + + expect(contents).toEqual({ + VAR1: 'workspace-value1', + VAR2: 'workspace-secret2', + VAR3: 'user-value3', + }); + }); + }); + + describe('updateSetting', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + settings: [ + { name: 's1', description: 'd1', envVar: 'VAR1' }, + { name: 's2', description: 'd2', envVar: 'VAR2', sensitive: true }, + ], + }; + const mockRequestSetting = vi.fn(); + + beforeEach(async () => { + const userEnvPath = path.join(extensionDir, '.env'); + await fsPromises.writeFile(userEnvPath, 'VAR1=value1\n'); + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345`, + ); + await userKeychain.setSecret('VAR2', 'value2'); + mockRequestSetting.mockClear(); + }); + + it('should update a non-sensitive setting in USER scope', async () => { + mockRequestSetting.mockResolvedValue('new-value1'); + + await updateSetting( + config, + '12345', + 'VAR1', + mockRequestSetting, + ExtensionSettingScope.USER, + ); + + const expectedEnvPath = path.join(extensionDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + expect(actualContent).toContain('VAR1=new-value1'); + }); + + it('should update a non-sensitive setting in WORKSPACE scope', async () => { + mockRequestSetting.mockResolvedValue('new-workspace-value'); + + await updateSetting( + config, + '12345', + 'VAR1', + mockRequestSetting, + ExtensionSettingScope.WORKSPACE, + ); + + const expectedEnvPath = path.join(tempWorkspaceDir, '.env'); + const actualContent = await fsPromises.readFile(expectedEnvPath, 'utf-8'); + expect(actualContent).toContain('VAR1=new-workspace-value'); + }); + + it('should update a sensitive setting in USER scope', async () => { + mockRequestSetting.mockResolvedValue('new-value2'); + + await updateSetting( + config, + '12345', + 'VAR2', + mockRequestSetting, + ExtensionSettingScope.USER, + ); + + const userKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345`, + ); + expect(await userKeychain.getSecret('VAR2')).toBe('new-value2'); + }); + + it('should update a sensitive setting in WORKSPACE scope', async () => { + mockRequestSetting.mockResolvedValue('new-workspace-secret'); + + await updateSetting( + config, + '12345', + 'VAR2', + mockRequestSetting, + ExtensionSettingScope.WORKSPACE, + ); + + const workspaceKeychain = new KeychainTokenStorage( + `Gemini CLI Extensions test-ext 12345 ${tempWorkspaceDir}`, + ); + expect(await workspaceKeychain.getSecret('VAR2')).toBe( + 'new-workspace-secret', + ); + }); + + it('should leave existing, unmanaged .env variables intact when updating in WORKSPACE scope', async () => { + // Setup a pre-existing .env file in the workspace with unmanaged variables + const workspaceEnvPath = path.join(tempWorkspaceDir, '.env'); + const originalEnvContent = + 'PROJECT_VAR_1=value_1\nPROJECT_VAR_2=value_2\nVAR1=original-value'; // VAR1 is managed by extension + await fsPromises.writeFile(workspaceEnvPath, originalEnvContent); + + // Simulate updating an extension-managed non-sensitive setting + mockRequestSetting.mockResolvedValue('updated-value'); + await updateSetting( + config, + '12345', + 'VAR1', + mockRequestSetting, + ExtensionSettingScope.WORKSPACE, + ); + + // Read the .env file after update + const actualContent = await fsPromises.readFile( + workspaceEnvPath, + 'utf-8', + ); + + // Assert that original variables are intact and extension variable is updated + expect(actualContent).toContain('PROJECT_VAR_1=value_1'); + expect(actualContent).toContain('PROJECT_VAR_2=value_2'); + expect(actualContent).toContain('VAR1=updated-value'); + + // Ensure no other unexpected changes or deletions + const lines = actualContent.split('\n').filter((line) => line.length > 0); + expect(lines).toHaveLength(3); // Should only have the three variables + }); + }); +}); diff --git a/packages/cli/src/config/extensions/extensionSettings.ts b/packages/cli/src/config/extensions/extensionSettings.ts new file mode 100644 index 00000000000..13561180d29 --- /dev/null +++ b/packages/cli/src/config/extensions/extensionSettings.ts @@ -0,0 +1,298 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs/promises'; +import * as fsSync from 'node:fs'; +import * as dotenv from 'dotenv'; +import * as path from 'node:path'; +import { ExtensionStorage } from './storage.js'; +import type { ExtensionConfig } from '../extension.js'; +import prompts from 'prompts'; +import { EXTENSION_SETTINGS_FILENAME } from './variables.js'; +import { KeychainTokenStorage } from '@qwen-code/qwen-code-core'; + +export enum ExtensionSettingScope { + USER = 'user', + WORKSPACE = 'workspace', +} + +export interface ExtensionSetting { + name: string; + description: string; + envVar: string; + // NOTE: If no value is set, this setting will be considered NOT sensitive. + sensitive?: boolean; +} + +const getKeychainStorageName = ( + extensionName: string, + extensionId: string, + scope: ExtensionSettingScope, +): string => { + const base = `Qwen Code Extensions ${extensionName} ${extensionId}`; + if (scope === ExtensionSettingScope.WORKSPACE) { + return `${base} ${process.cwd()}`; + } + return base; +}; + +const getEnvFilePath = ( + extensionName: string, + scope: ExtensionSettingScope, +): string => { + if (scope === ExtensionSettingScope.WORKSPACE) { + return path.join(process.cwd(), EXTENSION_SETTINGS_FILENAME); + } + return new ExtensionStorage(extensionName).getEnvFilePath(); +}; + +export async function maybePromptForSettings( + extensionConfig: ExtensionConfig, + extensionId: string, + requestSetting: (setting: ExtensionSetting) => Promise, + previousExtensionConfig?: ExtensionConfig, + previousSettings?: Record, +): Promise { + const { name: extensionName, settings } = extensionConfig; + if ( + (!settings || settings.length === 0) && + (!previousExtensionConfig?.settings || + previousExtensionConfig.settings.length === 0) + ) { + return; + } + // We assume user scope here because we don't have a way to ask the user for scope during the initial setup. + // The user can change the scope later using the `settings set` command. + const scope = ExtensionSettingScope.USER; + const envFilePath = getEnvFilePath(extensionName, scope); + const keychain = new KeychainTokenStorage( + getKeychainStorageName(extensionName, extensionId, scope), + ); + + if (!settings || settings.length === 0) { + await clearSettings(envFilePath, keychain); + return; + } + + const settingsChanges = getSettingsChanges( + settings, + previousExtensionConfig?.settings ?? [], + ); + + const allSettings: Record = { ...previousSettings }; + + for (const removedEnvSetting of settingsChanges.removeEnv) { + delete allSettings[removedEnvSetting.envVar]; + } + + for (const removedSensitiveSetting of settingsChanges.removeSensitive) { + await keychain.deleteSecret(removedSensitiveSetting.envVar); + } + + for (const setting of settingsChanges.promptForSensitive.concat( + settingsChanges.promptForEnv, + )) { + const answer = await requestSetting(setting); + allSettings[setting.envVar] = answer; + } + + const nonSensitiveSettings: Record = {}; + for (const setting of settings) { + const value = allSettings[setting.envVar]; + if (value === undefined) { + continue; + } + if (setting.sensitive) { + await keychain.setSecret(setting.envVar, value); + } else { + nonSensitiveSettings[setting.envVar] = value; + } + } + + const envContent = formatEnvContent(nonSensitiveSettings); + + await fs.writeFile(envFilePath, envContent); +} + +function formatEnvContent(settings: Record): string { + let envContent = ''; + for (const [key, value] of Object.entries(settings)) { + const formattedValue = value.includes(' ') ? `"${value}"` : value; + envContent += `${key}=${formattedValue}\n`; + } + return envContent; +} + +export async function promptForSetting( + setting: ExtensionSetting, +): Promise { + const response = await prompts({ + type: setting.sensitive ? 'password' : 'text', + name: 'value', + message: `${setting.name}\n${setting.description}`, + }); + return response.value; +} + +export async function getScopedEnvContents( + extensionConfig: ExtensionConfig, + extensionId: string, + scope: ExtensionSettingScope, +): Promise> { + const { name: extensionName } = extensionConfig; + const keychain = new KeychainTokenStorage( + getKeychainStorageName(extensionName, extensionId, scope), + ); + const envFilePath = getEnvFilePath(extensionName, scope); + let customEnv: Record = {}; + if (fsSync.existsSync(envFilePath)) { + const envFile = fsSync.readFileSync(envFilePath, 'utf-8'); + customEnv = dotenv.parse(envFile); + } + + if (extensionConfig.settings) { + for (const setting of extensionConfig.settings) { + if (setting.sensitive) { + const secret = await keychain.getSecret(setting.envVar); + if (secret) { + customEnv[setting.envVar] = secret; + } + } + } + } + return customEnv; +} + +export async function getEnvContents( + extensionConfig: ExtensionConfig, + extensionId: string, +): Promise> { + if (!extensionConfig.settings || extensionConfig.settings.length === 0) { + return Promise.resolve({}); + } + + const userSettings = await getScopedEnvContents( + extensionConfig, + extensionId, + ExtensionSettingScope.USER, + ); + const workspaceSettings = await getScopedEnvContents( + extensionConfig, + extensionId, + ExtensionSettingScope.WORKSPACE, + ); + + return { ...userSettings, ...workspaceSettings }; +} + +export async function updateSetting( + extensionConfig: ExtensionConfig, + extensionId: string, + settingKey: string, + requestSetting: (setting: ExtensionSetting) => Promise, + scope: ExtensionSettingScope, +): Promise { + const { name: extensionName, settings } = extensionConfig; + if (!settings || settings.length === 0) { + console.log('This extension does not have any settings.'); + return; + } + + const settingToUpdate = settings.find( + (s) => s.name === settingKey || s.envVar === settingKey, + ); + + if (!settingToUpdate) { + console.log(`Setting ${settingKey} not found.`); + return; + } + + const newValue = await requestSetting(settingToUpdate); + const keychain = new KeychainTokenStorage( + getKeychainStorageName(extensionName, extensionId, scope), + ); + + if (settingToUpdate.sensitive) { + await keychain.setSecret(settingToUpdate.envVar, newValue); + return; + } + + // For non-sensitive settings, we need to read the existing .env file, + // update the value, and write it back, preserving any other values. + const envFilePath = getEnvFilePath(extensionName, scope); + let envContent = ''; + if (fsSync.existsSync(envFilePath)) { + envContent = await fs.readFile(envFilePath, 'utf-8'); + } + + const parsedEnv = dotenv.parse(envContent); + parsedEnv[settingToUpdate.envVar] = newValue; + + // We only want to write back the variables that are not sensitive. + const nonSensitiveSettings: Record = {}; + const sensitiveEnvVars = new Set( + settings.filter((s) => s.sensitive).map((s) => s.envVar), + ); + for (const [key, value] of Object.entries(parsedEnv)) { + if (!sensitiveEnvVars.has(key)) { + nonSensitiveSettings[key] = value; + } + } + + const newEnvContent = formatEnvContent(nonSensitiveSettings); + await fs.writeFile(envFilePath, newEnvContent); +} + +interface settingsChanges { + promptForSensitive: ExtensionSetting[]; + removeSensitive: ExtensionSetting[]; + promptForEnv: ExtensionSetting[]; + removeEnv: ExtensionSetting[]; +} +function getSettingsChanges( + settings: ExtensionSetting[], + oldSettings: ExtensionSetting[], +): settingsChanges { + const isSameSetting = (a: ExtensionSetting, b: ExtensionSetting) => + a.envVar === b.envVar && (a.sensitive ?? false) === (b.sensitive ?? false); + + const sensitiveOld = oldSettings.filter((s) => s.sensitive ?? false); + const sensitiveNew = settings.filter((s) => s.sensitive ?? false); + const envOld = oldSettings.filter((s) => !(s.sensitive ?? false)); + const envNew = settings.filter((s) => !(s.sensitive ?? false)); + + return { + promptForSensitive: sensitiveNew.filter( + (s) => !sensitiveOld.some((old) => isSameSetting(s, old)), + ), + removeSensitive: sensitiveOld.filter( + (s) => !sensitiveNew.some((neu) => isSameSetting(s, neu)), + ), + promptForEnv: envNew.filter( + (s) => !envOld.some((old) => isSameSetting(s, old)), + ), + removeEnv: envOld.filter( + (s) => !envNew.some((neu) => isSameSetting(s, neu)), + ), + }; +} + +async function clearSettings( + envFilePath: string, + keychain: KeychainTokenStorage, +) { + if (fsSync.existsSync(envFilePath)) { + await fs.writeFile(envFilePath, ''); + } + if (!(await keychain.isAvailable())) { + return; + } + const secrets = await keychain.listSecrets(); + for (const secret of secrets) { + await keychain.deleteSecret(secret); + } + return; +} diff --git a/packages/cli/src/config/extensions/gemini-converter.ts b/packages/cli/src/config/extensions/gemini-converter.ts index 2aa0b7a749c..ccba248f3ca 100644 --- a/packages/cli/src/config/extensions/gemini-converter.ts +++ b/packages/cli/src/config/extensions/gemini-converter.ts @@ -12,7 +12,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { glob } from 'glob'; import type { ExtensionConfig, ExtensionSetting } from '../extension.js'; -import { ExtensionStorage } from '../extension.js'; +import { ExtensionStorage } from '../extensions/storage.js'; import { convertTomlToMarkdown } from '../../services/toml-to-markdown-converter.js'; export interface GeminiExtensionConfig { diff --git a/packages/cli/src/config/extensions/github.ts b/packages/cli/src/config/extensions/github.ts index 9bdcb6486f2..4db75c18aee 100644 --- a/packages/cli/src/config/extensions/github.ts +++ b/packages/cli/src/config/extensions/github.ts @@ -15,7 +15,8 @@ import * as os from 'node:os'; import * as https from 'node:https'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { EXTENSIONS_CONFIG_FILENAME, loadExtension } from '../extension.js'; +import { loadExtension } from '../extension.js'; +import { EXTENSIONS_CONFIG_FILENAME } from './variables.js'; import * as tar from 'tar'; import extract from 'extract-zip'; diff --git a/packages/cli/src/config/extensions/storage.test.ts b/packages/cli/src/config/extensions/storage.test.ts new file mode 100644 index 00000000000..4f392f94e64 --- /dev/null +++ b/packages/cli/src/config/extensions/storage.test.ts @@ -0,0 +1,101 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { ExtensionStorage } from './storage.js'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as fs from 'node:fs'; +import { + EXTENSION_SETTINGS_FILENAME, + EXTENSIONS_CONFIG_FILENAME, +} from './variables.js'; +import { Storage } from '@qwen-code/qwen-code-core'; + +vi.mock('node:os'); +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + promises: { + ...actual.promises, + mkdtemp: vi.fn(), + }, + }; +}); +vi.mock('@google/gemini-cli-core'); + +describe('ExtensionStorage', () => { + const mockHomeDir = '/mock/home'; + const extensionName = 'test-extension'; + let storage: ExtensionStorage; + + beforeEach(() => { + vi.mocked(os.homedir).mockReturnValue(mockHomeDir); + vi.mocked(Storage).mockImplementation( + () => + ({ + getExtensionsDir: () => + path.join(mockHomeDir, '.gemini', 'extensions'), + }) as any, // eslint-disable-line @typescript-eslint/no-explicit-any + ); + storage = new ExtensionStorage(extensionName); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should return the correct extension directory', () => { + const expectedDir = path.join( + mockHomeDir, + '.gemini', + 'extensions', + extensionName, + ); + expect(storage.getExtensionDir()).toBe(expectedDir); + }); + + it('should return the correct config path', () => { + const expectedPath = path.join( + mockHomeDir, + '.gemini', + 'extensions', + extensionName, + EXTENSIONS_CONFIG_FILENAME, // EXTENSIONS_CONFIG_FILENAME + ); + expect(storage.getConfigPath()).toBe(expectedPath); + }); + + it('should return the correct env file path', () => { + const expectedPath = path.join( + mockHomeDir, + '.gemini', + 'extensions', + extensionName, + EXTENSION_SETTINGS_FILENAME, // EXTENSION_SETTINGS_FILENAME + ); + expect(storage.getEnvFilePath()).toBe(expectedPath); + }); + + it('should return the correct user extensions directory', () => { + const expectedDir = path.join(mockHomeDir, '.gemini', 'extensions'); + expect(ExtensionStorage.getUserExtensionsDir()).toBe(expectedDir); + }); + + it('should create a temporary directory', async () => { + const mockTmpDir = '/tmp/gemini-extension-123'; + vi.mocked(fs.promises.mkdtemp).mockResolvedValue(mockTmpDir); + vi.mocked(os.tmpdir).mockReturnValue('/tmp'); + + const result = await ExtensionStorage.createTmpDir(); + + expect(fs.promises.mkdtemp).toHaveBeenCalledWith( + path.join('/tmp', 'gemini-extension'), + ); + expect(result).toBe(mockTmpDir); + }); +}); diff --git a/packages/cli/src/config/extensions/storage.ts b/packages/cli/src/config/extensions/storage.ts new file mode 100644 index 00000000000..fec7b38d456 --- /dev/null +++ b/packages/cli/src/config/extensions/storage.ts @@ -0,0 +1,40 @@ +import { Storage } from '@qwen-code/qwen-code-core'; +import path from 'node:path'; +import * as os from 'node:os'; +import { + EXTENSION_SETTINGS_FILENAME, + EXTENSIONS_CONFIG_FILENAME, +} from './variables.js'; +import * as fs from 'node:fs'; + +export class ExtensionStorage { + private readonly extensionName: string; + + constructor(extensionName: string) { + this.extensionName = extensionName; + } + + getExtensionDir(): string { + return path.join( + ExtensionStorage.getUserExtensionsDir(), + this.extensionName, + ); + } + + getConfigPath(): string { + return path.join(this.getExtensionDir(), EXTENSIONS_CONFIG_FILENAME); + } + + getEnvFilePath(): string { + return path.join(this.getExtensionDir(), EXTENSION_SETTINGS_FILENAME); + } + + static getUserExtensionsDir(): string { + const storage = new Storage(os.homedir()); + return storage.getExtensionsDir(); + } + + static async createTmpDir(): Promise { + return await fs.promises.mkdtemp(path.join(os.tmpdir(), 'qwen-extension')); + } +} diff --git a/packages/cli/src/config/extensions/update.test.ts b/packages/cli/src/config/extensions/update.test.ts index 849857e4d1b..f7eea8d392b 100644 --- a/packages/cli/src/config/extensions/update.test.ts +++ b/packages/cli/src/config/extensions/update.test.ts @@ -8,13 +8,12 @@ import { vi } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import { annotateActiveExtensions, loadExtension } from '../extension.js'; import { EXTENSIONS_CONFIG_FILENAME, - ExtensionStorage, INSTALL_METADATA_FILENAME, - annotateActiveExtensions, - loadExtension, -} from '../extension.js'; +} from './variables.js'; +import { ExtensionStorage } from './storage.js'; import { checkForAllExtensionUpdates, updateExtension } from './update.js'; import { QWEN_DIR } from '@qwen-code/qwen-code-core'; import { isWorkspaceTrusted } from '../trustedFolders.js'; diff --git a/packages/cli/src/config/extensions/update.ts b/packages/cli/src/config/extensions/update.ts index d74be540f57..16f298a0275 100644 --- a/packages/cli/src/config/extensions/update.ts +++ b/packages/cli/src/config/extensions/update.ts @@ -15,13 +15,14 @@ import { uninstallExtension, loadExtension, loadInstallMetadata, - ExtensionStorage, loadExtensionConfig, } from '../extension.js'; + import { checkForExtensionUpdate } from './github.js'; import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; import * as fs from 'node:fs'; import { getErrorMessage } from '../../utils/errors.js'; +import { ExtensionStorage } from './storage.js'; export interface ExtensionUpdateInfo { name: string; diff --git a/packages/cli/src/config/extensions/variables.ts b/packages/cli/src/config/extensions/variables.ts index 7c6ef846924..f905eea60f3 100644 --- a/packages/cli/src/config/extensions/variables.ts +++ b/packages/cli/src/config/extensions/variables.ts @@ -5,6 +5,13 @@ */ import { type VariableSchema, VARIABLE_SCHEMA } from './variableSchema.js'; +import path from 'node:path'; +import { QWEN_DIR } from '@qwen-code/qwen-code-core'; + +export const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); +export const EXTENSIONS_CONFIG_FILENAME = 'qwen-extension.json'; +export const INSTALL_METADATA_FILENAME = '.qwen-extension-install.json'; +export const EXTENSION_SETTINGS_FILENAME = '.env'; export type JsonObject = { [key: string]: JsonValue }; export type JsonArray = JsonValue[]; diff --git a/packages/cli/src/gemini.test.tsx b/packages/cli/src/gemini.test.tsx index 9fa0b8261f1..ad74bd279bd 100644 --- a/packages/cli/src/gemini.test.tsx +++ b/packages/cli/src/gemini.test.tsx @@ -263,6 +263,7 @@ describe('gemini.tsx main function', () => { const { loadSettings } = await import('./config/settings.js'); const cleanupModule = await import('./utils/cleanup.js'); const extensionModule = await import('./config/extension.js'); + const { ExtensionStorage } = await import('./config/extensions/storage.js'); const validatorModule = await import('./validateNonInterActiveAuth.js'); const streamJsonModule = await import('./nonInteractive/session.js'); const initializerModule = await import('./core/initializer.js'); @@ -276,10 +277,9 @@ describe('gemini.tsx main function', () => { const runExitCleanupMock = vi.mocked(cleanupModule.runExitCleanup); runExitCleanupMock.mockResolvedValue(undefined); vi.spyOn(extensionModule, 'loadExtensions').mockReturnValue([]); - vi.spyOn( - extensionModule.ExtensionStorage, - 'getUserExtensionsDir', - ).mockReturnValue('/tmp/extensions'); + vi.spyOn(ExtensionStorage, 'getUserExtensionsDir').mockReturnValue( + '/tmp/extensions', + ); vi.spyOn(initializerModule, 'initializeApp').mockResolvedValue({ authError: null, themeError: null, diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index b05f1245379..b9dfb09a9e0 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -15,7 +15,8 @@ import React from 'react'; import { validateAuthMethod } from './config/auth.js'; import * as cliConfig from './config/config.js'; import { loadCliConfig, parseArguments } from './config/config.js'; -import { ExtensionStorage, loadExtensions } from './config/extension.js'; +import { loadExtensions } from './config/extension.js'; +import { ExtensionStorage } from './config/extensions/storage.js'; import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js'; import { loadSettings, migrateDeprecatedSettings } from './config/settings.js'; import { diff --git a/packages/cli/src/services/FileCommandLoader.ts b/packages/cli/src/services/FileCommandLoader.ts index 38ae44ab196..8095a72e306 100644 --- a/packages/cli/src/services/FileCommandLoader.ts +++ b/packages/cli/src/services/FileCommandLoader.ts @@ -22,7 +22,7 @@ import { type CommandDefinition, } from './command-factory.js'; import type { SlashCommand } from '../ui/commands/types.js'; -import { EXTENSIONS_CONFIG_FILENAME } from '../config/extension.js'; +import { EXTENSIONS_CONFIG_FILENAME } from '../config/extensions/variables.js'; interface CommandDirectory { path: string; diff --git a/packages/cli/src/test-utils/createExtension.ts b/packages/cli/src/test-utils/createExtension.ts index cf20c4889b4..7366c3cf665 100644 --- a/packages/cli/src/test-utils/createExtension.ts +++ b/packages/cli/src/test-utils/createExtension.ts @@ -6,14 +6,14 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { - EXTENSIONS_CONFIG_FILENAME, - INSTALL_METADATA_FILENAME, -} from '../config/extension.js'; import { type MCPServerConfig, type ExtensionInstallMetadata, } from '@qwen-code/qwen-code-core'; +import { + EXTENSIONS_CONFIG_FILENAME, + INSTALL_METADATA_FILENAME, +} from '../config/extensions/variables.js'; export function createExtension({ extensionsDir = 'extensions-dir', diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts index 29428e8d8d1..80640fa0db7 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts @@ -9,10 +9,10 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { - ExtensionStorage, annotateActiveExtensions, loadExtension, } from '../../config/extension.js'; +import { ExtensionStorage } from '../../config/extensions/storage.js'; import { createExtension } from '../../test-utils/createExtension.js'; import { useExtensionUpdates } from './useExtensionUpdates.js'; import { QWEN_DIR, type GeminiCLIExtension } from '@qwen-code/qwen-code-core'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 56680403b89..36656b9b2a7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -115,6 +115,7 @@ export type { OAuthCredentials, } from './mcp/token-storage/types.js'; export { MCPOAuthTokenStorage } from './mcp/oauth-token-storage.js'; +export { KeychainTokenStorage } from './mcp/token-storage/keychain-token-storage.js'; export type { MCPOAuthConfig } from './mcp/oauth-provider.js'; export type { OAuthAuthorizationServerMetadata, diff --git a/packages/core/src/mcp/token-storage/keychain-token-storage.ts b/packages/core/src/mcp/token-storage/keychain-token-storage.ts index 70eccbadf53..4f7397967fd 100644 --- a/packages/core/src/mcp/token-storage/keychain-token-storage.ts +++ b/packages/core/src/mcp/token-storage/keychain-token-storage.ts @@ -22,6 +22,7 @@ interface Keytar { } const KEYCHAIN_TEST_PREFIX = '__keychain_test__'; +const SECRET_PREFIX = '__secret__'; export class KeychainTokenStorage extends BaseTokenStorage { private keychainAvailable: boolean | null = null; @@ -137,6 +138,7 @@ export class KeychainTokenStorage extends BaseTokenStorage { const credentials = await keytar.findCredentials(this.serviceName); return credentials .filter((cred) => !cred.account.startsWith(KEYCHAIN_TEST_PREFIX)) + .filter((cred) => !cred.account.startsWith(SECRET_PREFIX)) .map((cred: { account: string }) => cred.account); } catch (error) { console.error('Failed to list servers from keychain:', error); @@ -156,9 +158,9 @@ export class KeychainTokenStorage extends BaseTokenStorage { const result = new Map(); try { - const credentials = ( - await keytar.findCredentials(this.serviceName) - ).filter((c) => !c.account.startsWith(KEYCHAIN_TEST_PREFIX)); + const credentials = (await keytar.findCredentials(this.serviceName)) + .filter((c) => !c.account.startsWith(KEYCHAIN_TEST_PREFIX)) + .filter((c) => !c.account.startsWith(SECRET_PREFIX)); for (const cred of credentials) { try { @@ -248,4 +250,62 @@ export class KeychainTokenStorage extends BaseTokenStorage { async isAvailable(): Promise { return this.checkKeychainAvailability(); } + + async setSecret(key: string, value: string): Promise { + if (!(await this.checkKeychainAvailability())) { + throw new Error('Keychain is not available'); + } + const keytar = await this.getKeytar(); + if (!keytar) { + throw new Error('Keytar module not available'); + } + await keytar.setPassword(this.serviceName, `${SECRET_PREFIX}${key}`, value); + } + + async getSecret(key: string): Promise { + if (!(await this.checkKeychainAvailability())) { + throw new Error('Keychain is not available'); + } + const keytar = await this.getKeytar(); + if (!keytar) { + throw new Error('Keytar module not available'); + } + return keytar.getPassword(this.serviceName, `${SECRET_PREFIX}${key}`); + } + + async deleteSecret(key: string): Promise { + if (!(await this.checkKeychainAvailability())) { + throw new Error('Keychain is not available'); + } + const keytar = await this.getKeytar(); + if (!keytar) { + throw new Error('Keytar module not available'); + } + const deleted = await keytar.deletePassword( + this.serviceName, + `${SECRET_PREFIX}${key}`, + ); + if (!deleted) { + throw new Error(`No secret found for key: ${key}`); + } + } + + async listSecrets(): Promise { + if (!(await this.checkKeychainAvailability())) { + throw new Error('Keychain is not available'); + } + const keytar = await this.getKeytar(); + if (!keytar) { + throw new Error('Keytar module not available'); + } + try { + const credentials = await keytar.findCredentials(this.serviceName); + return credentials + .filter((cred) => cred.account.startsWith(SECRET_PREFIX)) + .map((cred) => cred.account.substring(SECRET_PREFIX.length)); + } catch (error) { + console.error('Failed to list secrets from keychain:', error); + return []; + } + } } diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 7a693add39c..27810fb4095 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -320,38 +320,38 @@ export class SkillManager { * @param dir - provided directory * @returns Array of skill configurations */ - async parseSkillsFromDir(dir: string): Promise { - const discoveredSkills: SkillConfig[] = []; - - try { - const absoluteSearchPath = path.resolve(dir); - const stats = await fs.stat(absoluteSearchPath).catch(() => null); - if (!stats || !stats.isDirectory()) { - return []; - } - - const skillFiles = await glob('*/SKILL.md', { - cwd: absoluteSearchPath, - absolute: true, - nodir: true, - }); - - for (const skillFile of skillFiles) { - const metadata = await this.parseSkillFile(skillFile, 'extension'); - if (metadata) { - discoveredSkills.push(metadata); - } - } - } catch (error) { - coreEvents.emitFeedback( - 'warning', - `Error discovering skills in ${dir}:`, - error, - ); - } - - return discoveredSkills; - } + // async parseSkillsFromDir(dir: string): Promise { + // const discoveredSkills: SkillConfig[] = []; + + // try { + // const absoluteSearchPath = path.resolve(dir); + // const stats = await fs.stat(absoluteSearchPath).catch(() => null); + // if (!stats || !stats.isDirectory()) { + // return []; + // } + + // const skillFiles = await glob('*/SKILL.md', { + // cwd: absoluteSearchPath, + // absolute: true, + // nodir: true, + // }); + + // for (const skillFile of skillFiles) { + // const metadata = await this.parseSkillFile(skillFile, 'extension'); + // if (metadata) { + // discoveredSkills.push(metadata); + // } + // } + // } catch (error) { + // coreEvents.emitFeedback( + // 'warning', + // `Error discovering skills in ${dir}:`, + // error, + // ); + // } + + // return discoveredSkills; + // } /** * Parses a SKILL.md file and returns the configuration. From 551e5469742c15f16435c2a5795febcb57c5de24 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 14 Jan 2026 15:30:27 +0800 Subject: [PATCH 05/30] feat: move extension to core package --- packages/cli/src/acp-integration/acpAgent.ts | 19 +- .../extensions/consent.ts | 78 +- .../cli/src/commands/extensions/disable.ts | 13 +- .../cli/src/commands/extensions/enable.ts | 14 +- .../cli/src/commands/extensions/install.ts | 92 +- packages/cli/src/commands/extensions/link.ts | 15 +- packages/cli/src/commands/extensions/list.ts | 10 +- .../cli/src/commands/extensions/uninstall.ts | 16 +- .../cli/src/commands/extensions/update.ts | 65 +- packages/cli/src/commands/extensions/utils.ts | 21 + packages/cli/src/commands/mcp/list.ts | 43 +- packages/cli/src/config/config.ts | 175 +-- packages/cli/src/config/extension.ts | 885 ----------- .../src/config/extensions/claude-converter.ts | 181 --- .../extensions/extensionEnablement.test.ts | 424 ------ .../config/extensions/extensionEnablement.ts | 239 --- .../cli/src/config/extensions/update.test.ts | 467 ------ packages/cli/src/config/extensions/update.ts | 183 --- packages/cli/src/config/settings.test.ts | 121 -- packages/cli/src/config/settings.ts | 27 - packages/cli/src/config/settingsSchema.ts | 42 - packages/cli/src/gemini.test.tsx | 6 - packages/cli/src/gemini.tsx | 38 +- .../src/services/command-migration-tool.ts | 2 +- packages/cli/src/ui/AppContainer.test.tsx | 9 - packages/cli/src/ui/AppContainer.tsx | 39 +- .../cli/src/ui/commands/extensionsCommand.ts | 87 +- .../ui/components/views/ExtensionsList.tsx | 28 +- .../cli/src/ui/contexts/UIActionsContext.tsx | 2 - .../cli/src/ui/contexts/UIStateContext.tsx | 3 - .../src/ui/hooks/useExtensionUpdates.test.ts | 8 +- .../cli/src/ui/hooks/useExtensionUpdates.ts | 94 +- .../cli/src/ui/hooks/useWorkspaceMigration.ts | 70 - packages/cli/src/ui/state/extensions.ts | 1 + packages/cli/src/utils/envVarResolver.ts | 26 +- packages/cli/tsconfig.json | 4 +- packages/core/src/config/config.ts | 191 ++- .../src/extension}/claude-converter.test.ts | 30 +- .../core/src/extension/claude-converter.ts | 500 ++++++ .../src/extension/extensionManager.test.ts} | 0 .../core/src/extension/extensionManager.ts | 1338 +++++++++++++++++ .../src/extension}/extensionSettings.test.ts | 4 +- .../src/extension}/extensionSettings.ts | 4 +- .../src/extension}/gemini-converter.test.ts | 0 .../src/extension}/gemini-converter.ts | 6 +- .../src/extension}/github.test.ts | 2 +- .../src/extension}/github.ts | 127 +- .../src/extension}/marketplace.test.ts | 10 +- .../src/extension}/marketplace.ts | 12 +- packages/core/src/extension/override.test.ts | 110 ++ packages/core/src/extension/override.ts | 102 ++ .../src/extension}/settings.test.ts | 2 +- .../src/extension}/settings.ts | 2 +- .../src/extension}/storage.test.ts | 0 .../src/extension}/storage.ts | 0 .../src/extension}/variableSchema.ts | 6 +- .../src/extension}/variables.test.ts | 0 .../src/extension}/variables.ts | 0 packages/core/src/index.ts | 3 + .../skills/skill-manager-extension.test.ts | 191 --- packages/core/src/skills/skill-manager.ts | 147 +- .../core/src/subagents/subagent-manager.ts | 12 +- packages/core/src/telemetry/constants.ts | 1 + packages/core/src/telemetry/index.ts | 2 + packages/core/src/telemetry/loggers.ts | 28 + .../src/telemetry/qwen-logger/qwen-logger.ts | 17 + packages/core/src/telemetry/types.ts | 29 + .../core/src/utils/envVarResolver.test.ts | 297 ++++ packages/core/src/utils/envVarResolver.ts | 126 ++ .../utils}/toml-to-markdown-converter.test.ts | 0 .../src/utils}/toml-to-markdown-converter.ts | 0 71 files changed, 3221 insertions(+), 3625 deletions(-) rename packages/cli/src/{config => commands}/extensions/consent.ts (50%) create mode 100644 packages/cli/src/commands/extensions/utils.ts delete mode 100644 packages/cli/src/config/extension.ts delete mode 100644 packages/cli/src/config/extensions/claude-converter.ts delete mode 100644 packages/cli/src/config/extensions/extensionEnablement.test.ts delete mode 100644 packages/cli/src/config/extensions/extensionEnablement.ts delete mode 100644 packages/cli/src/config/extensions/update.test.ts delete mode 100644 packages/cli/src/config/extensions/update.ts delete mode 100644 packages/cli/src/ui/hooks/useWorkspaceMigration.ts rename packages/{cli/src/config/extensions => core/src/extension}/claude-converter.test.ts (79%) create mode 100644 packages/core/src/extension/claude-converter.ts rename packages/{cli/src/config/extension.test.ts => core/src/extension/extensionManager.test.ts} (100%) create mode 100644 packages/core/src/extension/extensionManager.ts rename packages/{cli/src/config/extensions => core/src/extension}/extensionSettings.test.ts (99%) rename packages/{cli/src/config/extensions => core/src/extension}/extensionSettings.ts (98%) rename packages/{cli/src/config/extensions => core/src/extension}/gemini-converter.test.ts (100%) rename packages/{cli/src/config/extensions => core/src/extension}/gemini-converter.ts (96%) rename packages/{cli/src/config/extensions => core/src/extension}/github.test.ts (99%) rename packages/{cli/src/config/extensions => core/src/extension}/github.ts (85%) rename packages/{cli/src/config/extensions => core/src/extension}/marketplace.test.ts (87%) rename packages/{cli/src/config/extensions => core/src/extension}/marketplace.ts (95%) create mode 100644 packages/core/src/extension/override.test.ts create mode 100644 packages/core/src/extension/override.ts rename packages/{cli/src/config/extensions => core/src/extension}/settings.test.ts (98%) rename packages/{cli/src/config/extensions => core/src/extension}/settings.ts (98%) rename packages/{cli/src/config/extensions => core/src/extension}/storage.test.ts (100%) rename packages/{cli/src/config/extensions => core/src/extension}/storage.ts (100%) rename packages/{cli/src/config/extensions => core/src/extension}/variableSchema.ts (85%) rename packages/{cli/src/config/extensions => core/src/extension}/variables.test.ts (100%) rename packages/{cli/src/config/extensions => core/src/extension}/variables.ts (100%) delete mode 100644 packages/core/src/skills/skill-manager-extension.test.ts create mode 100644 packages/core/src/utils/envVarResolver.test.ts create mode 100644 packages/core/src/utils/envVarResolver.ts rename packages/{cli/src/services => core/src/utils}/toml-to-markdown-converter.test.ts (100%) rename packages/{cli/src/services => core/src/utils}/toml-to-markdown-converter.ts (100%) diff --git a/packages/cli/src/acp-integration/acpAgent.ts b/packages/cli/src/acp-integration/acpAgent.ts index e5f27636b11..d33a207feb9 100644 --- a/packages/cli/src/acp-integration/acpAgent.ts +++ b/packages/cli/src/acp-integration/acpAgent.ts @@ -27,11 +27,8 @@ import { Readable, Writable } from 'node:stream'; import type { LoadedSettings } from '../config/settings.js'; import { SettingScope } from '../config/settings.js'; import { z } from 'zod'; -import { ExtensionStorage } from '../config/extensions/storage.js'; -import type { Extension } from '../config/extension.js'; import type { CliArgs } from '../config/config.js'; import { loadCliConfig } from '../config/config.js'; -import { ExtensionEnablementManager } from '../config/extensions/extensionEnablement.js'; // Import the modular Session class import { Session } from './session/Session.js'; @@ -39,7 +36,6 @@ import { Session } from './session/Session.js'; export async function runAcpAgent( config: Config, settings: LoadedSettings, - extensions: Extension[], argv: CliArgs, ) { const stdout = Writable.toWeb(process.stdout) as WritableStream; @@ -52,8 +48,7 @@ export async function runAcpAgent( console.debug = console.error; new acp.AgentSideConnection( - (client: acp.Client) => - new GeminiAgent(config, settings, extensions, argv, client), + (client: acp.Client) => new GeminiAgent(config, settings, argv, client), stdout, stdin, ); @@ -66,7 +61,6 @@ class GeminiAgent { constructor( private config: Config, private settings: LoadedSettings, - private extensions: Extension[], private argv: CliArgs, private client: acp.Client, ) {} @@ -216,16 +210,7 @@ class GeminiAgent { continue: false, }; - const config = await loadCliConfig( - settings, - this.extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - this.argv.extensions, - ), - argvForSession, - cwd, - ); + const config = await loadCliConfig(settings, argvForSession, cwd); await config.initialize(); return config; diff --git a/packages/cli/src/config/extensions/consent.ts b/packages/cli/src/commands/extensions/consent.ts similarity index 50% rename from packages/cli/src/config/extensions/consent.ts rename to packages/cli/src/commands/extensions/consent.ts index a686188ea1e..8f0d3123f90 100644 --- a/packages/cli/src/config/extensions/consent.ts +++ b/packages/cli/src/commands/extensions/consent.ts @@ -1,5 +1,4 @@ import type { ConfirmationRequest } from '../../ui/types.js'; -import type { ExtensionConfig } from '../extension.js'; /** * Requests consent from the user to perform an action, by reading a Y/n @@ -10,7 +9,10 @@ import type { ExtensionConfig } from '../extension.js'; * @param consentDescription The description of the thing they will be consenting to. * @returns boolean, whether they consented or not. */ -export async function requestConsentNonInteractive(): Promise { +export async function requestConsentNonInteractive( + consentDescription: string, +): Promise { + console.info(consentDescription); const result = await promptForConsentNonInteractive( 'Do you want to continue? [Y/n]: ', ); @@ -83,75 +85,3 @@ async function promptForConsentInteractive( }); }); } - -/** - * Builds a consent string for installing an extension based on it's - * extensionConfig. - */ -export function extensionConsentString( - extensionConfig: ExtensionConfig, - commands?: string[], -): string { - const output: string[] = []; - const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); - output.push(`Installing extension "${extensionConfig.name}".`); - output.push( - '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', - ); - - if (mcpServerEntries.length) { - output.push('This extension will run the following MCP servers:'); - for (const [key, mcpServer] of mcpServerEntries) { - const isLocal = !!mcpServer.command; - const source = - mcpServer.httpUrl ?? - `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; - output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); - } - } - if (commands && commands.length > 0) { - output.push( - `This extension will add the following commands: ${commands.join(', ')}.`, - ); - } - if (extensionConfig.contextFileName) { - output.push( - `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, - ); - } - if (extensionConfig.excludeTools) { - output.push( - `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, - ); - } - return output.join('\n'); -} - -/** - * Requests consent from the user to install an extension (extensionConfig), if - * there is any difference between the consent string for `extensionConfig` and - * `previousExtensionConfig`. - * - * Always requests consent if previousExtensionConfig is null. - * - * Throws if the user does not consent. - */ -export async function maybeRequestConsentOrFail( - extensionConfig: ExtensionConfig, - requestConsent: (consent: string) => Promise, - commands: string[], - previousExtensionConfig?: ExtensionConfig, -) { - const extensionConsent = extensionConsentString(extensionConfig, commands); - if (previousExtensionConfig) { - const previousExtensionConsent = extensionConsentString( - previousExtensionConfig, - ); - if (previousExtensionConsent === extensionConsent) { - return; - } - } - if (!(await requestConsent(extensionConsent))) { - throw new Error(`Installation cancelled for "${extensionConfig.name}".`); - } -} diff --git a/packages/cli/src/commands/extensions/disable.ts b/packages/cli/src/commands/extensions/disable.ts index 0a88ce08f24..35be4aa8c11 100644 --- a/packages/cli/src/commands/extensions/disable.ts +++ b/packages/cli/src/commands/extensions/disable.ts @@ -5,21 +5,22 @@ */ import { type CommandModule } from 'yargs'; -import { disableExtension } from '../../config/extension.js'; import { SettingScope } from '../../config/settings.js'; import { getErrorMessage } from '../../utils/errors.js'; +import { getExtensionManager } from './utils.js'; interface DisableArgs { name: string; scope?: string; } -export function handleDisable(args: DisableArgs) { +export async function handleDisable(args: DisableArgs) { + const extensionManager = await getExtensionManager(); try { if (args.scope?.toLowerCase() === 'workspace') { - disableExtension(args.name, SettingScope.Workspace); + extensionManager.disableExtension(args.name, SettingScope.Workspace); } else { - disableExtension(args.name, SettingScope.User); + extensionManager.disableExtension(args.name, SettingScope.User); } console.log( `Extension "${args.name}" successfully disabled for scope "${args.scope}".`, @@ -61,8 +62,8 @@ export const disableCommand: CommandModule = { } return true; }), - handler: (argv) => { - handleDisable({ + handler: async (argv) => { + await handleDisable({ name: argv['name'] as string, scope: argv['scope'] as string, }); diff --git a/packages/cli/src/commands/extensions/enable.ts b/packages/cli/src/commands/extensions/enable.ts index 7a77112d20d..2286105271a 100644 --- a/packages/cli/src/commands/extensions/enable.ts +++ b/packages/cli/src/commands/extensions/enable.ts @@ -6,20 +6,22 @@ import { type CommandModule } from 'yargs'; import { FatalConfigError, getErrorMessage } from '@qwen-code/qwen-code-core'; -import { enableExtension } from '../../config/extension.js'; import { SettingScope } from '../../config/settings.js'; +import { getExtensionManager } from './utils.js'; interface EnableArgs { name: string; scope?: string; } -export function handleEnable(args: EnableArgs) { +export async function handleEnable(args: EnableArgs) { + const extensionManager = await getExtensionManager(); + try { if (args.scope?.toLowerCase() === 'workspace') { - enableExtension(args.name, SettingScope.Workspace); + extensionManager.enableExtension(args.name, SettingScope.Workspace); } else { - enableExtension(args.name, SettingScope.User); + extensionManager.enableExtension(args.name, SettingScope.User); } if (args.scope) { console.log( @@ -66,8 +68,8 @@ export const enableCommand: CommandModule = { } return true; }), - handler: (argv) => { - handleEnable({ + handler: async (argv) => { + await handleEnable({ name: argv['name'] as string, scope: argv['scope'] as string, }); diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index a7333b704c3..df3ba4b3447 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -5,70 +5,60 @@ */ import type { CommandModule } from 'yargs'; + import { - installExtension, - requestConsentNonInteractive, -} from '../../config/extension.js'; -import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; + ExtensionManager, + parseInstallSource, +} from '@qwen-code/qwen-code-core'; import { getErrorMessage } from '../../utils/errors.js'; -import { stat } from 'node:fs/promises'; -import { parseMarketplaceSource } from '../../config/extensions/marketplace.js'; +import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; +import { loadSettings } from '../../config/settings.js'; +import { requestConsentNonInteractive } from './consent.js'; interface InstallArgs { source: string; ref?: string; autoUpdate?: boolean; + allowPreRelease?: boolean; + consent?: boolean; } export async function handleInstall(args: InstallArgs) { try { - let installMetadata: ExtensionInstallMetadata; - const { source } = args; + const installMetadata = await parseInstallSource(args.source); - // Check if it's a marketplace source (format: marketplace-url:plugin-name) - const marketplaceParsed = parseMarketplaceSource(source); - if (marketplaceParsed) { - if (args.ref || args.autoUpdate) { - throw new Error( - '--ref and --auto-update are not applicable for marketplace extensions.', - ); - } - installMetadata = { - source, - type: 'marketplace', - }; - } else if ( - source.startsWith('http://') || - source.startsWith('https://') || - source.startsWith('git@') || - source.startsWith('sso://') + if ( + installMetadata.type !== 'git' && + installMetadata.type !== 'github-release' ) { - installMetadata = { - source, - type: 'git', - ref: args.ref, - autoUpdate: args.autoUpdate, - }; - } else { if (args.ref || args.autoUpdate) { throw new Error( - '--ref and --auto-update are not applicable for local extensions.', + '--ref and --auto-update are not applicable for marketplace extensions.', ); } - try { - await stat(source); - installMetadata = { - source, - type: 'local', - }; - } catch { - throw new Error('Install source not found.'); - } } - const name = await installExtension( - installMetadata, - requestConsentNonInteractive, + const requestConsent = args.consent + ? () => Promise.resolve(true) + : requestConsentNonInteractive; + const workspaceDir = process.cwd(); + const extensionManager = new ExtensionManager({ + workspaceDir, + isWorkspaceTrusted: !!isWorkspaceTrusted( + loadSettings(workspaceDir).merged, + ), + requestConsent, + }); + await extensionManager.refreshCache(); + + const name = await extensionManager.installExtension( + { + ...installMetadata, + ref: args.ref, + autoUpdate: args.autoUpdate, + allowPreRelease: args.allowPreRelease, + }, + requestConsent, ); console.log(`Extension "${name}" installed successfully and enabled.`); } catch (error) { @@ -97,6 +87,16 @@ export const installCommand: CommandModule = { describe: 'Enable auto-update for this extension.', type: 'boolean', }) + .option('pre-release', { + describe: 'Enable pre-release versions for this extension.', + type: 'boolean', + }) + .option('consent', { + describe: + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.', + type: 'boolean', + default: false, + }) .check((argv) => { if (!argv.source) { throw new Error('The source argument must be provided.'); @@ -108,6 +108,8 @@ export const installCommand: CommandModule = { source: argv['source'] as string, ref: argv['ref'] as string | undefined, autoUpdate: argv['auto-update'] as boolean | undefined, + allowPreRelease: argv['pre-release'] as boolean | undefined, + consent: argv['consent'] as boolean | undefined, }); }, }; diff --git a/packages/cli/src/commands/extensions/link.ts b/packages/cli/src/commands/extensions/link.ts index 8104e42b95f..ab2f946f9bf 100644 --- a/packages/cli/src/commands/extensions/link.ts +++ b/packages/cli/src/commands/extensions/link.ts @@ -5,13 +5,10 @@ */ import type { CommandModule } from 'yargs'; -import { - installExtension, - requestConsentNonInteractive, -} from '../../config/extension.js'; -import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; - +import { type ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; import { getErrorMessage } from '../../utils/errors.js'; +import { requestConsentNonInteractive } from './consent.js'; +import { getExtensionManager } from './utils.js'; interface InstallArgs { path: string; @@ -23,12 +20,14 @@ export async function handleLink(args: InstallArgs) { source: args.path, type: 'link', }; - const extensionName = await installExtension( + const extensionManager = await getExtensionManager(); + + const extension = await extensionManager.installExtension( installMetadata, requestConsentNonInteractive, ); console.log( - `Extension "${extensionName}" linked successfully and enabled.`, + `Extension "${extension.name}" linked successfully and enabled.`, ); } catch (error) { console.error(getErrorMessage(error)); diff --git a/packages/cli/src/commands/extensions/list.ts b/packages/cli/src/commands/extensions/list.ts index f6689a3c0c9..ea0fcba9149 100644 --- a/packages/cli/src/commands/extensions/list.ts +++ b/packages/cli/src/commands/extensions/list.ts @@ -5,19 +5,23 @@ */ import type { CommandModule } from 'yargs'; -import { loadUserExtensions, toOutputString } from '../../config/extension.js'; import { getErrorMessage } from '../../utils/errors.js'; +import { getExtensionManager } from './utils.js'; export async function handleList() { try { - const extensions = loadUserExtensions(); + const extensionManager = await getExtensionManager(); + const extensions = extensionManager.getLoadedExtensions(); + if (extensions.length === 0) { console.log('No extensions installed.'); return; } console.log( extensions - .map((extension, _): string => toOutputString(extension, process.cwd())) + .map((extension, _): string => + extensionManager.toOutputString(extension, process.cwd()), + ) .join('\n\n'), ); } catch (error) { diff --git a/packages/cli/src/commands/extensions/uninstall.ts b/packages/cli/src/commands/extensions/uninstall.ts index d7c131962be..02ce1cd68fa 100644 --- a/packages/cli/src/commands/extensions/uninstall.ts +++ b/packages/cli/src/commands/extensions/uninstall.ts @@ -5,8 +5,11 @@ */ import type { CommandModule } from 'yargs'; -import { uninstallExtension } from '../../config/extension.js'; import { getErrorMessage } from '../../utils/errors.js'; +import { ExtensionManager } from '@qwen-code/qwen-code-core'; +import { requestConsentNonInteractive } from './consent.js'; +import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; +import { loadSettings } from '../../config/settings.js'; interface UninstallArgs { name: string; // can be extension name or source URL. @@ -14,7 +17,16 @@ interface UninstallArgs { export async function handleUninstall(args: UninstallArgs) { try { - await uninstallExtension(args.name); + const workspaceDir = process.cwd(); + const extensionManager = new ExtensionManager({ + workspaceDir, + requestConsent: requestConsentNonInteractive, + isWorkspaceTrusted: !!isWorkspaceTrusted( + loadSettings(workspaceDir).merged, + ), + }); + await extensionManager.refreshCache(); + await extensionManager.uninstallExtension(args.name, false); console.log(`Extension "${args.name}" successfully uninstalled.`); } catch (error) { console.error(getErrorMessage(error)); diff --git a/packages/cli/src/commands/extensions/update.ts b/packages/cli/src/commands/extensions/update.ts index e882fa1b3b7..d254cac5ad1 100644 --- a/packages/cli/src/commands/extensions/update.ts +++ b/packages/cli/src/commands/extensions/update.ts @@ -5,23 +5,13 @@ */ import type { CommandModule } from 'yargs'; -import { - loadExtensions, - annotateActiveExtensions, - requestConsentNonInteractive, -} from '../../config/extension.js'; -import { ExtensionStorage } from '../../config/extensions/storage.js'; - -import { - updateAllUpdatableExtensions, - type ExtensionUpdateInfo, - checkForAllExtensionUpdates, - updateExtension, -} from '../../config/extensions/update.js'; -import { checkForExtensionUpdate } from '../../config/extensions/github.js'; import { getErrorMessage } from '../../utils/errors.js'; import { ExtensionUpdateState } from '../../ui/state/extensions.js'; -import { ExtensionEnablementManager } from '../../config/extensions/extensionEnablement.js'; +import { + checkForExtensionUpdate, + type ExtensionUpdateInfo, +} from '@qwen-code/qwen-code-core'; +import { getExtensionManager } from './utils.js'; interface UpdateArgs { name?: string; @@ -32,19 +22,9 @@ const updateOutput = (info: ExtensionUpdateInfo) => `Extension "${info.name}" successfully updated: ${info.originalVersion} → ${info.updatedVersion}.`; export async function handleUpdate(args: UpdateArgs) { - const workingDir = process.cwd(); - const extensionEnablementManager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - // Force enable named extensions, otherwise we will only update the enabled - // ones. - args.name ? [args.name] : [], - ); - const allExtensions = loadExtensions(extensionEnablementManager); - const extensions = annotateActiveExtensions( - allExtensions, - workingDir, - extensionEnablementManager, - ); + const extensionManager = await getExtensionManager(); + const extensions = extensionManager.getLoadedExtensions(); + if (args.name) { try { const extension = extensions.find( @@ -54,25 +34,23 @@ export async function handleUpdate(args: UpdateArgs) { console.log(`Extension "${args.name}" not found.`); return; } - let updateState: ExtensionUpdateState | undefined; if (!extension.installMetadata) { console.log( `Unable to install extension "${args.name}" due to missing install metadata`, ); return; } - await checkForExtensionUpdate(extension, (newState) => { - updateState = newState; - }); + const updateState = await checkForExtensionUpdate( + extension, + extensionManager, + ); if (updateState !== ExtensionUpdateState.UPDATE_AVAILABLE) { console.log(`Extension "${args.name}" is already up to date.`); return; } // TODO(chrstnb): we should list extensions if the requested extension is not installed. - const updatedExtensionInfo = (await updateExtension( + const updatedExtensionInfo = (await extensionManager.updateExtension( extension, - workingDir, - requestConsentNonInteractive, updateState, () => {}, ))!; @@ -93,18 +71,15 @@ export async function handleUpdate(args: UpdateArgs) { if (args.all) { try { const extensionState = new Map(); - await checkForAllExtensionUpdates(extensions, (action) => { - if (action.type === 'SET_STATE') { - extensionState.set(action.payload.name, { - status: action.payload.state, + await extensionManager.checkForAllExtensionUpdates( + (extensionName, state) => { + extensionState.set(extensionName, { + status: state, processed: true, // No need to process as we will force the update. }); - } - }); - let updateInfos = await updateAllUpdatableExtensions( - workingDir, - requestConsentNonInteractive, - extensions, + }, + ); + let updateInfos = await extensionManager.updateAllUpdatableExtensions( extensionState, () => {}, ); diff --git a/packages/cli/src/commands/extensions/utils.ts b/packages/cli/src/commands/extensions/utils.ts new file mode 100644 index 00000000000..5c30ea39718 --- /dev/null +++ b/packages/cli/src/commands/extensions/utils.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { ExtensionManager } from '@qwen-code/qwen-code-core'; +import { loadSettings } from '../../config/settings.js'; +import { requestConsentNonInteractive } from './consent.js'; +import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; + +export async function getExtensionManager(): Promise { + const workspaceDir = process.cwd(); + const extensionManager = new ExtensionManager({ + workspaceDir, + requestConsent: requestConsentNonInteractive, + isWorkspaceTrusted: !!isWorkspaceTrusted(loadSettings(workspaceDir).merged), + }); + await extensionManager.refreshCache(); + return extensionManager; +} diff --git a/packages/cli/src/commands/mcp/list.ts b/packages/cli/src/commands/mcp/list.ts index 46b8806324e..8836e55c041 100644 --- a/packages/cli/src/commands/mcp/list.ts +++ b/packages/cli/src/commands/mcp/list.ts @@ -8,11 +8,13 @@ import type { CommandModule } from 'yargs'; import { loadSettings } from '../../config/settings.js'; import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; -import { MCPServerStatus, createTransport } from '@qwen-code/qwen-code-core'; +import { + MCPServerStatus, + createTransport, + ExtensionManager, +} from '@qwen-code/qwen-code-core'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { loadExtensions } from '../../config/extension.js'; -import { ExtensionStorage } from '../../config/extensions/storage.js'; -import { ExtensionEnablementManager } from '../../config/extensions/extensionEnablement.js'; +import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; const COLOR_GREEN = '\u001b[32m'; const COLOR_YELLOW = '\u001b[33m'; @@ -23,22 +25,27 @@ async function getMcpServersFromConfig(): Promise< Record > { const settings = loadSettings(); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const extensionManager = new ExtensionManager({ + isWorkspaceTrusted: !!isWorkspaceTrusted(settings.merged), + telemetrySettings: settings.merged.telemetry, + }); + await extensionManager.refreshCache(); + const extensions = extensionManager.getLoadedExtensions(); const mcpServers = { ...(settings.merged.mcpServers || {}) }; for (const extension of extensions) { - Object.entries(extension.config.mcpServers || {}).forEach( - ([key, server]) => { - if (mcpServers[key]) { - return; - } - mcpServers[key] = { - ...server, - extensionName: extension.config.name, - }; - }, - ); + if (extension.isActive) { + Object.entries(extension.config.mcpServers || {}).forEach( + ([key, server]) => { + if (mcpServers[key]) { + return; + } + mcpServers[key] = { + ...server, + extensionName: extension.config.name, + }; + }, + ); + } } return mcpServers; } diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 7cd7d685a2c..3cddeb9eb5c 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -9,7 +9,6 @@ import { AuthType, Config, DEFAULT_QWEN_EMBEDDING_MODEL, - DEFAULT_MEMORY_FILE_FILTERING_OPTIONS, EditTool, FileDiscoveryService, getCurrentGeminiMdFilename, @@ -25,7 +24,6 @@ import { SessionService, type ResumedSessionData, type FileFilteringOptions, - type MCPServerConfig, } from '@qwen-code/qwen-code-core'; import { extensionsCommand } from '../commands/extensions.js'; import type { Settings } from './settings.js'; @@ -37,14 +35,11 @@ import { homedir } from 'node:os'; import { resolvePath } from '../utils/resolvePath.js'; import { getCliVersion } from '../utils/version.js'; -import type { Extension } from './extension.js'; -import { annotateActiveExtensions } from './extension.js'; import { loadSandboxConfig } from './sandboxConfig.js'; import { appEvents } from '../utils/events.js'; import { mcpCommand } from '../commands/mcp.js'; import { isWorkspaceTrusted } from './trustedFolders.js'; -import type { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; import { buildWebSearchConfig } from './webSearch.js'; // Simple console logger for now - replace with actual logger if available @@ -162,7 +157,7 @@ function normalizeOutputFormat( return OutputFormat.TEXT; } -export async function parseArguments(settings: Settings): Promise { +export async function parseArguments(): Promise { const rawArgv = hideBin(process.argv); const yargsInstance = yargs(rawArgv) .locale('en') @@ -537,11 +532,9 @@ export async function parseArguments(settings: Settings): Promise { }), ) // Register MCP subcommands - .command(mcpCommand); - - if (settings?.experimental?.extensionManagement ?? true) { - yargsInstance.command(extensionsCommand); - } + .command(mcpCommand) + // Register Extension subcommands + .command(extensionsCommand); yargsInstance .version(await getCliVersion()) // This will enable the --version flag based on package.json @@ -605,11 +598,11 @@ export async function loadHierarchicalGeminiMemory( includeDirectoriesToReadGemini: readonly string[] = [], debugMode: boolean, fileService: FileDiscoveryService, - settings: Settings, extensionContextFilePaths: string[] = [], folderTrust: boolean, memoryImportFormat: 'flat' | 'tree' = 'tree', fileFilteringOptions?: FileFilteringOptions, + maxDirs: number = 200, ): Promise<{ memoryContent: string; fileCount: number }> { // FIX: Use real, canonical paths for a reliable comparison to handle symlinks. const realCwd = fs.realpathSync(path.resolve(currentWorkingDirectory)); @@ -636,7 +629,7 @@ export async function loadHierarchicalGeminiMemory( folderTrust, memoryImportFormat, fileFilteringOptions, - settings.context?.discoveryMaxDirs, + maxDirs, ); } @@ -651,30 +644,17 @@ export function isDebugMode(argv: CliArgs): boolean { export async function loadCliConfig( settings: Settings, - extensions: Extension[], - extensionEnablementManager: ExtensionEnablementManager, argv: CliArgs, cwd: string = process.cwd(), + overrideExtensions?: string[], ): Promise { const debugMode = isDebugMode(argv); - const memoryImportFormat = settings.context?.importFormat || 'tree'; - const ideMode = settings.ide?.enabled ?? false; const folderTrust = settings.security?.folderTrust?.enabled ?? false; const trustedFolder = isWorkspaceTrusted(settings)?.isTrusted ?? true; - const allExtensions = annotateActiveExtensions( - extensions, - cwd, - extensionEnablementManager, - ); - - const activeExtensions = extensions.filter( - (_, i) => allExtensions[i].isActive, - ); - // Set the context filename in the server's memoryTool module BEFORE loading memory // TODO(b/343434939): This is a bit of a hack. The contextFileName should ideally be passed // directly to the Config constructor in core, and have core handle setGeminiMdFilename. @@ -686,51 +666,27 @@ export async function loadCliConfig( setServerGeminiMdFilename(getCurrentGeminiMdFilename()); } - const extensionContextFilePaths = activeExtensions.flatMap( - (e) => e.contextFiles, - ); - // Automatically load output-language.md if it exists - const outputLanguageFilePath = path.join( + let outputLanguageFilePath: string | undefined = path.join( Storage.getGlobalQwenDir(), 'output-language.md', ); if (fs.existsSync(outputLanguageFilePath)) { - extensionContextFilePaths.push(outputLanguageFilePath); if (debugMode) { logger.debug( `Found output-language.md, adding to context files: ${outputLanguageFilePath}`, ); } + } else { + outputLanguageFilePath = undefined; } const fileService = new FileDiscoveryService(cwd); - const fileFiltering = { - ...DEFAULT_MEMORY_FILE_FILTERING_OPTIONS, - ...settings.context?.fileFiltering, - }; - const includeDirectories = (settings.context?.includeDirectories || []) .map(resolvePath) .concat((argv.includeDirectories || []).map(resolvePath)); - // Call the (now wrapper) loadHierarchicalGeminiMemory which calls the server's version - const { memoryContent, fileCount } = await loadHierarchicalGeminiMemory( - cwd, - settings.context?.loadMemoryFromIncludeDirectories - ? includeDirectories - : [], - debugMode, - fileService, - settings, - extensionContextFilePaths, - trustedFolder, - memoryImportFormat, - fileFiltering, - ); - - let mcpServers = mergeMcpServers(settings, activeExtensions); const question = argv.promptInteractive || argv.prompt || ''; const inputFormat: InputFormat = (argv.inputFormat as InputFormat | undefined) ?? InputFormat.TEXT; @@ -844,38 +800,18 @@ export async function loadCliConfig( const excludeTools = mergeExcludeTools( settings, - activeExtensions, extraExcludes.length > 0 ? extraExcludes : undefined, argv.excludeTools, ); - const blockedMcpServers: Array<{ name: string; extensionName: string }> = []; - if (!argv.allowedMcpServerNames) { - if (settings.mcp?.allowed) { - mcpServers = allowedMcpServers( - mcpServers, - settings.mcp.allowed, - blockedMcpServers, - ); - } - - if (settings.mcp?.excluded) { - const excludedNames = new Set(settings.mcp.excluded.filter(Boolean)); - if (excludedNames.size > 0) { - mcpServers = Object.fromEntries( - Object.entries(mcpServers).filter(([key]) => !excludedNames.has(key)), - ); - } - } - } - - if (argv.allowedMcpServerNames) { - mcpServers = allowedMcpServers( - mcpServers, - argv.allowedMcpServerNames, - blockedMcpServers, - ); - } + const allowedMcpServers = argv.allowedMcpServerNames + ? new Set(argv.allowedMcpServerNames.filter(Boolean)) + : settings.mcp?.allowed + ? new Set(settings.mcp.allowed.filter(Boolean)) + : undefined; + const excludedMcpServers = settings.mcp?.excluded + ? new Set(settings.mcp.excluded.filter(Boolean)) + : undefined; const selectedAuthType = (argv.authType as AuthType | undefined) || @@ -943,6 +879,8 @@ export async function loadCliConfig( includeDirectories, loadMemoryFromIncludeDirectories: settings.context?.loadMemoryFromIncludeDirectories || false, + importFormat: settings.context?.importFormat || 'tree', + discoveryMaxDirs: settings.context?.discoveryMaxDirs || 200, debugMode, question, fullContext: argv.allFiles || false, @@ -952,9 +890,13 @@ export async function loadCliConfig( toolDiscoveryCommand: settings.tools?.discoveryCommand, toolCallCommand: settings.tools?.callCommand, mcpServerCommand: settings.mcp?.serverCommand, - mcpServers, - userMemory: memoryContent, - geminiMdFileCount: fileCount, + mcpServers: settings.mcpServers || {}, + allowedMcpServers: allowedMcpServers + ? Array.from(allowedMcpServers) + : undefined, + excludedMcpServers: excludedMcpServers + ? Array.from(excludedMcpServers) + : undefined, approvalMode, showMemoryUsage: argv.showMemoryUsage || settings.ui?.showMemoryUsage || false, @@ -977,15 +919,14 @@ export async function loadCliConfig( fileDiscoveryService: fileService, bugCommand: settings.advanced?.bugCommand, model: resolvedModel, - extensionContextFilePaths, + outputLanguageFilePath, sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1, maxSessionTurns: argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1, experimentalZedIntegration: argv.experimentalAcp || false, experimentalSkills: argv.experimentalSkills || false, listExtensions: argv.listExtensions || false, - extensions: allExtensions, - blockedMcpServers, + overrideExtensions: overrideExtensions || argv.extensions, noBrowser: !!process.env['NO_BROWSER'], authType: selectedAuthType, inputFormat, @@ -1040,61 +981,8 @@ export async function loadCliConfig( }); } -function allowedMcpServers( - mcpServers: { [x: string]: MCPServerConfig }, - allowMCPServers: string[], - blockedMcpServers: Array<{ name: string; extensionName: string }>, -) { - const allowedNames = new Set(allowMCPServers.filter(Boolean)); - if (allowedNames.size > 0) { - mcpServers = Object.fromEntries( - Object.entries(mcpServers).filter(([key, server]) => { - const isAllowed = allowedNames.has(key); - if (!isAllowed) { - blockedMcpServers.push({ - name: key, - extensionName: server.extensionName || '', - }); - } - return isAllowed; - }), - ); - } else { - blockedMcpServers.push( - ...Object.entries(mcpServers).map(([key, server]) => ({ - name: key, - extensionName: server.extensionName || '', - })), - ); - mcpServers = {}; - } - return mcpServers; -} - -function mergeMcpServers(settings: Settings, extensions: Extension[]) { - const mcpServers = { ...(settings.mcpServers || {}) }; - for (const extension of extensions) { - Object.entries(extension.config.mcpServers || {}).forEach( - ([key, server]) => { - if (mcpServers[key]) { - logger.warn( - `Skipping extension MCP config for server with key "${key}" as it already exists.`, - ); - return; - } - mcpServers[key] = { - ...server, - extensionName: extension.config.name, - }; - }, - ); - } - return mcpServers; -} - function mergeExcludeTools( settings: Settings, - extensions: Extension[], extraExcludes?: string[] | undefined, cliExcludeTools?: string[] | undefined, ): string[] { @@ -1103,10 +991,5 @@ function mergeExcludeTools( ...(settings.tools?.exclude || []), ...(extraExcludes || []), ]); - for (const extension of extensions) { - for (const tool of extension.config.excludeTools || []) { - allExcludeTools.add(tool); - } - } return [...allExcludeTools]; } diff --git a/packages/cli/src/config/extension.ts b/packages/cli/src/config/extension.ts deleted file mode 100644 index 32f4a655724..00000000000 --- a/packages/cli/src/config/extension.ts +++ /dev/null @@ -1,885 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import type { - MCPServerConfig, - GeminiCLIExtension, - ExtensionInstallMetadata, -} from '@qwen-code/qwen-code-core'; -import { - Storage, - Config, - ExtensionInstallEvent, - ExtensionUninstallEvent, - ExtensionDisableEvent, - ExtensionEnableEvent, - logExtensionEnable, - logExtensionInstallEvent, - logExtensionUninstall, - logExtensionDisable, -} from '@qwen-code/qwen-code-core'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import * as os from 'node:os'; -import { SettingScope, loadSettings } from '../config/settings.js'; -import { getErrorMessage } from '../utils/errors.js'; -import { - EXTENSIONS_CONFIG_FILENAME, - INSTALL_METADATA_FILENAME, - recursivelyHydrateStrings, -} from './extensions/variables.js'; -import { isWorkspaceTrusted } from './trustedFolders.js'; -import { resolveEnvVarsInObject } from '../utils/envVarResolver.js'; -import { - cloneFromGit, - downloadFromGitHubRelease, - parseGitHubRepoForReleases, -} from './extensions/github.js'; -import type { LoadExtensionContext } from './extensions/variableSchema.js'; -import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; -import chalk from 'chalk'; -import type { ConfirmationRequest } from '../ui/types.js'; -import { - installFromMarketplace, - parseMarketplaceSource, -} from './extensions/marketplace.js'; -import { isClaudePluginConfig } from './extensions/claude-converter.js'; -import { - isGeminiExtensionConfig, - convertGeminiExtensionPackage, -} from './extensions/gemini-converter.js'; -import { glob } from 'glob'; -import { createHash } from 'node:crypto'; -import { maybeRequestConsentOrFail } from './extensions/consent.js'; -import { ExtensionStorage } from './extensions/storage.js'; -import { - maybePromptForSettings, - promptForSetting, -} from './extensions/extensionSettings.js'; - -export interface Extension { - path: string; - config: ExtensionConfig; - contextFiles: string[]; - installMetadata?: ExtensionInstallMetadata | undefined; - /** Absolute paths to skills directories from this extension */ - skillsPaths?: string[]; - /** Absolute paths to agents files from this extension */ - agentsPaths?: string[]; -} - -export interface ExtensionConfig { - name: string; - version: string; - mcpServers?: Record; - contextFileName?: string | string[]; - excludeTools?: string[]; - commands?: string | string[]; - skills?: string | string[]; - agents?: string | string[]; - settings?: ExtensionSetting[]; -} - -export interface ExtensionSetting { - name: string; - description: string; - envVar: string; - sensitive?: boolean; -} - -export interface ExtensionUpdateInfo { - name: string; - originalVersion: string; - updatedVersion: string; -} - -export function getWorkspaceExtensions(workspaceDir: string): Extension[] { - // If the workspace dir is the user extensions dir, there are no workspace extensions. - if (path.resolve(workspaceDir) === path.resolve(os.homedir())) { - return []; - } - return loadExtensionsFromDir(workspaceDir); -} - -export async function copyExtension( - source: string, - destination: string, -): Promise { - await fs.promises.cp(source, destination, { recursive: true }); -} - -export async function performWorkspaceExtensionMigration( - extensions: Extension[], - requestConsent: (consent: string) => Promise, -): Promise { - const failedInstallNames: string[] = []; - - for (const extension of extensions) { - try { - const installMetadata: ExtensionInstallMetadata = { - source: extension.path, - type: 'local', - }; - await installExtension(installMetadata, requestConsent); - } catch (_) { - failedInstallNames.push(extension.config.name); - } - } - return failedInstallNames; -} - -function getTelemetryConfig(cwd: string) { - const settings = loadSettings(cwd); - const config = new Config({ - telemetry: settings.merged.telemetry, - interactive: false, - targetDir: cwd, - cwd, - model: '', - debugMode: false, - }); - return config; -} - -export function loadExtensions( - extensionEnablementManager: ExtensionEnablementManager, - workspaceDir: string = process.cwd(), -): Extension[] { - const settings = loadSettings(workspaceDir).merged; - const allExtensions = [...loadUserExtensions()]; - - if ( - (isWorkspaceTrusted(settings) ?? true) && - // Default management setting to true - !(settings.experimental?.extensionManagement ?? true) - ) { - allExtensions.push(...getWorkspaceExtensions(workspaceDir)); - } - - const uniqueExtensions = new Map(); - - for (const extension of allExtensions) { - if ( - !uniqueExtensions.has(extension.config.name) && - extensionEnablementManager.isEnabled(extension.config.name, workspaceDir) - ) { - uniqueExtensions.set(extension.config.name, extension); - } - } - - return Array.from(uniqueExtensions.values()); -} - -export function loadUserExtensions(): Extension[] { - const userExtensions = loadExtensionsFromDir(os.homedir()); - - const uniqueExtensions = new Map(); - for (const extension of userExtensions) { - if (!uniqueExtensions.has(extension.config.name)) { - uniqueExtensions.set(extension.config.name, extension); - } - } - - return Array.from(uniqueExtensions.values()); -} - -export function loadExtensionsFromDir(dir: string): Extension[] { - const storage = new Storage(dir); - const extensionsDir = storage.getExtensionsDir(); - if (!fs.existsSync(extensionsDir)) { - return []; - } - - const extensions: Extension[] = []; - for (const subdir of fs.readdirSync(extensionsDir)) { - const extensionDir = path.join(extensionsDir, subdir); - - const extension = loadExtension({ extensionDir, workspaceDir: dir }); - if (extension != null) { - extensions.push(extension); - } - } - return extensions; -} - -export function loadExtension(context: LoadExtensionContext): Extension | null { - const { extensionDir, workspaceDir } = context; - if (!fs.statSync(extensionDir).isDirectory()) { - return null; - } - - const installMetadata = loadInstallMetadata(extensionDir); - let effectiveExtensionPath = extensionDir; - - if (installMetadata?.type === 'link') { - effectiveExtensionPath = installMetadata.source; - } - - try { - let config = loadExtensionConfig({ - extensionDir: effectiveExtensionPath, - workspaceDir, - }); - - config = resolveEnvVarsInObject(config); - - if (config.mcpServers) { - config.mcpServers = Object.fromEntries( - Object.entries(config.mcpServers).map(([key, value]) => [ - key, - filterMcpConfig(value), - ]), - ); - } - - const contextFiles = getContextFileNames(config) - .map((contextFileName) => - path.join(effectiveExtensionPath, contextFileName), - ) - .filter((contextFilePath) => fs.existsSync(contextFilePath)); - - const skillsPaths = collectPathsFromConfig( - config.skills, - effectiveExtensionPath, - ); - const agentsPaths = collectPathsFromConfig( - config.agents, - effectiveExtensionPath, - ); - - return { - path: effectiveExtensionPath, - config, - contextFiles, - installMetadata, - skillsPaths, - agentsPaths, - }; - } catch (e) { - console.error( - `Warning: Skipping extension in ${effectiveExtensionPath}: ${getErrorMessage( - e, - )}`, - ); - return null; - } -} - -export function loadExtensionByName( - name: string, - workspaceDir: string = process.cwd(), -): Extension | null { - const userExtensionsDir = ExtensionStorage.getUserExtensionsDir(); - if (!fs.existsSync(userExtensionsDir)) { - return null; - } - - for (const subdir of fs.readdirSync(userExtensionsDir)) { - const extensionDir = path.join(userExtensionsDir, subdir); - if (!fs.statSync(extensionDir).isDirectory()) { - continue; - } - const extension = loadExtension({ extensionDir, workspaceDir }); - if ( - extension && - extension.config.name.toLowerCase() === name.toLowerCase() - ) { - return extension; - } - } - - return null; -} - -function filterMcpConfig(original: MCPServerConfig): MCPServerConfig { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { trust, ...rest } = original; - return Object.freeze(rest); -} - -export function loadInstallMetadata( - extensionDir: string, -): ExtensionInstallMetadata | undefined { - const metadataFilePath = path.join(extensionDir, INSTALL_METADATA_FILENAME); - try { - const configContent = fs.readFileSync(metadataFilePath, 'utf-8'); - const metadata = JSON.parse(configContent) as ExtensionInstallMetadata; - return metadata; - } catch (_e) { - return undefined; - } -} - -function getContextFileNames(config: ExtensionConfig): string[] { - if (!config.contextFileName) { - return ['QWEN.md']; - } else if (!Array.isArray(config.contextFileName)) { - return [config.contextFileName]; - } - return config.contextFileName; -} - -function collectPathsFromConfig( - configValue: string | string[] | undefined, - extensionPath: string, -): string[] { - if (!configValue) return []; - - const pathArray = Array.isArray(configValue) ? configValue : [configValue]; - const absolutePaths: string[] = []; - - for (const relativePath of pathArray) { - const absolutePath = path.isAbsolute(relativePath) - ? relativePath - : path.join(extensionPath, relativePath); - - if (fs.existsSync(absolutePath)) { - absolutePaths.push(absolutePath); - } - } - return absolutePaths; -} - -/** - * Returns an annotated list of extensions. If an extension is listed in enabledExtensionNames, it will be active. - * If enabledExtensionNames is empty, an extension is active unless it is disabled. - * @param extensions The base list of extensions. - * @param enabledExtensionNames The names of explicitly enabled extensions. - * @param workspaceDir The current workspace directory. - */ -export function annotateActiveExtensions( - extensions: Extension[], - workspaceDir: string, - manager: ExtensionEnablementManager, -): GeminiCLIExtension[] { - manager.validateExtensionOverrides(extensions); - return extensions.map((extension) => ({ - name: extension.config.name, - version: extension.config.version, - isActive: manager.isEnabled(extension.config.name, workspaceDir), - path: extension.path, - installMetadata: extension.installMetadata, - })); -} - -/** - * Requests consent from the user to perform an action, by reading a Y/n - * character from stdin. - * - * This should not be called from interactive mode as it will break the CLI. - * - * @param consentDescription The description of the thing they will be consenting to. - * @returns boolean, whether they consented or not. - */ -export async function requestConsentNonInteractive( - consentDescription: string, -): Promise { - console.info(consentDescription); - const result = await promptForConsentNonInteractive( - 'Do you want to continue? [Y/n]: ', - ); - return result; -} - -/** - * Requests consent from the user to perform an action, in interactive mode. - * - * This should not be called from non-interactive mode as it will not work. - * - * @param consentDescription The description of the thing they will be consenting to. - * @param setExtensionUpdateConfirmationRequest A function to actually add a prompt to the UI. - * @returns boolean, whether they consented or not. - */ -export async function requestConsentInteractive( - consentDescription: string, - addExtensionUpdateConfirmationRequest: (value: ConfirmationRequest) => void, -): Promise { - return await promptForConsentInteractive( - consentDescription + '\n\nDo you want to continue?', - addExtensionUpdateConfirmationRequest, - ); -} - -/** - * Asks users a prompt and awaits for a y/n response on stdin. - * - * This should not be called from interactive mode as it will break the CLI. - * - * @param prompt A yes/no prompt to ask the user - * @returns Whether or not the user answers 'y' (yes). Defaults to 'yes' on enter. - */ -async function promptForConsentNonInteractive( - prompt: string, -): Promise { - const readline = await import('node:readline'); - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - - return new Promise((resolve) => { - rl.question(prompt, (answer) => { - rl.close(); - resolve(['y', ''].includes(answer.trim().toLowerCase())); - }); - }); -} - -/** - * Asks users an interactive yes/no prompt. - * - * This should not be called from non-interactive mode as it will break the CLI. - * - * @param prompt A markdown prompt to ask the user - * @param setExtensionUpdateConfirmationRequest Function to update the UI state with the confirmation request. - * @returns Whether or not the user answers yes. - */ -async function promptForConsentInteractive( - prompt: string, - addExtensionUpdateConfirmationRequest: (value: ConfirmationRequest) => void, -): Promise { - return await new Promise((resolve) => { - addExtensionUpdateConfirmationRequest({ - prompt, - onConfirm: (resolvedConfirmed) => { - resolve(resolvedConfirmed); - }, - }); - }); -} - -export async function installExtension( - installMetadata: ExtensionInstallMetadata, - requestConsent: (consent: string) => Promise, - cwd: string = process.cwd(), - previousExtensionConfig?: ExtensionConfig, -): Promise { - const telemetryConfig = getTelemetryConfig(cwd); - let newExtensionConfig: ExtensionConfig | null = null; - let localSourcePath: string | undefined; - - try { - const settings = loadSettings(cwd).merged; - if (!isWorkspaceTrusted(settings)) { - throw new Error( - `Could not install extension from untrusted folder at ${installMetadata.source}`, - ); - } - - const extensionsDir = ExtensionStorage.getUserExtensionsDir(); - await fs.promises.mkdir(extensionsDir, { recursive: true }); - - if ( - !path.isAbsolute(installMetadata.source) && - (installMetadata.type === 'local' || installMetadata.type === 'link') - ) { - installMetadata.source = path.resolve(cwd, installMetadata.source); - } - - let tempDir: string | undefined; - - // Handle marketplace installation - if (installMetadata.type === 'marketplace') { - const marketplaceParsed = parseMarketplaceSource(installMetadata.source); - if (!marketplaceParsed) { - throw new Error( - `Invalid marketplace source format: ${installMetadata.source}. Expected format: marketplace-url:plugin-name`, - ); - } - - tempDir = await ExtensionStorage.createTmpDir(); - const marketplaceResult = await installFromMarketplace({ - marketplaceUrl: marketplaceParsed.marketplaceUrl, - pluginName: marketplaceParsed.pluginName, - tempDir, - requestConsent, - }); - - newExtensionConfig = marketplaceResult.config; - localSourcePath = marketplaceResult.sourcePath; - installMetadata = marketplaceResult.installMetadata; - } else if ( - installMetadata.type === 'git' || - installMetadata.type === 'github-release' - ) { - tempDir = await ExtensionStorage.createTmpDir(); - try { - const result = await downloadFromGitHubRelease( - installMetadata, - tempDir, - ); - installMetadata.type = result.type; - installMetadata.releaseTag = result.tagName; - } catch (_error) { - await cloneFromGit(installMetadata, tempDir); - installMetadata.type = 'git'; - } - localSourcePath = tempDir; - } else if ( - installMetadata.type === 'local' || - installMetadata.type === 'link' - ) { - localSourcePath = installMetadata.source; - } else { - throw new Error(`Unsupported install type: ${installMetadata.type}`); - } - - try { - localSourcePath = await convertGeminiOrClaudeExtension(localSourcePath); - // Load extension config if not already loaded (from marketplace) - if (!newExtensionConfig) { - newExtensionConfig = loadExtensionConfig({ - extensionDir: localSourcePath, - workspaceDir: cwd, - }); - } - - const newExtensionName = newExtensionConfig.name; - const extensionStorage = new ExtensionStorage(newExtensionName); - const destinationPath = extensionStorage.getExtensionDir(); - - const installedExtensions = loadUserExtensions(); - if ( - installedExtensions.some( - (installed) => installed.config.name === newExtensionName, - ) - ) { - throw new Error( - `Extension "${newExtensionName}" is already installed. Please uninstall it first.`, - ); - } - - const commands = await loadCommandsFromDir( - `${localSourcePath}/commands`, - newExtensionConfig.name, - ); - - await maybeRequestConsentOrFail( - newExtensionConfig, - requestConsent, - commands, - previousExtensionConfig, - ); - const extensionId = getExtensionId(newExtensionConfig, installMetadata); - await fs.promises.mkdir(destinationPath, { recursive: true }); - - await maybePromptForSettings( - newExtensionConfig, - extensionId, - promptForSetting, - ); - - if ( - installMetadata.type === 'local' || - installMetadata.type === 'git' || - installMetadata.type === 'github-release' - ) { - await copyExtension(localSourcePath, destinationPath); - } - - const metadataString = JSON.stringify(installMetadata, null, 2); - const metadataPath = path.join( - destinationPath, - INSTALL_METADATA_FILENAME, - ); - await fs.promises.writeFile(metadataPath, metadataString); - } finally { - if (tempDir) { - await fs.promises.rm(tempDir, { recursive: true, force: true }); - } - if (localSourcePath !== tempDir) { - await fs.promises.rm(localSourcePath, { recursive: true, force: true }); - } - } - - logExtensionInstallEvent( - telemetryConfig, - new ExtensionInstallEvent( - newExtensionConfig!.name, - newExtensionConfig!.version, - installMetadata.source, - 'success', - ), - ); - - enableExtension(newExtensionConfig!.name, SettingScope.User); - return newExtensionConfig!.name; - } catch (error) { - // Attempt to load config from the source path even if installation fails - // to get the name and version for logging. - if (!newExtensionConfig && localSourcePath) { - try { - newExtensionConfig = loadExtensionConfig({ - extensionDir: localSourcePath, - workspaceDir: cwd, - }); - } catch { - // Ignore error, this is just for logging. - } - } - logExtensionInstallEvent( - telemetryConfig, - new ExtensionInstallEvent( - newExtensionConfig?.name ?? '', - newExtensionConfig?.version ?? '', - installMetadata.source, - 'error', - ), - ); - throw error; - } -} - -async function loadCommandsFromDir( - dir: string, - extensionName: string, -): Promise { - const globOptions = { - nodir: true, - dot: true, - follow: true, - }; - - try { - const mdFiles = await glob('**/*.md', { - ...globOptions, - cwd: dir, - }); - - const commandNames = mdFiles.map((file) => { - const relativePathWithExt = path.relative(dir, path.join(dir, file)); - const relativePath = relativePathWithExt.substring( - 0, - relativePathWithExt.length - 3, - ); - const baseCommandName = relativePath - .split(path.sep) - .map((segment) => segment.replaceAll(':', '_')) - .join(':'); - - const commandName = `${extensionName}:${baseCommandName}`; - return commandName; - }); - - return commandNames; - } catch (error) { - // Ignore ENOENT (directory doesn't exist) and AbortError (operation was cancelled) - const isEnoent = (error as NodeJS.ErrnoException).code === 'ENOENT'; - const isAbortError = error instanceof Error && error.name === 'AbortError'; - if (!isEnoent && !isAbortError) { - console.error(`Error loading commands from ${dir}:`, error); - } - return []; - } -} - -export function validateName(name: string) { - if (!/^[a-zA-Z0-9-]+$/.test(name)) { - throw new Error( - `Invalid extension name: "${name}". Only letters (a-z, A-Z), numbers (0-9), and dashes (-) are allowed.`, - ); - } -} - -async function convertGeminiOrClaudeExtension(extensionDir: string) { - let newExtensionDir = extensionDir; - const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); - if (fs.existsSync(configFilePath)) { - newExtensionDir = extensionDir; - } else if (isGeminiExtensionConfig(extensionDir)) { - newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)) - .convertedDir; - } else if (isClaudePluginConfig(extensionDir)) { - // claude - } - return newExtensionDir; -} - -export function loadExtensionConfig( - context: LoadExtensionContext, -): ExtensionConfig { - const { extensionDir, workspaceDir } = context; - const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); - if (!fs.existsSync(configFilePath)) { - throw new Error(`Configuration file not found at ${configFilePath}`); - } - try { - const configContent = fs.readFileSync(configFilePath, 'utf-8'); - const config = recursivelyHydrateStrings(JSON.parse(configContent), { - extensionPath: extensionDir, - workspacePath: workspaceDir, - '/': path.sep, - pathSeparator: path.sep, - }) as unknown as ExtensionConfig; - - if (!config.name || !config.version) { - throw new Error( - `Invalid configuration in ${configFilePath}: missing ${!config.name ? '"name"' : '"version"'}`, - ); - } - validateName(config.name); - return config; - } catch (e) { - throw new Error( - `Failed to load extension config from ${configFilePath}: ${getErrorMessage( - e, - )}`, - ); - } -} - -export async function uninstallExtension( - extensionIdentifier: string, - cwd: string = process.cwd(), -): Promise { - const telemetryConfig = getTelemetryConfig(cwd); - const installedExtensions = loadUserExtensions(); - const extensionName = installedExtensions.find( - (installed) => - installed.config.name.toLowerCase() === - extensionIdentifier.toLowerCase() || - installed.installMetadata?.source.toLowerCase() === - extensionIdentifier.toLowerCase(), - )?.config.name; - if (!extensionName) { - throw new Error(`Extension not found.`); - } - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - [extensionName], - ); - manager.remove(extensionName); - const storage = new ExtensionStorage(extensionName); - - await fs.promises.rm(storage.getExtensionDir(), { - recursive: true, - force: true, - }); - logExtensionUninstall( - telemetryConfig, - new ExtensionUninstallEvent(extensionName, 'success'), - ); -} - -export function toOutputString( - extension: Extension, - workspaceDir: string, -): string { - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ); - const userEnabled = manager.isEnabled(extension.config.name, os.homedir()); - const workspaceEnabled = manager.isEnabled( - extension.config.name, - workspaceDir, - ); - - const status = workspaceEnabled ? chalk.green('✓') : chalk.red('✗'); - let output = `${status} ${extension.config.name} (${extension.config.version})`; - output += `\n Path: ${extension.path}`; - if (extension.installMetadata) { - output += `\n Source: ${extension.installMetadata.source} (Type: ${extension.installMetadata.type})`; - if (extension.installMetadata.ref) { - output += `\n Ref: ${extension.installMetadata.ref}`; - } - if (extension.installMetadata.releaseTag) { - output += `\n Release tag: ${extension.installMetadata.releaseTag}`; - } - } - output += `\n Enabled (User): ${userEnabled}`; - output += `\n Enabled (Workspace): ${workspaceEnabled}`; - if (extension.contextFiles.length > 0) { - output += `\n Context files:`; - extension.contextFiles.forEach((contextFile) => { - output += `\n ${contextFile}`; - }); - } - if (extension.config.mcpServers) { - output += `\n MCP servers:`; - Object.keys(extension.config.mcpServers).forEach((key) => { - output += `\n ${key}`; - }); - } - if (extension.config.excludeTools) { - output += `\n Excluded tools:`; - extension.config.excludeTools.forEach((tool) => { - output += `\n ${tool}`; - }); - } - return output; -} - -export function disableExtension( - name: string, - scope: SettingScope, - cwd: string = process.cwd(), -) { - const config = getTelemetryConfig(cwd); - if (scope === SettingScope.System || scope === SettingScope.SystemDefaults) { - throw new Error('System and SystemDefaults scopes are not supported.'); - } - const extension = loadExtensionByName(name, cwd); - if (!extension) { - throw new Error(`Extension with name ${name} does not exist.`); - } - - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - [name], - ); - const scopePath = scope === SettingScope.Workspace ? cwd : os.homedir(); - manager.disable(name, true, scopePath); - logExtensionDisable(config, new ExtensionDisableEvent(name, scope)); -} - -export function enableExtension( - name: string, - scope: SettingScope, - cwd: string = process.cwd(), -) { - if (scope === SettingScope.System || scope === SettingScope.SystemDefaults) { - throw new Error('System and SystemDefaults scopes are not supported.'); - } - const extension = loadExtensionByName(name, cwd); - if (!extension) { - throw new Error(`Extension with name ${name} does not exist.`); - } - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ); - const scopePath = scope === SettingScope.Workspace ? cwd : os.homedir(); - manager.enable(name, true, scopePath); - const config = getTelemetryConfig(cwd); - logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); -} - -export function getExtensionId( - config: ExtensionConfig, - installMetadata?: ExtensionInstallMetadata, -): string { - // IDs are created by hashing details of the installation source in order to - // deduplicate extensions with conflicting names and also obfuscate any - // potentially sensitive information such as private git urls, system paths, - // or project names. - let idValue = config.name; - const githubUrlParts = - installMetadata && - (installMetadata.type === 'git' || - installMetadata.type === 'github-release') - ? parseGitHubRepoForReleases(installMetadata.source) - : null; - if (githubUrlParts) { - // For github repos, we use the https URI to the repo as the ID. - idValue = `https://github.com/${githubUrlParts.owner}/${githubUrlParts.repo}`; - } else { - idValue = installMetadata?.source ?? config.name; - } - return hashValue(idValue); -} - -export function hashValue(value: string): string { - return createHash('sha256').update(value).digest('hex'); -} diff --git a/packages/cli/src/config/extensions/claude-converter.ts b/packages/cli/src/config/extensions/claude-converter.ts deleted file mode 100644 index c6022ae6201..00000000000 --- a/packages/cli/src/config/extensions/claude-converter.ts +++ /dev/null @@ -1,181 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * Converter for Claude Code plugins to Qwen Code format. - */ - -import type { ExtensionConfig } from '../extension.js'; -import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; - -export interface ClaudePluginConfig { - name: string; - version: string; - description?: string; - author?: { name?: string; email?: string; url?: string }; - homepage?: string; - repository?: string; - license?: string; - keywords?: string[]; - commands?: string | string[]; - agents?: string | string[]; - skills?: string | string[]; - hooks?: string; - mcpServers?: string | Record; - outputStyles?: string | string[]; - lspServers?: string; -} - -export type ClaudePluginSource = - | { source: 'github'; repo: string } - | { source: 'url'; url: string }; - -export interface ClaudeMarketplacePluginConfig extends ClaudePluginConfig { - source: string | ClaudePluginSource; - category?: string; - strict?: boolean; - tags?: string[]; -} - -export interface ClaudeMarketplaceConfig { - name: string; - owner: { name: string; email: string }; - plugins: ClaudeMarketplacePluginConfig[]; - metadata?: { description?: string; version?: string; pluginRoot?: string }; -} - -/** - * Converts a Claude plugin config to Qwen Code format. - * @param claudeConfig Claude plugin configuration - * @returns Qwen ExtensionConfig - */ -export function convertClaudeToQwenConfig( - claudeConfig: ClaudePluginConfig, -): ExtensionConfig { - // Validate required fields - if (!claudeConfig.name || !claudeConfig.version) { - throw new Error('Claude plugin config must have name and version fields'); - } - - // Parse MCP servers - let mcpServers: Record | undefined; - if (claudeConfig.mcpServers) { - if (typeof claudeConfig.mcpServers === 'string') { - // TODO: Load from file path - console.warn( - `[Claude Converter] MCP servers path not yet supported: ${claudeConfig.mcpServers}`, - ); - } else { - mcpServers = claudeConfig.mcpServers; - } - } - - // Warn about unsupported fields - if (claudeConfig.hooks) { - console.warn( - `[Claude Converter] Hooks are not yet supported in ${claudeConfig.name}`, - ); - } - if (claudeConfig.outputStyles) { - console.warn( - `[Claude Converter] Output styles are not yet supported in ${claudeConfig.name}`, - ); - } - if (claudeConfig.lspServers) { - console.warn( - `[Claude Converter] LSP servers are not yet supported in ${claudeConfig.name}`, - ); - } - - // Direct field mapping - return { - name: claudeConfig.name, - version: claudeConfig.version, - mcpServers, - commands: claudeConfig.commands, - skills: claudeConfig.skills, - agents: claudeConfig.agents, - }; -} - -/** - * Merges marketplace plugin config with the actual plugin.json config. - * Marketplace config takes precedence for conflicting fields. - * @param marketplacePlugin Marketplace plugin definition - * @param pluginConfig Actual plugin.json config (optional if strict=false) - * @returns Merged Claude plugin config - */ -export function mergeClaudeConfigs( - marketplacePlugin: ClaudeMarketplacePluginConfig, - pluginConfig?: ClaudePluginConfig, -): ClaudePluginConfig { - if (!pluginConfig && marketplacePlugin.strict !== false) { - throw new Error( - `Plugin ${marketplacePlugin.name} requires plugin.json (strict mode)`, - ); - } - - // Start with plugin.json config (if exists) - const merged: ClaudePluginConfig = pluginConfig - ? { ...pluginConfig } - : { - name: marketplacePlugin.name, - version: '1.0.0', // Default version if not in marketplace - }; - - // Overlay marketplace config (takes precedence) - if (marketplacePlugin.name) merged.name = marketplacePlugin.name; - if (marketplacePlugin.version) merged.version = marketplacePlugin.version; - if (marketplacePlugin.description) - merged.description = marketplacePlugin.description; - if (marketplacePlugin.author) merged.author = marketplacePlugin.author; - if (marketplacePlugin.homepage) merged.homepage = marketplacePlugin.homepage; - if (marketplacePlugin.repository) - merged.repository = marketplacePlugin.repository; - if (marketplacePlugin.license) merged.license = marketplacePlugin.license; - if (marketplacePlugin.keywords) merged.keywords = marketplacePlugin.keywords; - if (marketplacePlugin.commands) merged.commands = marketplacePlugin.commands; - if (marketplacePlugin.agents) merged.agents = marketplacePlugin.agents; - if (marketplacePlugin.skills) merged.skills = marketplacePlugin.skills; - if (marketplacePlugin.hooks) merged.hooks = marketplacePlugin.hooks; - if (marketplacePlugin.mcpServers) - merged.mcpServers = marketplacePlugin.mcpServers; - if (marketplacePlugin.outputStyles) - merged.outputStyles = marketplacePlugin.outputStyles; - if (marketplacePlugin.lspServers) - merged.lspServers = marketplacePlugin.lspServers; - - return merged; -} - -/** - * Checks if a config object is in Claude plugin format. - * @param config Configuration object to check - * @returns true if config appears to be Claude format - */ -export function isClaudePluginConfig( - config: unknown, -): config is ClaudePluginConfig { - if (typeof config !== 'object' || config === null) { - return false; - } - - const obj = config as Record; - - // Must have name and version - if (typeof obj['name'] !== 'string' || typeof obj['version'] !== 'string') { - return false; - } - - // Check for Claude-specific fields - const hasClaudeFields = - 'agents' in obj || - 'hooks' in obj || - 'outputStyles' in obj || - 'lspServers' in obj; - - return hasClaudeFields; -} diff --git a/packages/cli/src/config/extensions/extensionEnablement.test.ts b/packages/cli/src/config/extensions/extensionEnablement.test.ts deleted file mode 100644 index b87fc2d814f..00000000000 --- a/packages/cli/src/config/extensions/extensionEnablement.test.ts +++ /dev/null @@ -1,424 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import * as path from 'node:path'; -import fs from 'node:fs'; -import os from 'node:os'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ExtensionEnablementManager, Override } from './extensionEnablement.js'; -import type { Extension } from '../extension.js'; - -// Helper to create a temporary directory for testing -function createTestDir() { - const dirPath = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-test-')); - return { - path: dirPath, - cleanup: () => fs.rmSync(dirPath, { recursive: true, force: true }), - }; -} - -let testDir: { path: string; cleanup: () => void }; -let configDir: string; -let manager: ExtensionEnablementManager; - -describe('ExtensionEnablementManager', () => { - beforeEach(() => { - testDir = createTestDir(); - configDir = path.join(testDir.path, '.gemini'); - manager = new ExtensionEnablementManager(configDir); - }); - - afterEach(() => { - testDir.cleanup(); - // Reset the singleton instance for test isolation - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (ExtensionEnablementManager as any).instance = undefined; - }); - - describe('isEnabled', () => { - it('should return true if extension is not configured', () => { - expect(manager.isEnabled('ext-test', '/any/path')).toBe(true); - }); - - it('should return true if no overrides match', () => { - manager.disable('ext-test', false, '/another/path'); - expect(manager.isEnabled('ext-test', '/any/path')).toBe(true); - }); - - it('should enable a path based on an override rule', () => { - manager.disable('ext-test', true, '/'); - manager.enable('ext-test', true, '/home/user/projects/'); - expect(manager.isEnabled('ext-test', '/home/user/projects/my-app')).toBe( - true, - ); - }); - - it('should disable a path based on a disable override rule', () => { - manager.enable('ext-test', true, '/'); - manager.disable('ext-test', true, '/home/user/projects/'); - expect(manager.isEnabled('ext-test', '/home/user/projects/my-app')).toBe( - false, - ); - }); - - it('should respect the last matching rule (enable wins)', () => { - manager.disable('ext-test', true, '/home/user/projects/'); - manager.enable('ext-test', false, '/home/user/projects/my-app'); - expect(manager.isEnabled('ext-test', '/home/user/projects/my-app')).toBe( - true, - ); - }); - - it('should respect the last matching rule (disable wins)', () => { - manager.enable('ext-test', true, '/home/user/projects/'); - manager.disable('ext-test', false, '/home/user/projects/my-app'); - expect(manager.isEnabled('ext-test', '/home/user/projects/my-app')).toBe( - false, - ); - }); - - it('should handle', () => { - manager.enable('ext-test', true, '/home/user/projects'); - manager.disable('ext-test', false, '/home/user/projects/my-app'); - expect(manager.isEnabled('ext-test', '/home/user/projects/my-app')).toBe( - false, - ); - expect( - manager.isEnabled('ext-test', '/home/user/projects/something-else'), - ).toBe(true); - }); - }); - - describe('includeSubdirs', () => { - it('should add a glob when enabling with includeSubdirs', () => { - manager.enable('ext-test', true, '/path/to/dir'); - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('/path/to/dir/*'); - }); - - it('should not add a glob when enabling without includeSubdirs', () => { - manager.enable('ext-test', false, '/path/to/dir'); - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('/path/to/dir/'); - expect(config['ext-test'].overrides).not.toContain('/path/to/dir/*'); - }); - - it('should add a glob when disabling with includeSubdirs', () => { - manager.disable('ext-test', true, '/path/to/dir'); - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('!/path/to/dir/*'); - }); - - it('should remove conflicting glob rule when enabling without subdirs', () => { - manager.enable('ext-test', true, '/path/to/dir'); // Adds /path/to/dir* - manager.enable('ext-test', false, '/path/to/dir'); // Should remove the glob - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('/path/to/dir/'); - expect(config['ext-test'].overrides).not.toContain('/path/to/dir/*'); - }); - - it('should remove conflicting non-glob rule when enabling with subdirs', () => { - manager.enable('ext-test', false, '/path/to/dir'); // Adds /path/to/dir - manager.enable('ext-test', true, '/path/to/dir'); // Should remove the non-glob - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('/path/to/dir/*'); - expect(config['ext-test'].overrides).not.toContain('/path/to/dir/'); - }); - - it('should remove conflicting rules when disabling', () => { - manager.enable('ext-test', true, '/path/to/dir'); // enabled with glob - manager.disable('ext-test', false, '/path/to/dir'); // disabled without - const config = manager.readConfig(); - expect(config['ext-test'].overrides).toContain('!/path/to/dir/'); - expect(config['ext-test'].overrides).not.toContain('/path/to/dir/*'); - }); - - it('should correctly evaluate isEnabled with subdirs', () => { - manager.disable('ext-test', true, '/'); - manager.enable('ext-test', true, '/path/to/dir'); - expect(manager.isEnabled('ext-test', '/path/to/dir/')).toBe(true); - expect(manager.isEnabled('ext-test', '/path/to/dir/sub/')).toBe(true); - expect(manager.isEnabled('ext-test', '/path/to/another/')).toBe(false); - }); - - it('should correctly evaluate isEnabled without subdirs', () => { - manager.disable('ext-test', true, '/*'); - manager.enable('ext-test', false, '/path/to/dir'); - expect(manager.isEnabled('ext-test', '/path/to/dir')).toBe(true); - expect(manager.isEnabled('ext-test', '/path/to/dir/sub')).toBe(false); - }); - }); - - describe('pruning child rules', () => { - it('should remove child rules when enabling a parent with subdirs', () => { - // Pre-existing rules for children - manager.enable('ext-test', false, '/path/to/dir/subdir1'); - manager.disable('ext-test', true, '/path/to/dir/subdir2'); - manager.enable('ext-test', false, '/path/to/another/dir'); - - // Enable the parent directory - manager.enable('ext-test', true, '/path/to/dir'); - - const config = manager.readConfig(); - const overrides = config['ext-test'].overrides; - - // The new parent rule should be present - expect(overrides).toContain(`/path/to/dir/*`); - - // Child rules should be removed - expect(overrides).not.toContain('/path/to/dir/subdir1/'); - expect(overrides).not.toContain(`!/path/to/dir/subdir2/*`); - - // Unrelated rules should remain - expect(overrides).toContain('/path/to/another/dir/'); - }); - - it('should remove child rules when disabling a parent with subdirs', () => { - // Pre-existing rules for children - manager.enable('ext-test', false, '/path/to/dir/subdir1'); - manager.disable('ext-test', true, '/path/to/dir/subdir2'); - manager.enable('ext-test', false, '/path/to/another/dir'); - - // Disable the parent directory - manager.disable('ext-test', true, '/path/to/dir'); - - const config = manager.readConfig(); - const overrides = config['ext-test'].overrides; - - // The new parent rule should be present - expect(overrides).toContain(`!/path/to/dir/*`); - - // Child rules should be removed - expect(overrides).not.toContain('/path/to/dir/subdir1/'); - expect(overrides).not.toContain(`!/path/to/dir/subdir2/*`); - - // Unrelated rules should remain - expect(overrides).toContain('/path/to/another/dir/'); - }); - - it('should not remove child rules if includeSubdirs is false', () => { - manager.enable('ext-test', false, '/path/to/dir/subdir1'); - manager.enable('ext-test', false, '/path/to/dir'); // Not including subdirs - - const config = manager.readConfig(); - const overrides = config['ext-test'].overrides; - - expect(overrides).toContain('/path/to/dir/subdir1/'); - expect(overrides).toContain('/path/to/dir/'); - }); - }); - - it('should enable a path based on an enable override', () => { - manager.disable('ext-test', true, '/Users/chrstn'); - manager.enable('ext-test', true, '/Users/chrstn/gemini-cli'); - - expect(manager.isEnabled('ext-test', '/Users/chrstn/gemini-cli')).toBe( - true, - ); - }); - - it('should ignore subdirs', () => { - manager.disable('ext-test', false, '/Users/chrstn'); - expect(manager.isEnabled('ext-test', '/Users/chrstn/gemini-cli')).toBe( - true, - ); - }); - - describe('extension overrides (-e )', () => { - beforeEach(() => { - manager = new ExtensionEnablementManager(configDir, ['ext-test']); - }); - - it('can enable extensions, case-insensitive', () => { - manager.disable('ext-test', true, '/'); - expect(manager.isEnabled('ext-test', '/')).toBe(true); - expect(manager.isEnabled('Ext-Test', '/')).toBe(true); - // Double check that it would have been disabled otherwise - expect( - new ExtensionEnablementManager(configDir).isEnabled('ext-test', '/'), - ).toBe(false); - }); - - it('disable all other extensions', () => { - manager = new ExtensionEnablementManager(configDir, ['ext-test']); - manager.enable('ext-test-2', true, '/'); - expect(manager.isEnabled('ext-test-2', '/')).toBe(false); - // Double check that it would have been enabled otherwise - expect( - new ExtensionEnablementManager(configDir).isEnabled('ext-test-2', '/'), - ).toBe(true); - }); - - it('none disables all extensions', () => { - manager = new ExtensionEnablementManager(configDir, ['none']); - manager.enable('ext-test', true, '/'); - expect(manager.isEnabled('ext-test', '/path/to/dir')).toBe(false); - // Double check that it would have been enabled otherwise - expect( - new ExtensionEnablementManager(configDir).isEnabled('ext-test', '/'), - ).toBe(true); - }); - }); - - describe('validateExtensionOverrides', () => { - let consoleErrorSpy: ReturnType; - - beforeEach(() => { - consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - }); - - afterEach(() => { - consoleErrorSpy.mockRestore(); - }); - - it('should not log an error if enabledExtensionNamesOverride is empty', () => { - const manager = new ExtensionEnablementManager(configDir, []); - manager.validateExtensionOverrides([]); - expect(consoleErrorSpy).not.toHaveBeenCalled(); - }); - - it('should not log an error if all enabledExtensionNamesOverride are valid', () => { - const manager = new ExtensionEnablementManager(configDir, [ - 'ext-one', - 'ext-two', - ]); - const extensions = [ - { config: { name: 'ext-one' } }, - { config: { name: 'ext-two' } }, - ] as Extension[]; - manager.validateExtensionOverrides(extensions); - expect(consoleErrorSpy).not.toHaveBeenCalled(); - }); - - it('should log an error for each invalid extension name in enabledExtensionNamesOverride', () => { - const manager = new ExtensionEnablementManager(configDir, [ - 'ext-one', - 'ext-invalid', - 'ext-another-invalid', - ]); - const extensions = [ - { config: { name: 'ext-one' } }, - { config: { name: 'ext-two' } }, - ] as Extension[]; - manager.validateExtensionOverrides(extensions); - expect(consoleErrorSpy).toHaveBeenCalledTimes(2); - expect(consoleErrorSpy).toHaveBeenCalledWith( - 'Extension not found: ext-invalid', - ); - expect(consoleErrorSpy).toHaveBeenCalledWith( - 'Extension not found: ext-another-invalid', - ); - }); - - it('should not log an error if "none" is in enabledExtensionNamesOverride', () => { - const manager = new ExtensionEnablementManager(configDir, ['none']); - manager.validateExtensionOverrides([]); - expect(consoleErrorSpy).not.toHaveBeenCalled(); - }); - }); -}); - -describe('Override', () => { - it('should create an override from input', () => { - const override = Override.fromInput('/path/to/dir', true); - expect(override.baseRule).toBe(`/path/to/dir/`); - expect(override.isDisable).toBe(false); - expect(override.includeSubdirs).toBe(true); - }); - - it('should create a disable override from input', () => { - const override = Override.fromInput('!/path/to/dir', false); - expect(override.baseRule).toBe(`/path/to/dir/`); - expect(override.isDisable).toBe(true); - expect(override.includeSubdirs).toBe(false); - }); - - it('should create an override from a file rule', () => { - const override = Override.fromFileRule('/path/to/dir'); - expect(override.baseRule).toBe('/path/to/dir'); - expect(override.isDisable).toBe(false); - expect(override.includeSubdirs).toBe(false); - }); - - it('should create a disable override from a file rule', () => { - const override = Override.fromFileRule('!/path/to/dir/'); - expect(override.isDisable).toBe(true); - expect(override.baseRule).toBe('/path/to/dir/'); - expect(override.includeSubdirs).toBe(false); - }); - - it('should create an override with subdirs from a file rule', () => { - const override = Override.fromFileRule('/path/to/dir/*'); - expect(override.baseRule).toBe('/path/to/dir/'); - expect(override.isDisable).toBe(false); - expect(override.includeSubdirs).toBe(true); - }); - - it('should correctly identify conflicting overrides', () => { - const override1 = Override.fromInput('/path/to/dir', true); - const override2 = Override.fromInput('/path/to/dir', false); - expect(override1.conflictsWith(override2)).toBe(true); - }); - - it('should correctly identify non-conflicting overrides', () => { - const override1 = Override.fromInput('/path/to/dir', true); - const override2 = Override.fromInput('/path/to/another/dir', true); - expect(override1.conflictsWith(override2)).toBe(false); - }); - - it('should correctly identify equal overrides', () => { - const override1 = Override.fromInput('/path/to/dir', true); - const override2 = Override.fromInput('/path/to/dir', true); - expect(override1.isEqualTo(override2)).toBe(true); - }); - - it('should correctly identify unequal overrides', () => { - const override1 = Override.fromInput('/path/to/dir', true); - const override2 = Override.fromInput('!/path/to/dir', true); - expect(override1.isEqualTo(override2)).toBe(false); - }); - - it('should generate the correct regex', () => { - const override = Override.fromInput('/path/to/dir', true); - const regex = override.asRegex(); - expect(regex.test('/path/to/dir/')).toBe(true); - expect(regex.test('/path/to/dir/subdir')).toBe(true); - expect(regex.test('/path/to/another/dir')).toBe(false); - }); - - it('should correctly identify child overrides', () => { - const parent = Override.fromInput('/path/to/dir', true); - const child = Override.fromInput('/path/to/dir/subdir', false); - expect(child.isChildOf(parent)).toBe(true); - }); - - it('should correctly identify child overrides with glob', () => { - const parent = Override.fromInput('/path/to/dir/*', true); - const child = Override.fromInput('/path/to/dir/subdir', false); - expect(child.isChildOf(parent)).toBe(true); - }); - - it('should correctly identify non-child overrides', () => { - const parent = Override.fromInput('/path/to/dir', true); - const other = Override.fromInput('/path/to/another/dir', false); - expect(other.isChildOf(parent)).toBe(false); - }); - - it('should generate the correct output string', () => { - const override = Override.fromInput('/path/to/dir', true); - expect(override.output()).toBe(`/path/to/dir/*`); - }); - - it('should generate the correct output string for a disable override', () => { - const override = Override.fromInput('!/path/to/dir', false); - expect(override.output()).toBe(`!/path/to/dir/`); - }); - - it('should disable a path based on a disable override rule', () => { - const override = Override.fromInput('!/path/to/dir', false); - expect(override.output()).toBe(`!/path/to/dir/`); - }); -}); diff --git a/packages/cli/src/config/extensions/extensionEnablement.ts b/packages/cli/src/config/extensions/extensionEnablement.ts deleted file mode 100644 index 737bc08d4d5..00000000000 --- a/packages/cli/src/config/extensions/extensionEnablement.ts +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import fs from 'node:fs'; -import path from 'node:path'; -import { type Extension } from '../extension.js'; - -export interface ExtensionEnablementConfig { - overrides: string[]; -} - -export interface AllExtensionsEnablementConfig { - [extensionName: string]: ExtensionEnablementConfig; -} - -export class Override { - constructor( - public baseRule: string, - public isDisable: boolean, - public includeSubdirs: boolean, - ) {} - - static fromInput(inputRule: string, includeSubdirs: boolean): Override { - const isDisable = inputRule.startsWith('!'); - let baseRule = isDisable ? inputRule.substring(1) : inputRule; - baseRule = ensureLeadingAndTrailingSlash(baseRule); - return new Override(baseRule, isDisable, includeSubdirs); - } - - static fromFileRule(fileRule: string): Override { - const isDisable = fileRule.startsWith('!'); - let baseRule = isDisable ? fileRule.substring(1) : fileRule; - const includeSubdirs = baseRule.endsWith('*'); - baseRule = includeSubdirs - ? baseRule.substring(0, baseRule.length - 1) - : baseRule; - return new Override(baseRule, isDisable, includeSubdirs); - } - - conflictsWith(other: Override): boolean { - if (this.baseRule === other.baseRule) { - return ( - this.includeSubdirs !== other.includeSubdirs || - this.isDisable !== other.isDisable - ); - } - return false; - } - - isEqualTo(other: Override): boolean { - return ( - this.baseRule === other.baseRule && - this.includeSubdirs === other.includeSubdirs && - this.isDisable === other.isDisable - ); - } - - asRegex(): RegExp { - return globToRegex(`${this.baseRule}${this.includeSubdirs ? '*' : ''}`); - } - - isChildOf(parent: Override) { - if (!parent.includeSubdirs) { - return false; - } - return parent.asRegex().test(this.baseRule); - } - - output(): string { - return `${this.isDisable ? '!' : ''}${this.baseRule}${this.includeSubdirs ? '*' : ''}`; - } - - matchesPath(path: string) { - return this.asRegex().test(path); - } -} - -const ensureLeadingAndTrailingSlash = function (dirPath: string): string { - // Normalize separators to forward slashes for consistent matching across platforms. - let result = dirPath.replace(/\\/g, '/'); - if (result.charAt(0) !== '/') { - result = '/' + result; - } - if (result.charAt(result.length - 1) !== '/') { - result = result + '/'; - } - return result; -}; - -/** - * Converts a glob pattern to a RegExp object. - * This is a simplified implementation that supports `*`. - * - * @param glob The glob pattern to convert. - * @returns A RegExp object. - */ -function globToRegex(glob: string): RegExp { - const regexString = glob - .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters - .replace(/(\/?)\*/g, '($1.*)?'); // Convert * to optional group - - return new RegExp(`^${regexString}$`); -} - -export class ExtensionEnablementManager { - private configFilePath: string; - private configDir: string; - // If non-empty, this overrides all other extension configuration and enables - // only the ones in this list. - private enabledExtensionNamesOverride: string[]; - - constructor(configDir: string, enabledExtensionNames?: string[]) { - this.configDir = configDir; - this.configFilePath = path.join(configDir, 'extension-enablement.json'); - this.enabledExtensionNamesOverride = - enabledExtensionNames?.map((name) => name.toLowerCase()) ?? []; - } - - validateExtensionOverrides(extensions: Extension[]) { - for (const name of this.enabledExtensionNamesOverride) { - if (name === 'none') continue; - if ( - !extensions.some( - (ext) => ext.config.name.toLowerCase() === name.toLowerCase(), - ) - ) { - console.error(`Extension not found: ${name}`); - } - } - } - - /** - * Determines if an extension is enabled based on its name and the current - * path. The last matching rule in the overrides list wins. - * - * @param extensionName The name of the extension. - * @param currentPath The absolute path of the current working directory. - * @returns True if the extension is enabled, false otherwise. - */ - isEnabled(extensionName: string, currentPath: string): boolean { - // If we have a single override called 'none', this disables all extensions. - // Typically, this comes from the user passing `-e none`. - if ( - this.enabledExtensionNamesOverride.length === 1 && - this.enabledExtensionNamesOverride[0] === 'none' - ) { - return false; - } - - // If we have explicit overrides, only enable those extensions. - if (this.enabledExtensionNamesOverride.length > 0) { - // When checking against overrides ONLY, we use a case insensitive match. - // The override names are already lowercased in the constructor. - return this.enabledExtensionNamesOverride.includes( - extensionName.toLocaleLowerCase(), - ); - } - - // Otherwise, we use the configuration settings - const config = this.readConfig(); - const extensionConfig = config[extensionName]; - // Extensions are enabled by default. - let enabled = true; - const allOverrides = extensionConfig?.overrides ?? []; - for (const rule of allOverrides) { - const override = Override.fromFileRule(rule); - if (override.matchesPath(ensureLeadingAndTrailingSlash(currentPath))) { - enabled = !override.isDisable; - } - } - return enabled; - } - - readConfig(): AllExtensionsEnablementConfig { - try { - const content = fs.readFileSync(this.configFilePath, 'utf-8'); - return JSON.parse(content); - } catch (error) { - if ( - error instanceof Error && - 'code' in error && - error.code === 'ENOENT' - ) { - return {}; - } - console.error('Error reading extension enablement config:', error); - return {}; - } - } - - writeConfig(config: AllExtensionsEnablementConfig): void { - fs.mkdirSync(this.configDir, { recursive: true }); - fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2)); - } - - enable( - extensionName: string, - includeSubdirs: boolean, - scopePath: string, - ): void { - const config = this.readConfig(); - if (!config[extensionName]) { - config[extensionName] = { overrides: [] }; - } - const override = Override.fromInput(scopePath, includeSubdirs); - const overrides = config[extensionName].overrides.filter((rule) => { - const fileOverride = Override.fromFileRule(rule); - if ( - fileOverride.conflictsWith(override) || - fileOverride.isEqualTo(override) - ) { - return false; // Remove conflicts and equivalent values. - } - return !fileOverride.isChildOf(override); - }); - overrides.push(override.output()); - config[extensionName].overrides = overrides; - this.writeConfig(config); - } - - disable( - extensionName: string, - includeSubdirs: boolean, - scopePath: string, - ): void { - this.enable(extensionName, includeSubdirs, `!${scopePath}`); - } - - remove(extensionName: string): void { - const config = this.readConfig(); - if (config[extensionName]) { - delete config[extensionName]; - this.writeConfig(config); - } - } -} diff --git a/packages/cli/src/config/extensions/update.test.ts b/packages/cli/src/config/extensions/update.test.ts deleted file mode 100644 index f7eea8d392b..00000000000 --- a/packages/cli/src/config/extensions/update.test.ts +++ /dev/null @@ -1,467 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import { vi } from 'vitest'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { annotateActiveExtensions, loadExtension } from '../extension.js'; -import { - EXTENSIONS_CONFIG_FILENAME, - INSTALL_METADATA_FILENAME, -} from './variables.js'; -import { ExtensionStorage } from './storage.js'; -import { checkForAllExtensionUpdates, updateExtension } from './update.js'; -import { QWEN_DIR } from '@qwen-code/qwen-code-core'; -import { isWorkspaceTrusted } from '../trustedFolders.js'; -import { ExtensionUpdateState } from '../../ui/state/extensions.js'; -import { createExtension } from '../../test-utils/createExtension.js'; -import { ExtensionEnablementManager } from './extensionEnablement.js'; - -const mockGit = { - clone: vi.fn(), - getRemotes: vi.fn(), - fetch: vi.fn(), - checkout: vi.fn(), - listRemote: vi.fn(), - revparse: vi.fn(), - // Not a part of the actual API, but we need to use this to do the correct - // file system interactions. - path: vi.fn(), -}; - -vi.mock('simple-git', () => ({ - simpleGit: vi.fn((path: string) => { - mockGit.path.mockReturnValue(path); - return mockGit; - }), -})); - -vi.mock('../extensions/github.js', async (importOriginal) => { - const actual = - await importOriginal(); - return { - ...actual, - downloadFromGitHubRelease: vi - .fn() - .mockRejectedValue(new Error('Mocked GitHub release download failure')), - }; -}); - -vi.mock('os', async (importOriginal) => { - const mockedOs = await importOriginal(); - return { - ...mockedOs, - homedir: vi.fn(), - }; -}); - -vi.mock('../trustedFolders.js', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - isWorkspaceTrusted: vi.fn(), - }; -}); - -const mockLogExtensionInstallEvent = vi.hoisted(() => vi.fn()); -const mockLogExtensionUninstall = vi.hoisted(() => vi.fn()); - -vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { - const actual = - await importOriginal(); - return { - ...actual, - logExtensionInstallEvent: mockLogExtensionInstallEvent, - logExtensionUninstall: mockLogExtensionUninstall, - ExtensionInstallEvent: vi.fn(), - ExtensionUninstallEvent: vi.fn(), - }; -}); - -describe('update tests', () => { - let tempHomeDir: string; - let tempWorkspaceDir: string; - let userExtensionsDir: string; - - beforeEach(() => { - tempHomeDir = fs.mkdtempSync( - path.join(os.tmpdir(), 'qwen-code-test-home-'), - ); - tempWorkspaceDir = fs.mkdtempSync( - path.join(tempHomeDir, 'qwen-code-test-workspace-'), - ); - vi.mocked(os.homedir).mockReturnValue(tempHomeDir); - userExtensionsDir = path.join(tempHomeDir, QWEN_DIR, 'extensions'); - // Clean up before each test - fs.rmSync(userExtensionsDir, { recursive: true, force: true }); - fs.mkdirSync(userExtensionsDir, { recursive: true }); - vi.mocked(isWorkspaceTrusted).mockReturnValue({ - isTrusted: true, - source: 'file', - }); - vi.spyOn(process, 'cwd').mockReturnValue(tempWorkspaceDir); - Object.values(mockGit).forEach((fn) => fn.mockReset()); - }); - - afterEach(() => { - fs.rmSync(tempHomeDir, { recursive: true, force: true }); - fs.rmSync(tempWorkspaceDir, { recursive: true, force: true }); - }); - - describe('updateExtension', () => { - it('should update a git-installed extension', async () => { - const gitUrl = 'https://github.com/google/gemini-extensions.git'; - const extensionName = 'qwen-extensions'; - const targetExtDir = path.join(userExtensionsDir, extensionName); - const metadataPath = path.join(targetExtDir, INSTALL_METADATA_FILENAME); - - fs.mkdirSync(targetExtDir, { recursive: true }); - fs.writeFileSync( - path.join(targetExtDir, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify({ name: extensionName, version: '1.0.0' }), - ); - fs.writeFileSync( - metadataPath, - JSON.stringify({ source: gitUrl, type: 'git' }), - ); - - mockGit.clone.mockImplementation(async (_, destination) => { - fs.mkdirSync(path.join(mockGit.path(), destination), { - recursive: true, - }); - fs.writeFileSync( - path.join(mockGit.path(), destination, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify({ name: extensionName, version: '1.1.0' }), - ); - }); - mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir: targetExtDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - const updateInfo = await updateExtension( - extension, - tempHomeDir, - async (_) => true, - ExtensionUpdateState.UPDATE_AVAILABLE, - () => {}, - ); - - expect(updateInfo).toEqual({ - name: 'qwen-extensions', - originalVersion: '1.0.0', - updatedVersion: '1.1.0', - }); - - const updatedConfig = JSON.parse( - fs.readFileSync( - path.join(targetExtDir, EXTENSIONS_CONFIG_FILENAME), - 'utf-8', - ), - ); - expect(updatedConfig.version).toBe('1.1.0'); - }); - - it('should call setExtensionUpdateState with UPDATING and then UPDATED_NEEDS_RESTART on success', async () => { - const extensionName = 'test-extension'; - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: extensionName, - version: '1.0.0', - installMetadata: { - source: 'https://some.git/repo', - type: 'git', - }, - }); - - mockGit.clone.mockImplementation(async (_, destination) => { - fs.mkdirSync(path.join(mockGit.path(), destination), { - recursive: true, - }); - fs.writeFileSync( - path.join(mockGit.path(), destination, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify({ name: extensionName, version: '1.1.0' }), - ); - }); - mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]); - - const dispatch = vi.fn(); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - await updateExtension( - extension, - tempHomeDir, - async (_) => true, - ExtensionUpdateState.UPDATE_AVAILABLE, - dispatch, - ); - - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: extensionName, - state: ExtensionUpdateState.UPDATING, - }, - }); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: extensionName, - state: ExtensionUpdateState.UPDATED_NEEDS_RESTART, - }, - }); - }); - - it('should call setExtensionUpdateState with ERROR on failure', async () => { - const extensionName = 'test-extension'; - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: extensionName, - version: '1.0.0', - installMetadata: { - source: 'https://some.git/repo', - type: 'git', - }, - }); - - mockGit.clone.mockRejectedValue(new Error('Git clone failed')); - mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]); - - const dispatch = vi.fn(); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - await expect( - updateExtension( - extension, - tempHomeDir, - async (_) => true, - ExtensionUpdateState.UPDATE_AVAILABLE, - dispatch, - ), - ).rejects.toThrow(); - - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: extensionName, - state: ExtensionUpdateState.UPDATING, - }, - }); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: extensionName, - state: ExtensionUpdateState.ERROR, - }, - }); - }); - }); - - describe('checkForAllExtensionUpdates', () => { - it('should return UpdateAvailable for a git extension with updates', async () => { - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'test-extension', - version: '1.0.0', - installMetadata: { - source: 'https://some.git/repo', - type: 'git', - }, - }); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - - mockGit.getRemotes.mockResolvedValue([ - { name: 'origin', refs: { fetch: 'https://some.git/repo' } }, - ]); - mockGit.listRemote.mockResolvedValue('remoteHash HEAD'); - mockGit.revparse.mockResolvedValue('localHash'); - - const dispatch = vi.fn(); - await checkForAllExtensionUpdates([extension], dispatch); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: 'test-extension', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); - }); - - it('should return UpToDate for a git extension with no updates', async () => { - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'test-extension', - version: '1.0.0', - installMetadata: { - source: 'https://some.git/repo', - type: 'git', - }, - }); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - - mockGit.getRemotes.mockResolvedValue([ - { name: 'origin', refs: { fetch: 'https://some.git/repo' } }, - ]); - mockGit.listRemote.mockResolvedValue('sameHash HEAD'); - mockGit.revparse.mockResolvedValue('sameHash'); - - const dispatch = vi.fn(); - await checkForAllExtensionUpdates([extension], dispatch); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: 'test-extension', - state: ExtensionUpdateState.UP_TO_DATE, - }, - }); - }); - - it('should return UpToDate for a local extension with no updates', async () => { - const localExtensionSourcePath = path.join(tempHomeDir, 'local-source'); - const sourceExtensionDir = createExtension({ - extensionsDir: localExtensionSourcePath, - name: 'my-local-ext', - version: '1.0.0', - }); - - const installedExtensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'local-extension', - version: '1.0.0', - installMetadata: { source: sourceExtensionDir, type: 'local' }, - }); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir: installedExtensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - const dispatch = vi.fn(); - await checkForAllExtensionUpdates([extension], dispatch); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: 'local-extension', - state: ExtensionUpdateState.UP_TO_DATE, - }, - }); - }); - - it('should return UpdateAvailable for a local extension with updates', async () => { - const localExtensionSourcePath = path.join(tempHomeDir, 'local-source'); - const sourceExtensionDir = createExtension({ - extensionsDir: localExtensionSourcePath, - name: 'my-local-ext', - version: '1.1.0', - }); - - const installedExtensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'local-extension', - version: '1.0.0', - installMetadata: { source: sourceExtensionDir, type: 'local' }, - }); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir: installedExtensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - const dispatch = vi.fn(); - await checkForAllExtensionUpdates([extension], dispatch); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: 'local-extension', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); - }); - - it('should return Error when git check fails', async () => { - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'error-extension', - version: '1.0.0', - installMetadata: { - source: 'https://some.git/repo', - type: 'git', - }, - }); - const extension = annotateActiveExtensions( - [ - loadExtension({ - extensionDir, - workspaceDir: tempWorkspaceDir, - })!, - ], - process.cwd(), - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - )[0]; - - mockGit.getRemotes.mockRejectedValue(new Error('Git error')); - - const dispatch = vi.fn(); - await checkForAllExtensionUpdates([extension], dispatch); - expect(dispatch).toHaveBeenCalledWith({ - type: 'SET_STATE', - payload: { - name: 'error-extension', - state: ExtensionUpdateState.ERROR, - }, - }); - }); - }); -}); diff --git a/packages/cli/src/config/extensions/update.ts b/packages/cli/src/config/extensions/update.ts deleted file mode 100644 index 16f298a0275..00000000000 --- a/packages/cli/src/config/extensions/update.ts +++ /dev/null @@ -1,183 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import { - type ExtensionUpdateAction, - ExtensionUpdateState, - type ExtensionUpdateStatus, -} from '../../ui/state/extensions.js'; -import { - copyExtension, - installExtension, - uninstallExtension, - loadExtension, - loadInstallMetadata, - loadExtensionConfig, -} from '../extension.js'; - -import { checkForExtensionUpdate } from './github.js'; -import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; -import * as fs from 'node:fs'; -import { getErrorMessage } from '../../utils/errors.js'; -import { ExtensionStorage } from './storage.js'; - -export interface ExtensionUpdateInfo { - name: string; - originalVersion: string; - updatedVersion: string; -} - -export async function updateExtension( - extension: GeminiCLIExtension, - cwd: string = process.cwd(), - requestConsent: (consent: string) => Promise, - currentState: ExtensionUpdateState, - dispatchExtensionStateUpdate: (action: ExtensionUpdateAction) => void, -): Promise { - if (currentState === ExtensionUpdateState.UPDATING) { - return undefined; - } - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { name: extension.name, state: ExtensionUpdateState.UPDATING }, - }); - const installMetadata = loadInstallMetadata(extension.path); - - if (!installMetadata?.type) { - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { name: extension.name, state: ExtensionUpdateState.ERROR }, - }); - throw new Error( - `Extension ${extension.name} cannot be updated, type is unknown.`, - ); - } - if (installMetadata?.type === 'link') { - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { name: extension.name, state: ExtensionUpdateState.UP_TO_DATE }, - }); - throw new Error(`Extension is linked so does not need to be updated`); - } - const originalVersion = extension.version; - - const tempDir = await ExtensionStorage.createTmpDir(); - try { - await copyExtension(extension.path, tempDir); - const previousExtensionConfig = await loadExtensionConfig({ - extensionDir: extension.path, - workspaceDir: cwd, - }); - await uninstallExtension(extension.name, cwd); - await installExtension( - installMetadata, - requestConsent, - cwd, - previousExtensionConfig, - ); - - const updatedExtensionStorage = new ExtensionStorage(extension.name); - const updatedExtension = loadExtension({ - extensionDir: updatedExtensionStorage.getExtensionDir(), - workspaceDir: cwd, - }); - if (!updatedExtension) { - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { name: extension.name, state: ExtensionUpdateState.ERROR }, - }); - throw new Error('Updated extension not found after installation.'); - } - const updatedVersion = updatedExtension.config.version; - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { - name: extension.name, - state: ExtensionUpdateState.UPDATED_NEEDS_RESTART, - }, - }); - return { - name: extension.name, - originalVersion, - updatedVersion, - }; - } catch (e) { - console.error( - `Error updating extension, rolling back. ${getErrorMessage(e)}`, - ); - dispatchExtensionStateUpdate({ - type: 'SET_STATE', - payload: { name: extension.name, state: ExtensionUpdateState.ERROR }, - }); - await copyExtension(tempDir, extension.path); - throw e; - } finally { - await fs.promises.rm(tempDir, { recursive: true, force: true }); - } -} - -export async function updateAllUpdatableExtensions( - cwd: string = process.cwd(), - requestConsent: (consent: string) => Promise, - extensions: GeminiCLIExtension[], - extensionsState: Map, - dispatch: (action: ExtensionUpdateAction) => void, -): Promise { - return ( - await Promise.all( - extensions - .filter( - (extension) => - extensionsState.get(extension.name)?.status === - ExtensionUpdateState.UPDATE_AVAILABLE, - ) - .map((extension) => - updateExtension( - extension, - cwd, - requestConsent, - extensionsState.get(extension.name)!.status, - dispatch, - ), - ), - ) - ).filter((updateInfo) => !!updateInfo); -} - -export interface ExtensionUpdateCheckResult { - state: ExtensionUpdateState; - error?: string; -} - -export async function checkForAllExtensionUpdates( - extensions: GeminiCLIExtension[], - dispatch: (action: ExtensionUpdateAction) => void, -): Promise { - dispatch({ type: 'BATCH_CHECK_START' }); - const promises: Array> = []; - for (const extension of extensions) { - if (!extension.installMetadata) { - dispatch({ - type: 'SET_STATE', - payload: { - name: extension.name, - state: ExtensionUpdateState.NOT_UPDATABLE, - }, - }); - continue; - } - promises.push( - checkForExtensionUpdate(extension, (updatedState) => { - dispatch({ - type: 'SET_STATE', - payload: { name: extension.name, state: updatedState }, - }); - }), - ); - } - await Promise.all(promises); - dispatch({ type: 'BATCH_CHECK_END' }); -} diff --git a/packages/cli/src/config/settings.test.ts b/packages/cli/src/config/settings.test.ts index 9db17b7d394..a2806ead2e0 100644 --- a/packages/cli/src/config/settings.test.ts +++ b/packages/cli/src/config/settings.test.ts @@ -51,7 +51,6 @@ import { import * as fs from 'node:fs'; // fs will be mocked separately import stripJsonComments from 'strip-json-comments'; // Will be mocked separately import { isWorkspaceTrusted } from './trustedFolders.js'; -import { disableExtension } from './extension.js'; // These imports will get the versions from the vi.mock('./settings.js', ...) factory. import { @@ -64,8 +63,6 @@ import { needsMigration, type Settings, loadEnvironment, - migrateDeprecatedSettings, - SettingScope, SETTINGS_VERSION, SETTINGS_VERSION_KEY, } from './settings.js'; @@ -2649,122 +2646,4 @@ describe('Settings Loading and Merging', () => { }); }); }); - - describe('migrateDeprecatedSettings', () => { - let mockFsExistsSync: Mocked; - let mockFsReadFileSync: Mocked; - let mockDisableExtension: Mocked; - - beforeEach(() => { - vi.resetAllMocks(); - - mockFsExistsSync = vi.mocked(fs.existsSync); - mockFsReadFileSync = vi.mocked(fs.readFileSync); - mockDisableExtension = vi.mocked(disableExtension); - - (mockFsExistsSync as Mock).mockReturnValue(true); - vi.mocked(isWorkspaceTrusted).mockReturnValue(true); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('should migrate disabled extensions from user and workspace settings', () => { - const userSettingsContent = { - extensions: { - disabled: ['user-ext-1', 'shared-ext'], - }, - }; - const workspaceSettingsContent = { - extensions: { - disabled: ['workspace-ext-1', 'shared-ext'], - }, - }; - - (mockFsReadFileSync as Mock).mockImplementation( - (p: fs.PathOrFileDescriptor) => { - if (p === USER_SETTINGS_PATH) - return JSON.stringify(userSettingsContent); - if (p === MOCK_WORKSPACE_SETTINGS_PATH) - return JSON.stringify(workspaceSettingsContent); - return '{}'; - }, - ); - - const loadedSettings = loadSettings(MOCK_WORKSPACE_DIR); - const setValueSpy = vi.spyOn(loadedSettings, 'setValue'); - - migrateDeprecatedSettings(loadedSettings, MOCK_WORKSPACE_DIR); - - // Check user settings migration - expect(mockDisableExtension).toHaveBeenCalledWith( - 'user-ext-1', - SettingScope.User, - MOCK_WORKSPACE_DIR, - ); - expect(mockDisableExtension).toHaveBeenCalledWith( - 'shared-ext', - SettingScope.User, - MOCK_WORKSPACE_DIR, - ); - - // Check workspace settings migration - expect(mockDisableExtension).toHaveBeenCalledWith( - 'workspace-ext-1', - SettingScope.Workspace, - MOCK_WORKSPACE_DIR, - ); - expect(mockDisableExtension).toHaveBeenCalledWith( - 'shared-ext', - SettingScope.Workspace, - MOCK_WORKSPACE_DIR, - ); - - // Check that setValue was called to remove the deprecated setting - expect(setValueSpy).toHaveBeenCalledWith( - SettingScope.User, - 'extensions', - { - disabled: undefined, - }, - ); - expect(setValueSpy).toHaveBeenCalledWith( - SettingScope.Workspace, - 'extensions', - { - disabled: undefined, - }, - ); - }); - - it('should not do anything if there are no deprecated settings', () => { - const userSettingsContent = { - extensions: { - enabled: ['user-ext-1'], - }, - }; - const workspaceSettingsContent = { - someOtherSetting: 'value', - }; - - (mockFsReadFileSync as Mock).mockImplementation( - (p: fs.PathOrFileDescriptor) => { - if (p === USER_SETTINGS_PATH) - return JSON.stringify(userSettingsContent); - if (p === MOCK_WORKSPACE_SETTINGS_PATH) - return JSON.stringify(workspaceSettingsContent); - return '{}'; - }, - ); - - const loadedSettings = loadSettings(MOCK_WORKSPACE_DIR); - const setValueSpy = vi.spyOn(loadedSettings, 'setValue'); - - migrateDeprecatedSettings(loadedSettings, MOCK_WORKSPACE_DIR); - - expect(mockDisableExtension).not.toHaveBeenCalled(); - expect(setValueSpy).not.toHaveBeenCalled(); - }); - }); }); diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index ae29074b293..b9199321afa 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -30,7 +30,6 @@ import { import { resolveEnvVarsInObject } from '../utils/envVarResolver.js'; import { customDeepMerge, type MergeableObject } from '../utils/deepMerge.js'; import { updateSettingsFilePreservingFormat } from '../utils/commentJson.js'; -import { disableExtension } from './extension.js'; function getMergeStrategyForPath(path: string[]): MergeStrategy | undefined { let current: SettingDefinition | undefined = undefined; @@ -81,7 +80,6 @@ const MIGRATION_MAP: Record = { excludeTools: 'tools.exclude', excludeMCPServers: 'mcp.excluded', excludedProjectEnvVars: 'advanced.excludedEnvVars', - extensionManagement: 'experimental.extensionManagement', extensions: 'extensions', fileFiltering: 'context.fileFiltering', folderTrustFeature: 'security.folderTrust.featureEnabled', @@ -812,31 +810,6 @@ export function loadSettings( ); } -export function migrateDeprecatedSettings( - loadedSettings: LoadedSettings, - workspaceDir: string = process.cwd(), -): void { - const processScope = (scope: SettingScope) => { - const settings = loadedSettings.forScope(scope).settings; - if (settings.extensions?.disabled) { - console.log( - `Migrating deprecated extensions.disabled settings from ${scope} settings...`, - ); - for (const extension of settings.extensions.disabled ?? []) { - disableExtension(extension, scope, workspaceDir); - } - - const newExtensionsValue = { ...settings.extensions }; - newExtensionsValue.disabled = undefined; - - loadedSettings.setValue(scope, 'extensions', newExtensionsValue); - } - }; - - processScope(SettingScope.User); - processScope(SettingScope.Workspace); -} - export function saveSettings(settingsFile: SettingsFile): void { try { // Ensure the directory exists diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 2fe467ba92c..9503f4ecfde 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -1192,15 +1192,6 @@ const SETTINGS_SCHEMA = { description: 'Setting to enable experimental features', showInDialog: false, properties: { - extensionManagement: { - type: 'boolean', - label: 'Extension Management', - category: 'Experimental', - requiresRestart: true, - default: true, - description: 'Enable extension management features.', - showInDialog: false, - }, visionModelPreview: { type: 'boolean', label: 'Vision Model Preview', @@ -1223,39 +1214,6 @@ const SETTINGS_SCHEMA = { }, }, }, - - extensions: { - type: 'object', - label: 'Extensions', - category: 'Extensions', - requiresRestart: true, - default: {}, - description: 'Settings for extensions.', - showInDialog: false, - properties: { - disabled: { - type: 'array', - label: 'Disabled Extensions', - category: 'Extensions', - requiresRestart: true, - default: [] as string[], - description: 'List of disabled extensions.', - showInDialog: false, - mergeStrategy: MergeStrategy.UNION, - }, - workspacesWithMigrationNudge: { - type: 'array', - label: 'Workspaces with Migration Nudge', - category: 'Extensions', - requiresRestart: false, - default: [] as string[], - description: - 'List of workspaces for which the migration nudge has been shown.', - showInDialog: false, - mergeStrategy: MergeStrategy.UNION, - }, - }, - }, } as const satisfies SettingsSchema; export type SettingsSchemaType = typeof SETTINGS_SCHEMA; diff --git a/packages/cli/src/gemini.test.tsx b/packages/cli/src/gemini.test.tsx index ad74bd279bd..a71df5f81b4 100644 --- a/packages/cli/src/gemini.test.tsx +++ b/packages/cli/src/gemini.test.tsx @@ -262,8 +262,6 @@ describe('gemini.tsx main function', () => { ); const { loadSettings } = await import('./config/settings.js'); const cleanupModule = await import('./utils/cleanup.js'); - const extensionModule = await import('./config/extension.js'); - const { ExtensionStorage } = await import('./config/extensions/storage.js'); const validatorModule = await import('./validateNonInterActiveAuth.js'); const streamJsonModule = await import('./nonInteractive/session.js'); const initializerModule = await import('./core/initializer.js'); @@ -276,10 +274,6 @@ describe('gemini.tsx main function', () => { vi.mocked(cleanupModule.registerCleanup).mockImplementation(() => {}); const runExitCleanupMock = vi.mocked(cleanupModule.runExitCleanup); runExitCleanupMock.mockResolvedValue(undefined); - vi.spyOn(extensionModule, 'loadExtensions').mockReturnValue([]); - vi.spyOn(ExtensionStorage, 'getUserExtensionsDir').mockReturnValue( - '/tmp/extensions', - ); vi.spyOn(initializerModule, 'initializeApp').mockResolvedValue({ authError: null, themeError: null, diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index b9dfb09a9e0..957842948f6 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -15,10 +15,8 @@ import React from 'react'; import { validateAuthMethod } from './config/auth.js'; import * as cliConfig from './config/config.js'; import { loadCliConfig, parseArguments } from './config/config.js'; -import { loadExtensions } from './config/extension.js'; -import { ExtensionStorage } from './config/extensions/storage.js'; import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js'; -import { loadSettings, migrateDeprecatedSettings } from './config/settings.js'; +import { loadSettings } from './config/settings.js'; import { initializeApp, type InitializationResult, @@ -104,7 +102,6 @@ function getNodeMemoryArgs(isDebugMode: boolean): string[] { return []; } -import { ExtensionEnablementManager } from './config/extensions/extensionEnablement.js'; import { loadSandboxConfig } from './config/sandboxConfig.js'; import { runAcpAgent } from './acp-integration/acpAgent.js'; @@ -201,10 +198,9 @@ export async function startInteractiveUI( export async function main() { setupUnhandledRejectionHandler(); const settings = loadSettings(); - migrateDeprecatedSettings(settings); await cleanupCheckpoints(); - let argv = await parseArguments(settings.merged); + let argv = await parseArguments(); // Check for invalid input combinations early to prevent crashes if (argv.promptInteractive && !process.stdin.isTTY) { @@ -246,9 +242,9 @@ export async function main() { if (sandboxConfig) { const partialConfig = await loadCliConfig( settings.merged, - [], - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), argv, + undefined, + [], ); if ( @@ -332,25 +328,21 @@ export async function main() { // to run Gemini CLI. It is now safe to perform expensive initialization that // may have side effects. { - const extensionEnablementManager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ); - const extensions = loadExtensions(extensionEnablementManager); const config = await loadCliConfig( settings.merged, - extensions, - extensionEnablementManager, argv, + process.cwd(), + argv.extensions, ); - if (config.getListExtensions()) { - console.log('Installed extensions:'); - for (const extension of extensions) { - console.log(`- ${extension.config.name}`); - } - process.exit(0); - } + // FIXME: list extensions after the config initialize + // if (config.getListExtensions()) { + // console.log('Installed extensions:'); + // for (const extension of extensions) { + // console.log(`- ${extension.config.name}`); + // } + // process.exit(0); + // } // Setup unified ConsolePatcher based on interactive mode const isInteractive = config.isInteractive(); @@ -396,7 +388,7 @@ export async function main() { } if (config.getExperimentalZedIntegration()) { - return runAcpAgent(config, settings, extensions, argv); + return runAcpAgent(config, settings, argv); } let input = config.getQuestion(); diff --git a/packages/cli/src/services/command-migration-tool.ts b/packages/cli/src/services/command-migration-tool.ts index 1bb4b8e134c..670632522c3 100644 --- a/packages/cli/src/services/command-migration-tool.ts +++ b/packages/cli/src/services/command-migration-tool.ts @@ -11,7 +11,7 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; import { glob } from 'glob'; -import { convertTomlToMarkdown } from './toml-to-markdown-converter.js'; +import { convertTomlToMarkdown } from '@qwen-code/qwen-code-core/src/utils/toml-to-markdown-converter.js'; export interface MigrationResult { success: boolean; diff --git a/packages/cli/src/ui/AppContainer.test.tsx b/packages/cli/src/ui/AppContainer.test.tsx index 60426f1dd40..ee17aa67aee 100644 --- a/packages/cli/src/ui/AppContainer.test.tsx +++ b/packages/cli/src/ui/AppContainer.test.tsx @@ -76,7 +76,6 @@ vi.mock('./hooks/useFolderTrust.js'); vi.mock('./hooks/useIdeTrustListener.js'); vi.mock('./hooks/useMessageQueue.js'); vi.mock('./hooks/useAutoAcceptIndicator.js'); -vi.mock('./hooks/useWorkspaceMigration.js'); vi.mock('./hooks/useGitBranchName.js'); vi.mock('./contexts/VimModeContext.js'); vi.mock('./contexts/SessionContext.js'); @@ -103,7 +102,6 @@ import { useFolderTrust } from './hooks/useFolderTrust.js'; import { useIdeTrustListener } from './hooks/useIdeTrustListener.js'; import { useMessageQueue } from './hooks/useMessageQueue.js'; import { useAutoAcceptIndicator } from './hooks/useAutoAcceptIndicator.js'; -import { useWorkspaceMigration } from './hooks/useWorkspaceMigration.js'; import { useGitBranchName } from './hooks/useGitBranchName.js'; import { useVimMode } from './contexts/VimModeContext.js'; import { useSessionStats } from './contexts/SessionContext.js'; @@ -134,7 +132,6 @@ describe('AppContainer State Management', () => { const mockedUseIdeTrustListener = useIdeTrustListener as Mock; const mockedUseMessageQueue = useMessageQueue as Mock; const mockedUseAutoAcceptIndicator = useAutoAcceptIndicator as Mock; - const mockedUseWorkspaceMigration = useWorkspaceMigration as Mock; const mockedUseGitBranchName = useGitBranchName as Mock; const mockedUseVimMode = useVimMode as Mock; const mockedUseSessionStats = useSessionStats as Mock; @@ -239,12 +236,6 @@ describe('AppContainer State Management', () => { getQueuedMessagesText: vi.fn().mockReturnValue(''), }); mockedUseAutoAcceptIndicator.mockReturnValue(false); - mockedUseWorkspaceMigration.mockReturnValue({ - showWorkspaceMigrationDialog: false, - workspaceExtensions: [], - onWorkspaceMigrationDialogOpen: vi.fn(), - onWorkspaceMigrationDialogClose: vi.fn(), - }); mockedUseGitBranchName.mockReturnValue('main'); mockedUseVimMode.mockReturnValue({ isVimEnabled: false, diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index d76a4fd69a8..6d69236dc13 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -87,10 +87,12 @@ import { ConsolePatcher } from './utils/ConsolePatcher.js'; import { registerCleanup, runExitCleanup } from '../utils/cleanup.js'; import { useMessageQueue } from './hooks/useMessageQueue.js'; import { useAutoAcceptIndicator } from './hooks/useAutoAcceptIndicator.js'; -import { useWorkspaceMigration } from './hooks/useWorkspaceMigration.js'; import { useSessionStats } from './contexts/SessionContext.js'; import { useGitBranchName } from './hooks/useGitBranchName.js'; -import { useExtensionUpdates } from './hooks/useExtensionUpdates.js'; +import { + useExtensionUpdates, + useConfirmUpdateRequests, +} from './hooks/useExtensionUpdates.js'; import { ShellFocusContext } from './contexts/ShellFocusContext.js'; import { t } from '../i18n/index.js'; import { useWelcomeBack } from './hooks/useWelcomeBack.js'; @@ -101,6 +103,7 @@ import { processVisionSwitchOutcome } from './hooks/useVisionAutoSwitch.js'; import { useSubagentCreateDialog } from './hooks/useSubagentCreateDialog.js'; import { useAgentsManagerDialog } from './hooks/useAgentsManagerDialog.js'; import { useAttentionNotifications } from './hooks/useAttentionNotifications.js'; +import { requestConsentInteractive } from '../commands/extensions/consent.js'; const CTRL_EXIT_PROMPT_DURATION_MS = 1000; @@ -161,15 +164,21 @@ export const AppContainer = (props: AppContainerProps) => { config.isTrustedFolder(), ); - const extensions = config.getExtensions(); + const extensionManager = config.getExtensionManager(); + + extensionManager.setRequestConsent((description) => + requestConsentInteractive(description, addConfirmUpdateExtensionRequest), + ); + + const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = + useConfirmUpdateRequests(); + const { extensionsUpdateState, extensionsUpdateStateInternal, dispatchExtensionStateUpdate, - confirmUpdateExtensionRequests, - addConfirmUpdateExtensionRequest, } = useExtensionUpdates( - extensions, + extensionManager, historyManager.addItem, config.getWorkingDir(), ); @@ -440,13 +449,6 @@ export const AppContainer = (props: AppContainerProps) => { remount: refreshStatic, }); - const { - showWorkspaceMigrationDialog, - workspaceExtensions, - onWorkspaceMigrationDialogOpen, - onWorkspaceMigrationDialogClose, - } = useWorkspaceMigration(settings); - const { toggleVimEnabled } = useVimMode(); const { @@ -582,11 +584,11 @@ export const AppContainer = (props: AppContainerProps) => { : [], config.getDebugMode(), config.getFileService(), - settings.merged, config.getExtensionContextFilePaths(), config.isTrustedFolder(), settings.merged.context?.importFormat || 'tree', // Use setting or default to 'tree' config.getFileFilteringOptions(), + config.getDiscoveryMaxDirs(), ); config.setUserMemory(memoryContent); @@ -1274,7 +1276,6 @@ export const AppContainer = (props: AppContainerProps) => { const dialogsVisible = showWelcomeBackDialog || - showWorkspaceMigrationDialog || shouldShowIdePrompt || shouldShowCommandMigrationNudge || isFolderTrustDialogOpen || @@ -1360,8 +1361,6 @@ export const AppContainer = (props: AppContainerProps) => { historyRemountKey, messageQueue, showAutoAcceptIndicator, - showWorkspaceMigrationDialog, - workspaceExtensions, currentModel, contextFileNames, errorCount, @@ -1451,8 +1450,6 @@ export const AppContainer = (props: AppContainerProps) => { historyRemountKey, messageQueue, showAutoAcceptIndicator, - showWorkspaceMigrationDialog, - workspaceExtensions, contextFileNames, errorCount, availableTerminalHeight, @@ -1513,8 +1510,6 @@ export const AppContainer = (props: AppContainerProps) => { refreshStatic, handleFinalSubmit, handleClearScreen, - onWorkspaceMigrationDialogOpen, - onWorkspaceMigrationDialogClose, // Vision switch dialog handleVisionSwitchSelect, // Welcome back dialog @@ -1551,8 +1546,6 @@ export const AppContainer = (props: AppContainerProps) => { refreshStatic, handleFinalSubmit, handleClearScreen, - onWorkspaceMigrationDialogOpen, - onWorkspaceMigrationDialogClose, handleVisionSwitchSelect, handleWelcomeBackSelection, handleWelcomeBackClose, diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index b02dcf9edcd..b15c6d82dd3 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -4,13 +4,6 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { requestConsentInteractive } from '../../config/extension.js'; -import { - updateAllUpdatableExtensions, - type ExtensionUpdateInfo, - updateExtension, - checkForAllExtensionUpdates, -} from '../../config/extensions/update.js'; import { getErrorMessage } from '../../utils/errors.js'; import { ExtensionUpdateState } from '../state/extensions.js'; import { MessageType } from '../types.js'; @@ -20,8 +13,34 @@ import { CommandKind, } from './types.js'; import { t } from '../../i18n/index.js'; +import type { ExtensionUpdateInfo } from '@qwen-code/qwen-code-core'; + +function showMessageIfNoExtensions( + context: CommandContext, + extensions: unknown[], +): boolean { + if (extensions.length === 0) { + context.ui.addItem( + { + type: MessageType.INFO, + text: 'No extensions installed. Run `/extensions explore` to check out the gallery.', + }, + Date.now(), + ); + return true; + } + return false; +} async function listAction(context: CommandContext) { + const extensions = context.services.config + ? context.services.config.getExtensions() + : []; + + if (showMessageIfNoExtensions(context, extensions)) { + return; + } + context.ui.addItem( { type: MessageType.EXTENSIONS_LIST, @@ -34,7 +53,6 @@ async function updateAction(context: CommandContext, args: string) { const updateArgs = args.split(' ').filter((value) => value.length > 0); const all = updateArgs.length === 1 && updateArgs[0] === '--all'; const names = all ? undefined : updateArgs; - let updateInfos: ExtensionUpdateInfo[] = []; if (!all && names?.length === 0) { context.ui.addItem( @@ -47,29 +65,40 @@ async function updateAction(context: CommandContext, args: string) { return; } + let updateInfos: ExtensionUpdateInfo[] = []; + + const extensionManager = context.services.config!.getExtensionManager(); + const extensions = context.services.config + ? context.services.config.getExtensions() + : []; + + if (showMessageIfNoExtensions(context, extensions)) { + return Promise.resolve(); + } + try { - await checkForAllExtensionUpdates( - context.services.config!.getExtensions(), - context.ui.dispatchExtensionStateUpdate, + context.ui.dispatchExtensionStateUpdate({ type: 'BATCH_CHECK_START' }); + await extensionManager.checkForAllExtensionUpdates((extensionName, state) => + context.ui.dispatchExtensionStateUpdate({ + type: 'SET_STATE', + payload: { name: extensionName, state }, + }), ); + context.ui.dispatchExtensionStateUpdate({ type: 'BATCH_CHECK_END' }); + context.ui.setPendingItem({ type: MessageType.EXTENSIONS_LIST, }); if (all) { - updateInfos = await updateAllUpdatableExtensions( - context.services.config!.getWorkingDir(), - // We don't have the ability to prompt for consent yet in this flow. - (description) => - requestConsentInteractive( - description, - context.ui.addConfirmUpdateExtensionRequest, - ), - context.services.config!.getExtensions(), + updateInfos = await extensionManager.updateAllUpdatableExtensions( context.ui.extensionsUpdateState, - context.ui.dispatchExtensionStateUpdate, + (extensionName, state) => + context.ui.dispatchExtensionStateUpdate({ + type: 'SET_STATE', + payload: { name: extensionName, state }, + }), ); } else if (names?.length) { - const workingDir = context.services.config!.getWorkingDir(); const extensions = context.services.config!.getExtensions(); for (const name of names) { const extension = extensions.find( @@ -85,17 +114,15 @@ async function updateAction(context: CommandContext, args: string) { ); continue; } - const updateInfo = await updateExtension( + const updateInfo = await extensionManager.updateExtension( extension, - workingDir, - (description) => - requestConsentInteractive( - description, - context.ui.addConfirmUpdateExtensionRequest, - ), context.ui.extensionsUpdateState.get(extension.name)?.status ?? ExtensionUpdateState.UNKNOWN, - context.ui.dispatchExtensionStateUpdate, + (extensionName, state) => + context.ui.dispatchExtensionStateUpdate({ + type: 'SET_STATE', + payload: { name: extensionName, state }, + }), ); if (updateInfo) updateInfos.push(updateInfo); } diff --git a/packages/cli/src/ui/components/views/ExtensionsList.tsx b/packages/cli/src/ui/components/views/ExtensionsList.tsx index 742bee13046..50b87d8c45e 100644 --- a/packages/cli/src/ui/components/views/ExtensionsList.tsx +++ b/packages/cli/src/ui/components/views/ExtensionsList.tsx @@ -9,12 +9,10 @@ import { useUIState } from '../../contexts/UIStateContext.js'; import { ExtensionUpdateState } from '../../state/extensions.js'; export const ExtensionsList = () => { - const { commandContext, extensionsUpdateState } = useUIState(); - const allExtensions = commandContext.services.config!.getExtensions(); - const settings = commandContext.services.settings; - const disabledExtensions = settings.merged.extensions?.disabled ?? []; + const { extensionsUpdateState, commandContext } = useUIState(); + const extensions = commandContext.services.config?.getExtensions() || []; - if (allExtensions.length === 0) { + if (extensions.length === 0) { return No extensions installed.; } @@ -22,10 +20,11 @@ export const ExtensionsList = () => { Installed extensions: - {allExtensions.map((ext) => { + {extensions.map((ext) => { const state = extensionsUpdateState.get(ext.name); - const isActive = !disabledExtensions.includes(ext.name); + const isActive = ext.isActive; const activeString = isActive ? 'active' : 'disabled'; + const activeColor = isActive ? 'green' : 'grey'; let stateColor = 'gray'; const stateText = state || 'unknown state'; @@ -44,6 +43,7 @@ export const ExtensionsList = () => { break; case ExtensionUpdateState.UP_TO_DATE: case ExtensionUpdateState.NOT_UPDATABLE: + case ExtensionUpdateState.UPDATED: stateColor = 'green'; break; default: @@ -52,12 +52,22 @@ export const ExtensionsList = () => { } return ( - + {`${ext.name} (v${ext.version})`} - {` - ${activeString}`} + {` - ${activeString}`} {{` (${stateText})`}} + {ext.resolvedSettings && ext.resolvedSettings.length > 0 && ( + + settings: + {ext.resolvedSettings.map((setting) => ( + + - {setting.name}: {setting.value} + + ))} + + )} ); })} diff --git a/packages/cli/src/ui/contexts/UIActionsContext.tsx b/packages/cli/src/ui/contexts/UIActionsContext.tsx index 78243da30db..92f32b67bd4 100644 --- a/packages/cli/src/ui/contexts/UIActionsContext.tsx +++ b/packages/cli/src/ui/contexts/UIActionsContext.tsx @@ -55,8 +55,6 @@ export interface UIActions { refreshStatic: () => void; handleFinalSubmit: (value: string) => void; handleClearScreen: () => void; - onWorkspaceMigrationDialogOpen: () => void; - onWorkspaceMigrationDialogClose: () => void; // Vision switch dialog handleVisionSwitchSelect: (outcome: VisionSwitchOutcome) => void; // Welcome back dialog diff --git a/packages/cli/src/ui/contexts/UIStateContext.tsx b/packages/cli/src/ui/contexts/UIStateContext.tsx index d795a6089c7..99470223b61 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -89,9 +89,6 @@ export interface UIState { historyRemountKey: number; messageQueue: string[]; showAutoAcceptIndicator: ApprovalMode; - showWorkspaceMigrationDialog: boolean; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - workspaceExtensions: any[]; // Extension[] // Quota-related state currentModel: string; contextFileNames: string[]; diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts index 80640fa0db7..3f21c019c5d 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts @@ -11,14 +11,14 @@ import * as path from 'node:path'; import { annotateActiveExtensions, loadExtension, + ExtensionManager, } from '../../config/extension.js'; -import { ExtensionStorage } from '../../config/extensions/storage.js'; import { createExtension } from '../../test-utils/createExtension.js'; import { useExtensionUpdates } from './useExtensionUpdates.js'; import { QWEN_DIR, type GeminiCLIExtension } from '@qwen-code/qwen-code-core'; import { renderHook, waitFor } from '@testing-library/react'; import { MessageType } from '../types.js'; -import { ExtensionEnablementManager } from '../../config/extensions/extensionEnablement.js'; + import { checkForAllExtensionUpdates, updateExtension, @@ -116,7 +116,7 @@ describe('useExtensionUpdates', () => { const extension = annotateActiveExtensions( [loadExtension({ extensionDir, workspaceDir: tempHomeDir })!], tempHomeDir, - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), + new ExtensionManager(), )[0]; const addItem = vi.fn(); @@ -189,7 +189,7 @@ describe('useExtensionUpdates', () => { })!, ], tempHomeDir, - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), + new ExtensionManager(), ); const addItem = vi.fn(); diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.ts index 8d7ec625d73..4d409e100af 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; +import type { ExtensionManager } from '@qwen-code/qwen-code-core'; import { getErrorMessage } from '../../utils/errors.js'; import { ExtensionUpdateState, @@ -14,11 +14,6 @@ import { import { useCallback, useEffect, useMemo, useReducer } from 'react'; import type { UseHistoryManagerReturn } from './useHistoryManager.js'; import { MessageType, type ConfirmationRequest } from '../types.js'; -import { - checkForAllExtensionUpdates, - updateExtension, -} from '../../config/extensions/update.js'; -import { requestConsentInteractive } from '../../config/extension.js'; import { checkExhaustive } from '../../utils/checks.js'; type ConfirmationRequestWrapper = { @@ -45,15 +40,7 @@ function confirmationRequestsReducer( } } -export const useExtensionUpdates = ( - extensions: GeminiCLIExtension[], - addItem: UseHistoryManagerReturn['addItem'], - cwd: string, -) => { - const [extensionsUpdateState, dispatchExtensionStateUpdate] = useReducer( - extensionUpdatesReducer, - initialExtensionUpdatesState, - ); +export const useConfirmUpdateRequests = () => { const [ confirmUpdateExtensionRequests, dispatchConfirmUpdateExtensionRequests, @@ -78,15 +65,52 @@ export const useExtensionUpdates = ( }, [dispatchConfirmUpdateExtensionRequests], ); + return { + addConfirmUpdateExtensionRequest, + confirmUpdateExtensionRequests, + dispatchConfirmUpdateExtensionRequests, + }; +}; + +export const useExtensionUpdates = ( + extensionManager: ExtensionManager, + addItem: UseHistoryManagerReturn['addItem'], + cwd: string, +) => { + const [extensionsUpdateState, dispatchExtensionStateUpdate] = useReducer( + extensionUpdatesReducer, + initialExtensionUpdatesState, + ); + const extensions = extensionManager.getLoadedExtensions(); useEffect(() => { (async () => { - await checkForAllExtensionUpdates( - extensions, - dispatchExtensionStateUpdate, + const extensionsToCheck = extensions.filter((extension) => { + const currentStatus = extensionsUpdateState.extensionStatuses.get( + extension.name, + ); + if (!currentStatus) return true; + const currentState = currentStatus.status; + return !currentState || currentState === ExtensionUpdateState.UNKNOWN; + }); + if (extensionsToCheck.length === 0) return; + dispatchExtensionStateUpdate({ type: 'BATCH_CHECK_START' }); + await extensionManager.checkForAllExtensionUpdates( + (extensionName: string, state: ExtensionUpdateState) => { + dispatchExtensionStateUpdate({ + type: 'SET_STATE', + payload: { name: extensionName, state }, + }); + }, ); + dispatchExtensionStateUpdate({ type: 'BATCH_CHECK_END' }); })(); - }, [extensions, extensions.length, dispatchExtensionStateUpdate]); + }, [ + extensions, + extensionManager, + extensionsUpdateState.extensionStatuses, + dispatchExtensionStateUpdate, + ]); useEffect(() => { if (extensionsUpdateState.batchChecksInProgress > 0) { @@ -113,17 +137,17 @@ export const useExtensionUpdates = ( }); if (extension.installMetadata?.autoUpdate) { - updateExtension( - extension, - cwd, - (description) => - requestConsentInteractive( - description, - addConfirmUpdateExtensionRequest, - ), - currentState.status, - dispatchExtensionStateUpdate, - ) + extensionManager + .updateExtension( + extension, + currentState.status, + (extensionName, state) => { + dispatchExtensionStateUpdate({ + type: 'SET_STATE', + payload: { name: extensionName, state }, + }); + }, + ) .then((result) => { if (!result) return; addItem( @@ -157,13 +181,7 @@ export const useExtensionUpdates = ( Date.now(), ); } - }, [ - extensions, - extensionsUpdateState, - addConfirmUpdateExtensionRequest, - addItem, - cwd, - ]); + }, [extensions, extensionManager, extensionsUpdateState, addItem, cwd]); const extensionsUpdateStateComputed = useMemo(() => { const result = new Map(); @@ -180,7 +198,5 @@ export const useExtensionUpdates = ( extensionsUpdateState: extensionsUpdateStateComputed, extensionsUpdateStateInternal: extensionsUpdateState.extensionStatuses, dispatchExtensionStateUpdate, - confirmUpdateExtensionRequests, - addConfirmUpdateExtensionRequest, }; }; diff --git a/packages/cli/src/ui/hooks/useWorkspaceMigration.ts b/packages/cli/src/ui/hooks/useWorkspaceMigration.ts deleted file mode 100644 index 8f9a3addaff..00000000000 --- a/packages/cli/src/ui/hooks/useWorkspaceMigration.ts +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import { useState, useEffect } from 'react'; -import { - type Extension, - getWorkspaceExtensions, -} from '../../config/extension.js'; -import { type LoadedSettings, SettingScope } from '../../config/settings.js'; -import process from 'node:process'; - -export function useWorkspaceMigration(settings: LoadedSettings) { - const [showWorkspaceMigrationDialog, setShowWorkspaceMigrationDialog] = - useState(false); - const [workspaceExtensions, setWorkspaceExtensions] = useState( - [], - ); - - useEffect(() => { - // Default to true if not set. - if (!(settings.merged.experimental?.extensionManagement ?? true)) { - return; - } - const cwd = process.cwd(); - const extensions = getWorkspaceExtensions(cwd); - if ( - extensions.length > 0 && - !settings.merged.extensions?.workspacesWithMigrationNudge?.includes(cwd) - ) { - setWorkspaceExtensions(extensions); - setShowWorkspaceMigrationDialog(true); - console.log(settings.merged.extensions); - } - }, [ - settings.merged.extensions, - settings.merged.experimental?.extensionManagement, - ]); - - const onWorkspaceMigrationDialogOpen = () => { - const userSettings = settings.forScope(SettingScope.User); - const extensionSettings = userSettings.settings.extensions || { - disabled: [], - }; - const workspacesWithMigrationNudge = - extensionSettings.workspacesWithMigrationNudge || []; - - const cwd = process.cwd(); - if (!workspacesWithMigrationNudge.includes(cwd)) { - workspacesWithMigrationNudge.push(cwd); - } - - extensionSettings.workspacesWithMigrationNudge = - workspacesWithMigrationNudge; - settings.setValue(SettingScope.User, 'extensions', extensionSettings); - }; - - const onWorkspaceMigrationDialogClose = () => { - setShowWorkspaceMigrationDialog(false); - }; - - return { - showWorkspaceMigrationDialog, - workspaceExtensions, - onWorkspaceMigrationDialogOpen, - onWorkspaceMigrationDialogClose, - }; -} diff --git a/packages/cli/src/ui/state/extensions.ts b/packages/cli/src/ui/state/extensions.ts index a83745b5cb6..88f0cadcdf9 100644 --- a/packages/cli/src/ui/state/extensions.ts +++ b/packages/cli/src/ui/state/extensions.ts @@ -10,6 +10,7 @@ export enum ExtensionUpdateState { CHECKING_FOR_UPDATES = 'checking for updates', UPDATED_NEEDS_RESTART = 'updated, needs restart', UPDATING = 'updating', + UPDATED = 'updated', UPDATE_AVAILABLE = 'update available', UP_TO_DATE = 'up to date', ERROR = 'error', diff --git a/packages/cli/src/utils/envVarResolver.ts b/packages/cli/src/utils/envVarResolver.ts index d6d50d02063..096b5549ec0 100644 --- a/packages/cli/src/utils/envVarResolver.ts +++ b/packages/cli/src/utils/envVarResolver.ts @@ -17,10 +17,16 @@ * resolveEnvVarsInString("URL: ${BASE_URL}/api") // Returns "URL: https://api.example.com/api" * resolveEnvVarsInString("Missing: $UNDEFINED_VAR") // Returns "Missing: $UNDEFINED_VAR" */ -export function resolveEnvVarsInString(value: string): string { +export function resolveEnvVarsInString( + value: string, + customEnv?: Record, +): string { const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g; // Find $VAR_NAME or ${VAR_NAME} return value.replace(envVarRegex, (match, varName1, varName2) => { const varName = varName1 || varName2; + if (customEnv && typeof customEnv[varName] === 'string') { + return customEnv[varName]; + } if (process && process.env && typeof process.env[varName] === 'string') { return process.env[varName]!; } @@ -47,8 +53,11 @@ export function resolveEnvVarsInString(value: string): string { * }; * const resolved = resolveEnvVarsInObject(config); */ -export function resolveEnvVarsInObject(obj: T): T { - return resolveEnvVarsInObjectInternal(obj, new WeakSet()); +export function resolveEnvVarsInObject( + obj: T, + customEnv?: Record, +): T { + return resolveEnvVarsInObjectInternal(obj, new WeakSet(), customEnv); } /** @@ -61,6 +70,7 @@ export function resolveEnvVarsInObject(obj: T): T { function resolveEnvVarsInObjectInternal( obj: T, visited: WeakSet, + customEnv?: Record, ): T { if ( obj === null || @@ -72,7 +82,7 @@ function resolveEnvVarsInObjectInternal( } if (typeof obj === 'string') { - return resolveEnvVarsInString(obj) as unknown as T; + return resolveEnvVarsInString(obj, customEnv) as unknown as T; } if (Array.isArray(obj)) { @@ -84,7 +94,7 @@ function resolveEnvVarsInObjectInternal( visited.add(obj); const result = obj.map((item) => - resolveEnvVarsInObjectInternal(item, visited), + resolveEnvVarsInObjectInternal(item, visited, customEnv), ) as unknown as T; visited.delete(obj); return result; @@ -101,7 +111,11 @@ function resolveEnvVarsInObjectInternal( const newObj = { ...obj } as T; for (const key in newObj) { if (Object.prototype.hasOwnProperty.call(newObj, key)) { - newObj[key] = resolveEnvVarsInObjectInternal(newObj[key], visited); + newObj[key] = resolveEnvVarsInObjectInternal( + newObj[key], + visited, + customEnv, + ); } } visited.delete(obj as object); diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json index 073f2aa1b0b..cd546eeda92 100644 --- a/packages/cli/tsconfig.json +++ b/packages/cli/tsconfig.json @@ -11,7 +11,9 @@ "src/**/*.ts", "src/**/*.tsx", "src/**/*.json", - "./package.json" + "./package.json", + "../core/src/utils/toml-to-markdown-converter.test.ts", + "../core/src/utils/toml-to-markdown-converter.ts" ], "exclude": [ "node_modules", diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 3f5c4c63f2f..45d18b0783f 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -80,6 +80,10 @@ import { type TelemetryTarget, uiTelemetryService, } from '../telemetry/index.js'; +import { + ExtensionManager, + type Extension, +} from '../extension/extensionManager.js'; // Utils import { shouldAttemptBrowserLaunch } from '../utils/browser.js'; @@ -102,6 +106,7 @@ import { type ResumedSessionData, } from '../services/sessionService.js'; import { randomUUID } from 'node:crypto'; +import { loadServerHierarchicalMemory } from '../utils/memoryDiscovery.js'; // Re-export types export type { AnyToolInvocation, FileFilteringOptions, MCPOAuthConfig }; @@ -192,20 +197,17 @@ export interface GitCoAuthorSettings { email?: string; } -export interface GeminiCLIExtension { - name: string; - version: string; - isActive: boolean; - path: string; - installMetadata?: ExtensionInstallMetadata; -} - export interface ExtensionInstallMetadata { source: string; type: 'git' | 'local' | 'link' | 'github-release' | 'marketplace'; releaseTag?: string; // Only present for github-release installs. ref?: string; autoUpdate?: boolean; + allowPreRelease?: boolean; + marketplace?: { + marketplaceSource: string; + pluginName: string; + }; } export const DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD = 25_000; @@ -303,14 +305,15 @@ export interface ConfigParameters { includeDirectories?: string[]; bugCommand?: BugCommandSettings; model?: string; - extensionContextFilePaths?: string[]; + outputLanguageFilePath?: string; maxSessionTurns?: number; sessionTokenLimit?: number; experimentalSkills?: boolean; experimentalZedIntegration?: boolean; listExtensions?: boolean; - extensions?: GeminiCLIExtension[]; - blockedMcpServers?: Array<{ name: string; extensionName: string }>; + overrideExtensions?: string[]; + allowedMcpServers?: string[]; + excludedMcpServers?: string[]; noBrowser?: boolean; summarizeToolOutput?: Record; folderTrustFeature?: boolean; @@ -320,6 +323,8 @@ export interface ConfigParameters { generationConfig?: Partial; cliVersion?: string; loadMemoryFromIncludeDirectories?: boolean; + importFormat?: 'tree' | 'flat'; + discoveryMaxDirs?: number; chatRecording?: boolean; // Web search providers webSearch?: { @@ -338,7 +343,6 @@ export interface ConfigParameters { shouldUseNodePtyShell?: boolean; skipNextSpeakerCheck?: boolean; shellExecutionConfig?: ShellExecutionConfig; - extensionManagement?: boolean; skipLoopDetection?: boolean; vlmSwitchMode?: string; truncateToolOutputThreshold?: number; @@ -391,6 +395,7 @@ export class Config { private toolRegistry!: ToolRegistry; private promptRegistry!: PromptRegistry; private subagentManager!: SubagentManager; + private extensionManager!: ExtensionManager; private skillManager!: SkillManager; private fileSystemService: FileSystemService; private contentGeneratorConfig!: ContentGeneratorConfig; @@ -413,6 +418,8 @@ export class Config { private readonly toolCallCommand: string | undefined; private readonly mcpServerCommand: string | undefined; private mcpServers: Record | undefined; + private readonly allowedMcpServers?: string[]; + private readonly excludedMcpServers?: string[]; private sessionSubagents: SubagentConfig[]; private userMemory: string; private sdkMode: boolean; @@ -435,11 +442,12 @@ export class Config { private gitService: GitService | undefined = undefined; private sessionService: SessionService | undefined = undefined; private chatRecordingService: ChatRecordingService | undefined = undefined; + private extensionContextFilePaths: string[] = []; private readonly checkpointing: boolean; private readonly proxy: string | undefined; private readonly cwd: string; private readonly bugCommand: BugCommandSettings | undefined; - private readonly extensionContextFilePaths: string[]; + private readonly outputLanguageFilePath?: string; private readonly noBrowser: boolean; private readonly folderTrustFeature: boolean; private readonly folderTrust: boolean; @@ -449,11 +457,8 @@ export class Config { private readonly maxSessionTurns: number; private readonly sessionTokenLimit: number; private readonly listExtensions: boolean; - private readonly _extensions: GeminiCLIExtension[]; - private readonly _blockedMcpServers: Array<{ - name: string; - extensionName: string; - }>; + private readonly overrideExtensions?: string[]; + fallbackModelHandler?: FallbackModelHandler; private quotaErrorOccurred: boolean = false; private readonly summarizeToolOutput: @@ -464,6 +469,8 @@ export class Config { private readonly experimentalSkills: boolean = false; private readonly chatRecordingEnabled: boolean; private readonly loadMemoryFromIncludeDirectories: boolean = false; + private readonly importFormat: 'tree' | 'flat'; + private readonly discoveryMaxDirs: number; private readonly webSearch?: { provider: Array<{ type: 'tavily' | 'google' | 'dashscope'; @@ -480,7 +487,6 @@ export class Config { private readonly shouldUseNodePtyShell: boolean; private readonly skipNextSpeakerCheck: boolean; private shellExecutionConfig: ShellExecutionConfig; - private readonly extensionManagement: boolean = true; private readonly skipLoopDetection: boolean; private readonly skipStartupContext: boolean; private readonly vlmSwitchMode: string | undefined; @@ -521,6 +527,8 @@ export class Config { this.toolCallCommand = params.toolCallCommand; this.mcpServerCommand = params.mcpServerCommand; this.mcpServers = params.mcpServers; + this.allowedMcpServers = params.allowedMcpServers; + this.excludedMcpServers = params.excludedMcpServers; this.sessionSubagents = params.sessionSubagents ?? []; this.sdkMode = params.sdkMode ?? false; this.userMemory = params.userMemory ?? ''; @@ -543,6 +551,7 @@ export class Config { email: 'qwen-coder@alibabacloud.com', }; this.usageStatisticsEnabled = params.usageStatisticsEnabled ?? true; + this.outputLanguageFilePath = params.outputLanguageFilePath; this.fileFiltering = { respectGitIgnore: params.fileFiltering?.respectGitIgnore ?? true, @@ -556,15 +565,13 @@ export class Config { this.cwd = params.cwd ?? process.cwd(); this.fileDiscoveryService = params.fileDiscoveryService ?? null; this.bugCommand = params.bugCommand; - this.extensionContextFilePaths = params.extensionContextFilePaths ?? []; this.maxSessionTurns = params.maxSessionTurns ?? -1; this.sessionTokenLimit = params.sessionTokenLimit ?? -1; this.experimentalZedIntegration = params.experimentalZedIntegration ?? false; this.experimentalSkills = params.experimentalSkills ?? false; this.listExtensions = params.listExtensions ?? false; - this._extensions = params.extensions ?? []; - this._blockedMcpServers = params.blockedMcpServers ?? []; + this.overrideExtensions = params.overrideExtensions; this.noBrowser = params.noBrowser ?? false; this.summarizeToolOutput = params.summarizeToolOutput; this.folderTrustFeature = params.folderTrustFeature ?? false; @@ -583,6 +590,8 @@ export class Config { this.loadMemoryFromIncludeDirectories = params.loadMemoryFromIncludeDirectories ?? false; + this.importFormat = params.importFormat ?? 'tree'; + this.discoveryMaxDirs = params.discoveryMaxDirs ?? 200; this.chatCompression = params.chatCompression; this.interactive = params.interactive ?? false; this.trustedFolder = params.trustedFolder; @@ -608,7 +617,6 @@ export class Config { params.truncateToolOutputLines ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES; this.enableToolOutputTruncation = params.enableToolOutputTruncation ?? true; this.useSmartEdit = params.useSmartEdit ?? false; - this.extensionManagement = params.extensionManagement ?? true; this.channel = params.channel; this.storage = new Storage(this.targetDir); this.vlmSwitchMode = params.vlmSwitchMode; @@ -656,6 +664,23 @@ export class Config { this.subagentManager.loadSessionSubagents(this.sessionSubagents); } + this.extensionManager = new ExtensionManager({ + workspaceDir: this.targetDir, + enabledExtensionOverrides: this.overrideExtensions, + config: this, + isWorkspaceTrusted: this.isTrustedFolder(), + }); + + await this.extensionManager.refreshCache(); + const activeExtensions = await this.extensionManager + .getLoadedExtensions() + .filter((e) => e.isActive); + this.extensionContextFilePaths = activeExtensions.flatMap( + (e) => e.contextFiles, + ); + + await this.refreshHierarchicalMemory(); + this.toolRegistry = await this.createToolRegistry( options?.sendSdkMcpMessage, ); @@ -665,6 +690,24 @@ export class Config { logStartSession(this, new StartSessionEvent(this)); } + async refreshHierarchicalMemory(): Promise { + const { memoryContent, fileCount } = await loadServerHierarchicalMemory( + this.getWorkingDir(), + this.shouldLoadMemoryFromIncludeDirectories() + ? this.getWorkspaceContext().getDirectories() + : [], + this.getDebugMode(), + this.getFileService(), + this.getExtensionContextFilePaths(), + this.getFolderTrust(), + this.getImportFormat(), + this.getFileFilteringOptions(), + this.getDiscoveryMaxDirs(), + ); + this.setUserMemory(memoryContent); + this.setGeminiMdFileCount(fileCount); + } + getContentGenerator(): ContentGenerator { return this.contentGenerator; } @@ -763,6 +806,14 @@ export class Config { return this.loadMemoryFromIncludeDirectories; } + getImportFormat(): 'tree' | 'flat' { + return this.importFormat; + } + + getDiscoveryMaxDirs(): number { + return this.discoveryMaxDirs; + } + getContentGeneratorConfig(): ContentGeneratorConfig { return this.contentGeneratorConfig; } @@ -870,7 +921,14 @@ export class Config { } getExcludeTools(): string[] | undefined { - return this.excludeTools; + const allExcludeTools = new Set(this.excludeTools || []); + const extensions = this.getActiveExtensions(); + for (const extension of extensions) { + for (const tool of extension.config.excludeTools || []) { + allExcludeTools.add(tool); + } + } + return [...allExcludeTools]; } getToolDiscoveryCommand(): string | undefined { @@ -886,7 +944,37 @@ export class Config { } getMcpServers(): Record | undefined { - return this.mcpServers; + let mcpServers = { ...(this.mcpServers || {}) }; + const extensions = this.getActiveExtensions(); + for (const extension of extensions) { + Object.entries(extension.config.mcpServers || {}).forEach( + ([key, server]) => { + if (mcpServers[key]) return; + mcpServers[key] = { + ...server, + extensionName: extension.config.name, + }; + }, + ); + } + + if (this.allowedMcpServers) { + mcpServers = Object.fromEntries( + Object.entries(mcpServers).filter(([key]) => + this.allowedMcpServers?.includes(key), + ), + ); + } + + if (this.excludedMcpServers) { + mcpServers = Object.fromEntries( + Object.entries(mcpServers).filter( + ([key]) => !this.excludedMcpServers?.includes(key), + ), + ); + } + + return mcpServers; } addMcpServers(servers: Record): void { @@ -1065,7 +1153,10 @@ export class Config { } getExtensionContextFilePaths(): string[] { - return this.extensionContextFilePaths; + return [ + ...this.extensionContextFilePaths, + ...(this.outputLanguageFilePath ? [this.outputLanguageFilePath] : []), + ]; } getExperimentalZedIntegration(): boolean { @@ -1080,16 +1171,54 @@ export class Config { return this.listExtensions; } - getExtensionManagement(): boolean { - return this.extensionManagement; + getExtensionManager(): ExtensionManager { + return this.extensionManager; } - getExtensions(): GeminiCLIExtension[] { - return this._extensions; + getExtensions(): Extension[] { + const extensions = this.extensionManager.getLoadedExtensions(); + if (this.overrideExtensions) { + return extensions.filter((e) => + this.overrideExtensions?.includes(e.name), + ); + } else { + return extensions; + } + } + + getActiveExtensions(): Extension[] { + return this.getExtensions().filter((e) => e.isActive); } getBlockedMcpServers(): Array<{ name: string; extensionName: string }> { - return this._blockedMcpServers; + const mcpServers = { ...(this.mcpServers || {}) }; + const extensions = this.getActiveExtensions(); + for (const extension of extensions) { + Object.entries(extension.config.mcpServers || {}).forEach( + ([key, server]) => { + if (mcpServers[key]) return; + mcpServers[key] = { + ...server, + extensionName: extension.config.name, + }; + }, + ); + } + const blockedMcpServers: Array<{ name: string; extensionName: string }> = + []; + + if (this.allowedMcpServers) { + Object.entries(mcpServers).forEach(([key, server]) => { + const isAllowed = this.allowedMcpServers?.includes(key); + if (!isAllowed) { + blockedMcpServers.push({ + name: key, + extensionName: server.extensionName || '', + }); + } + }); + } + return blockedMcpServers; } getNoBrowser(): boolean { diff --git a/packages/cli/src/config/extensions/claude-converter.test.ts b/packages/core/src/extension/claude-converter.test.ts similarity index 79% rename from packages/cli/src/config/extensions/claude-converter.test.ts rename to packages/core/src/extension/claude-converter.test.ts index 4502158c672..9e74b07bf08 100644 --- a/packages/cli/src/config/extensions/claude-converter.test.ts +++ b/packages/core/src/extension/claude-converter.test.ts @@ -26,7 +26,7 @@ describe('convertClaudeToQwenConfig', () => { expect(result.version).toBe('1.0.0'); }); - it('should convert config with commands and agents', () => { + it('should convert config with basic fields only', () => { const claudeConfig: ClaudePluginConfig = { name: 'full-plugin', version: '1.0.0', @@ -37,9 +37,10 @@ describe('convertClaudeToQwenConfig', () => { const result = convertClaudeToQwenConfig(claudeConfig); - expect(result.commands).toBe('commands'); - expect(result.agents).toEqual(['agents/agent1.md']); - expect(result.skills).toEqual(['skills/skill1']); + // Commands, skills, agents are collected as directories, not in config + expect(result.name).toBe('full-plugin'); + expect(result.version).toBe('1.0.0'); + expect(result.mcpServers).toBeUndefined(); }); it('should throw error for missing name', () => { @@ -104,18 +105,17 @@ describe('mergeClaudeConfigs', () => { }); describe('isClaudePluginConfig', () => { - it('should identify Claude config with agent field', () => { - const config = { - name: 'test', - version: '1.0.0', - agents: ['agent.md'], + it('should identify Claude plugin directory', () => { + const extensionDir = '/tmp/test-extension'; + const marketplace = { + marketplaceSource: 'https://test.com', + pluginName: 'test-plugin', }; - expect(isClaudePluginConfig(config)).toBe(true); - }); - - it('should return false for invalid config', () => { - expect(isClaudePluginConfig(null)).toBe(false); - expect(isClaudePluginConfig({})).toBe(false); + // This will check if marketplace.json exists and contains the plugin + // Note: In real usage, this requires actual file system setup + expect(typeof isClaudePluginConfig(extensionDir, marketplace)).toBe( + 'boolean', + ); }); }); diff --git a/packages/core/src/extension/claude-converter.ts b/packages/core/src/extension/claude-converter.ts new file mode 100644 index 00000000000..9e6cead541b --- /dev/null +++ b/packages/core/src/extension/claude-converter.ts @@ -0,0 +1,500 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Converter for Claude Code plugins to Qwen Code format. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { glob } from 'glob'; +import type { ExtensionConfig } from './extensionManager.js'; +import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; +import { ExtensionStorage } from './storage.js'; + +export interface ClaudePluginConfig { + name: string; + version: string; + description?: string; + author?: { name?: string; email?: string; url?: string }; + homepage?: string; + repository?: string; + license?: string; + keywords?: string[]; + commands?: string | string[]; + agents?: string | string[]; + skills?: string | string[]; + hooks?: string; + mcpServers?: string | Record; + outputStyles?: string | string[]; + lspServers?: string; +} + +export type ClaudePluginSource = + | { source: 'github'; repo: string } + | { source: 'url'; url: string }; + +export interface ClaudeMarketplacePluginConfig extends ClaudePluginConfig { + source: string | ClaudePluginSource; + category?: string; + strict?: boolean; + tags?: string[]; +} + +export interface ClaudeMarketplaceConfig { + name: string; + owner: { name: string; email: string }; + plugins: ClaudeMarketplacePluginConfig[]; + metadata?: { description?: string; version?: string; pluginRoot?: string }; +} + +/** + * Converts a Claude plugin config to Qwen Code format. + * @param claudeConfig Claude plugin configuration + * @returns Qwen ExtensionConfig + */ +export function convertClaudeToQwenConfig( + claudeConfig: ClaudePluginConfig, +): ExtensionConfig { + // Validate required fields + if (!claudeConfig.name || !claudeConfig.version) { + throw new Error('Claude plugin config must have name and version fields'); + } + + // Parse MCP servers + let mcpServers: Record | undefined; + if (claudeConfig.mcpServers) { + if (typeof claudeConfig.mcpServers === 'string') { + // TODO: Load from file path + console.warn( + `[Claude Converter] MCP servers path not yet supported: ${claudeConfig.mcpServers}`, + ); + } else { + mcpServers = claudeConfig.mcpServers; + } + } + + // Warn about unsupported fields + if (claudeConfig.hooks) { + console.warn( + `[Claude Converter] Hooks are not yet supported in ${claudeConfig.name}`, + ); + } + if (claudeConfig.outputStyles) { + console.warn( + `[Claude Converter] Output styles are not yet supported in ${claudeConfig.name}`, + ); + } + if (claudeConfig.lspServers) { + console.warn( + `[Claude Converter] LSP servers are not yet supported in ${claudeConfig.name}`, + ); + } + + // Direct field mapping - commands, skills, agents will be collected as folders + return { + name: claudeConfig.name, + version: claudeConfig.version, + mcpServers, + }; +} + +/** + * Converts a complete Claude plugin package to Qwen Code format. + * Creates a new temporary directory with: + * 1. Converted qwen-extension.json + * 2. Commands, skills, and agents collected to respective folders + * 3. MCP servers resolved from JSON files if needed + * 4. All other files preserved + * + * @param extensionDir Path to the Claude plugin directory + * @param marketplace Marketplace information for loading marketplace.json + * @returns Object containing converted config and the temporary directory path + */ +export async function convertClaudePluginPackage( + extensionDir: string, + marketplace: { marketplaceSource: string; pluginName: string }, +): Promise<{ config: ExtensionConfig; convertedDir: string }> { + // Step 1: Load marketplace.json + const marketplaceJsonPath = path.join( + extensionDir, + '.claude-plugin', + 'marketplace.json', + ); + if (!fs.existsSync(marketplaceJsonPath)) { + throw new Error( + `Marketplace configuration not found at ${marketplaceJsonPath}`, + ); + } + + const marketplaceContent = fs.readFileSync(marketplaceJsonPath, 'utf-8'); + const marketplaceConfig: ClaudeMarketplaceConfig = + JSON.parse(marketplaceContent); + + // Find the target plugin in marketplace + const marketplacePlugin = marketplaceConfig.plugins.find( + (p) => p.name === marketplace.pluginName, + ); + if (!marketplacePlugin) { + throw new Error( + `Plugin ${marketplace.pluginName} not found in marketplace.json`, + ); + } + + // Step 2: Resolve plugin source directory based on source field + const source = marketplacePlugin.source; + let pluginSourceDir: string; + + if (typeof source === 'string') { + // Check if it's a URL (online path) + if (source.startsWith('http://') || source.startsWith('https://')) { + throw new Error( + `Online plugin sources are not supported in convertClaudePluginPackage. ` + + `Plugin ${marketplace.pluginName} has source: ${source}. ` + + `This should be downloaded and resolved before calling this function.`, + ); + } + // Relative path within marketplace directory + const marketplaceDir = marketplaceConfig.metadata?.pluginRoot + ? path.join(extensionDir, marketplaceConfig.metadata.pluginRoot) + : extensionDir; + pluginSourceDir = path.join(marketplaceDir, source); + } else if (source.source === 'github' || source.source === 'url') { + throw new Error( + `Online plugin sources (github/url) are not supported in convertClaudePluginPackage. ` + + `Plugin ${marketplace.pluginName} has source type: ${source.source}. ` + + `This should be downloaded and resolved before calling this function.`, + ); + } else { + throw new Error( + `Unsupported plugin source type for ${marketplace.pluginName}: ${JSON.stringify(source)}`, + ); + } + + if (!fs.existsSync(pluginSourceDir)) { + throw new Error(`Plugin source directory not found: ${pluginSourceDir}`); + } + + // Step 3: Load and merge plugin.json if exists (based on strict mode) + const strict = marketplacePlugin.strict ?? true; + let mergedConfig: ClaudePluginConfig; + + if (strict) { + const pluginJsonPath = path.join( + pluginSourceDir, + '.claude-plugin', + 'plugin.json', + ); + if (!fs.existsSync(pluginJsonPath)) { + throw new Error(`Strict mode requires plugin.json at ${pluginJsonPath}`); + } + const pluginContent = fs.readFileSync(pluginJsonPath, 'utf-8'); + const pluginConfig: ClaudePluginConfig = JSON.parse(pluginContent); + mergedConfig = mergeClaudeConfigs(marketplacePlugin, pluginConfig); + } else { + mergedConfig = marketplacePlugin as ClaudePluginConfig; + } + + // Step 4: Resolve MCP servers from JSON files if needed + if (mergedConfig.mcpServers && typeof mergedConfig.mcpServers === 'string') { + const mcpServersPath = path.isAbsolute(mergedConfig.mcpServers) + ? mergedConfig.mcpServers + : path.join(pluginSourceDir, mergedConfig.mcpServers); + + if (fs.existsSync(mcpServersPath)) { + try { + const mcpContent = fs.readFileSync(mcpServersPath, 'utf-8'); + mergedConfig.mcpServers = JSON.parse(mcpContent) as Record< + string, + MCPServerConfig + >; + } catch (error) { + console.warn( + `Failed to parse MCP servers file ${mcpServersPath}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + } + + // Step 5: Create temporary directory for converted extension + const tmpDir = await ExtensionStorage.createTmpDir(); + + try { + // Step 6: Copy plugin files to temporary directory + await copyDirectory(pluginSourceDir, tmpDir); + + // Step 7: Collect commands to commands folder + if (mergedConfig.commands) { + const commandsDestDir = path.join(tmpDir, 'commands'); + await collectResources( + mergedConfig.commands, + pluginSourceDir, + commandsDestDir, + ); + } + + // Step 8: Collect skills to skills folder + if (mergedConfig.skills) { + const skillsDestDir = path.join(tmpDir, 'skills'); + await collectResources( + mergedConfig.skills, + pluginSourceDir, + skillsDestDir, + ); + } + + // Step 9: Collect agents to agents folder + if (mergedConfig.agents) { + const agentsDestDir = path.join(tmpDir, 'agents'); + await collectResources( + mergedConfig.agents, + pluginSourceDir, + agentsDestDir, + ); + } + + // Step 10: Convert to Qwen format config + const qwenConfig = convertClaudeToQwenConfig(mergedConfig); + + // Step 11: Write qwen-extension.json + const qwenConfigPath = path.join(tmpDir, 'qwen-extension.json'); + fs.writeFileSync( + qwenConfigPath, + JSON.stringify(qwenConfig, null, 2), + 'utf-8', + ); + + return { + config: qwenConfig, + convertedDir: tmpDir, + }; + } catch (error) { + // Clean up temporary directory on error + try { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } catch { + // Ignore cleanup errors + } + throw error; + } +} + +/** + * Recursively copies a directory and its contents. + * @param source Source directory path + * @param destination Destination directory path + */ +async function copyDirectory( + source: string, + destination: string, +): Promise { + // Create destination directory if it doesn't exist + if (!fs.existsSync(destination)) { + fs.mkdirSync(destination, { recursive: true }); + } + + const entries = fs.readdirSync(source, { withFileTypes: true }); + + for (const entry of entries) { + const sourcePath = path.join(source, entry.name); + const destPath = path.join(destination, entry.name); + + if (entry.isDirectory()) { + await copyDirectory(sourcePath, destPath); + } else { + fs.copyFileSync(sourcePath, destPath); + } + } +} + +/** + * Collects resources (commands, skills, agents) to a destination folder. + * If a resource is already in the destination folder, it will be skipped. + * @param resourcePaths String or array of resource paths + * @param pluginRoot Root directory of the plugin + * @param destDir Destination directory for collected resources + */ +async function collectResources( + resourcePaths: string | string[], + pluginRoot: string, + destDir: string, +): Promise { + const paths = Array.isArray(resourcePaths) ? resourcePaths : [resourcePaths]; + + // Create destination directory + if (!fs.existsSync(destDir)) { + fs.mkdirSync(destDir, { recursive: true }); + } + + // Get the destination folder name (e.g., 'commands', 'skills', 'agents') + const destFolderName = path.basename(destDir); + + for (const resourcePath of paths) { + const resolvedPath = path.isAbsolute(resourcePath) + ? resourcePath + : path.join(pluginRoot, resourcePath); + + if (!fs.existsSync(resolvedPath)) { + console.warn(`Resource path not found: ${resolvedPath}`); + continue; + } + + const stat = fs.statSync(resolvedPath); + + if (stat.isDirectory()) { + // If it's a directory, check if it's already the destination folder + const dirName = path.basename(resolvedPath); + const parentDir = path.dirname(resolvedPath); + + // If the directory is already named as the destination folder (e.g., 'commands') + // and it's at the plugin root level, skip it + if (dirName === destFolderName && parentDir === pluginRoot) { + console.log( + `Skipping ${resolvedPath} as it's already in the correct location`, + ); + continue; + } + + // Copy all files from the directory + const files = await glob('**/*', { + cwd: resolvedPath, + nodir: true, + dot: false, + }); + + for (const file of files) { + const srcFile = path.join(resolvedPath, file); + const destFile = path.join(destDir, file); + + // Ensure parent directory exists + const destFileDir = path.dirname(destFile); + if (!fs.existsSync(destFileDir)) { + fs.mkdirSync(destFileDir, { recursive: true }); + } + + fs.copyFileSync(srcFile, destFile); + } + } else { + // If it's a file, check if it's already in the destination folder + const relativePath = path.relative(pluginRoot, resolvedPath); + + // Check if the file path starts with the destination folder name + // e.g., 'commands/test1.md' or 'commands/me/test.md' should be skipped + const segments = relativePath.split(path.sep); + if (segments.length > 0 && segments[0] === destFolderName) { + console.log( + `Skipping ${resolvedPath} as it's already in ${destFolderName}/`, + ); + continue; + } + + // Copy the file to destination + const fileName = path.basename(resolvedPath); + const destFile = path.join(destDir, fileName); + fs.copyFileSync(resolvedPath, destFile); + } + } +} + +/** + * Merges marketplace plugin config with the actual plugin.json config. + * Marketplace config takes precedence for conflicting fields. + * @param marketplacePlugin Marketplace plugin definition + * @param pluginConfig Actual plugin.json config (optional if strict=false) + * @returns Merged Claude plugin config + */ +export function mergeClaudeConfigs( + marketplacePlugin: ClaudeMarketplacePluginConfig, + pluginConfig?: ClaudePluginConfig, +): ClaudePluginConfig { + if (!pluginConfig && marketplacePlugin.strict !== false) { + throw new Error( + `Plugin ${marketplacePlugin.name} requires plugin.json (strict mode)`, + ); + } + + // Start with plugin.json config (if exists) + const merged: ClaudePluginConfig = pluginConfig + ? { ...pluginConfig } + : { + name: marketplacePlugin.name, + version: '1.0.0', // Default version if not in marketplace + }; + + // Overlay marketplace config (takes precedence) + if (marketplacePlugin.name) merged.name = marketplacePlugin.name; + if (marketplacePlugin.version) merged.version = marketplacePlugin.version; + if (marketplacePlugin.description) + merged.description = marketplacePlugin.description; + if (marketplacePlugin.author) merged.author = marketplacePlugin.author; + if (marketplacePlugin.homepage) merged.homepage = marketplacePlugin.homepage; + if (marketplacePlugin.repository) + merged.repository = marketplacePlugin.repository; + if (marketplacePlugin.license) merged.license = marketplacePlugin.license; + if (marketplacePlugin.keywords) merged.keywords = marketplacePlugin.keywords; + if (marketplacePlugin.commands) merged.commands = marketplacePlugin.commands; + if (marketplacePlugin.agents) merged.agents = marketplacePlugin.agents; + if (marketplacePlugin.skills) merged.skills = marketplacePlugin.skills; + if (marketplacePlugin.hooks) merged.hooks = marketplacePlugin.hooks; + if (marketplacePlugin.mcpServers) + merged.mcpServers = marketplacePlugin.mcpServers; + if (marketplacePlugin.outputStyles) + merged.outputStyles = marketplacePlugin.outputStyles; + if (marketplacePlugin.lspServers) + merged.lspServers = marketplacePlugin.lspServers; + + return merged; +} + +/** + * Checks if a config object is in Claude plugin format. + * @param config Configuration object to check + * @returns true if config appears to be Claude format + */ +export function isClaudePluginConfig( + extensionDir: string, + marketplace: { marketplaceSource: string; pluginName: string }, +) { + const marketplaceConfigFilePath = path.join( + extensionDir, + '.claude-plugin/marketplace.json', + ); + if (!fs.existsSync(marketplaceConfigFilePath)) { + return false; + } + + const marketplaceConfigContent = fs.readFileSync( + marketplaceConfigFilePath, + 'utf-8', + ); + const marketplaceConfig = JSON.parse(marketplaceConfigContent); + + if (typeof marketplaceConfig !== 'object' || marketplaceConfig === null) { + return false; + } + + const marketplaceConfigObj = marketplaceConfig as Record; + + // Must have name and owner + if ( + typeof marketplaceConfigObj['name'] !== 'string' || + typeof marketplaceConfigObj['owner'] !== 'object' + ) { + return false; + } + + if (!Array.isArray(marketplaceConfigObj['plugins'])) { + return false; + } + + const marketplacePluginObj = marketplaceConfigObj['plugins'].find( + (plugin: ClaudeMarketplacePluginConfig) => + plugin.name === marketplace.pluginName, + ); + + if (!marketplacePluginObj) return false; + + return true; +} diff --git a/packages/cli/src/config/extension.test.ts b/packages/core/src/extension/extensionManager.test.ts similarity index 100% rename from packages/cli/src/config/extension.test.ts rename to packages/core/src/extension/extensionManager.test.ts diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts new file mode 100644 index 00000000000..5b2922e5bdc --- /dev/null +++ b/packages/core/src/extension/extensionManager.ts @@ -0,0 +1,1338 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { + MCPServerConfig, + ExtensionInstallMetadata, + SkillConfig, + SubagentConfig, +} from '../index.js'; +import { + Storage, + Config, + logExtensionEnable, + logExtensionInstallEvent, + logExtensionUninstall, + logExtensionDisable, +} from '../index.js'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { getErrorMessage } from '../utils/errors.js'; +import { + EXTENSIONS_CONFIG_FILENAME, + INSTALL_METADATA_FILENAME, + recursivelyHydrateStrings, +} from './variables.js'; +import { resolveEnvVarsInObject } from '../utils/envVarResolver.js'; +import { + checkForExtensionUpdate, + cloneFromGit, + downloadFromGitHubRelease, + parseGitHubRepoForReleases, +} from './github.js'; +import type { LoadExtensionContext } from './variableSchema.js'; +import { Override, type AllExtensionsEnablementConfig } from './override.js'; +import chalk from 'chalk'; +import { + installFromMarketplace, + parseMarketplaceSource, +} from './marketplace.js'; +import { + isGeminiExtensionConfig, + convertGeminiExtensionPackage, +} from './gemini-converter.js'; +import { glob } from 'glob'; +import { createHash } from 'node:crypto'; +import { ExtensionStorage } from './storage.js'; +import { + getEnvContents, + maybePromptForSettings, + promptForSetting, +} from './extensionSettings.js'; +import type { TelemetrySettings } from '../config/config.js'; +import { logExtensionUpdateEvent } from '../telemetry/loggers.js'; +import { + ExtensionDisableEvent, + ExtensionEnableEvent, + ExtensionInstallEvent, + ExtensionUninstallEvent, + ExtensionUpdateEvent, +} from '../telemetry/types.js'; +import { stat } from 'node:fs/promises'; + +// ============================================================================ +// Types and Interfaces +// ============================================================================ + +export enum SettingScope { + User = 'User', + Workspace = 'Workspace', + System = 'System', + SystemDefaults = 'SystemDefaults', +} + +export interface Extension { + id: string; + name: string; + version: string; + isActive: boolean; + path: string; + config: ExtensionConfig; + + installMetadata?: ExtensionInstallMetadata; + mcpServers?: Record; + contextFiles: string[]; + excludeTools?: string[]; + settings?: ExtensionSetting[]; + resolvedSettings?: ResolvedExtensionSetting[]; + skills?: SkillConfig[]; + agents?: SubagentConfig[]; +} + +export interface ExtensionConfig { + name: string; + version: string; + mcpServers?: Record; + contextFileName?: string | string[]; + excludeTools?: string[]; + commands?: string | string[]; + skills?: string | string[]; + agents?: string | string[]; + settings?: ExtensionSetting[]; +} + +export interface ExtensionSetting { + name: string; + description: string; + envVar: string; + sensitive?: boolean; +} + +export interface ResolvedExtensionSetting { + name: string; + envVar: string; + value: string; + sensitive: boolean; +} + +export interface ExtensionUpdateInfo { + name: string; + originalVersion: string; + updatedVersion: string; +} + +export interface ExtensionUpdateStatus { + status: ExtensionUpdateState; + processed: boolean; +} + +export enum ExtensionUpdateState { + CHECKING_FOR_UPDATES = 'checking for updates', + UPDATED_NEEDS_RESTART = 'updated, needs restart', + UPDATING = 'updating', + UPDATED = 'updated', + UPDATE_AVAILABLE = 'update available', + UP_TO_DATE = 'up to date', + ERROR = 'error', + NOT_UPDATABLE = 'not updatable', + UNKNOWN = 'unknown', +} + +/** Extension storage level - user level or project/workspace level */ +export type ExtensionLevel = 'user' | 'project'; + +export interface ExtensionManagerOptions { + /** Working directory for project-level extensions */ + workspaceDir?: string; + /** Override list of enabled extension names (from CLI -e flag) */ + enabledExtensionOverrides?: string[]; + isWorkspaceTrusted: boolean; + telemetrySettings?: TelemetrySettings; + config?: Config; + requestConsent?: (consent: string) => Promise; +} + +// ============================================================================ +// Helper Functions +// ============================================================================ + +function ensureLeadingAndTrailingSlash(dirPath: string): string { + let result = dirPath.replace(/\\/g, '/'); + if (result.charAt(0) !== '/') { + result = '/' + result; + } + if (result.charAt(result.length - 1) !== '/') { + result = result + '/'; + } + return result; +} + +function getTelemetryConfig( + cwd: string, + telemetrySettings?: TelemetrySettings, +) { + const config = new Config({ + telemetry: telemetrySettings, + interactive: false, + targetDir: cwd, + cwd, + model: '', + debugMode: false, + }); + return config; +} + +function filterMcpConfig(original: MCPServerConfig): MCPServerConfig { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { trust, ...rest } = original; + return Object.freeze(rest); +} + +function getContextFileNames(config: ExtensionConfig): string[] { + if (!config.contextFileName) { + return ['QWEN.md']; + } else if (!Array.isArray(config.contextFileName)) { + return [config.contextFileName]; + } + return config.contextFileName; +} + +async function loadCommandsFromDir( + dir: string, + extensionName: string, +): Promise { + const globOptions = { + nodir: true, + dot: true, + follow: true, + }; + + try { + const mdFiles = await glob('**/*.md', { + ...globOptions, + cwd: dir, + }); + + const commandNames = mdFiles.map((file) => { + const relativePathWithExt = path.relative(dir, path.join(dir, file)); + const relativePath = relativePathWithExt.substring( + 0, + relativePathWithExt.length - 3, + ); + const baseCommandName = relativePath + .split(path.sep) + .map((segment) => segment.replaceAll(':', '_')) + .join(':'); + + const commandName = `${extensionName}:${baseCommandName}`; + return commandName; + }); + + return commandNames; + } catch (error) { + const isEnoent = (error as NodeJS.ErrnoException).code === 'ENOENT'; + const isAbortError = error instanceof Error && error.name === 'AbortError'; + if (!isEnoent && !isAbortError) { + console.error(`Error loading commands from ${dir}:`, error); + } + return []; + } +} + +async function convertGeminiOrClaudeExtension(extensionDir: string) { + let newExtensionDir = extensionDir; + const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); + if (fs.existsSync(configFilePath)) { + newExtensionDir = extensionDir; + } else if (isGeminiExtensionConfig(extensionDir)) { + newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)) + .convertedDir; + } + // Claude plugin conversion not yet implemented + return newExtensionDir; +} + +// ============================================================================ +// ExtensionManager Class +// ============================================================================ + +/** + * ExtensionManager manages extensions at different levels (user/project) + * and directly implements enablement functionality. + * + * Reference: SkillManager pattern for level-based management + */ +export class ExtensionManager { + // Level-based cache (reference: SkillManager) + private extensionCache: Map | null = null; + + // Enablement configuration (directly implemented) + private readonly configDir: string; + private readonly configFilePath: string; + private readonly enabledExtensionNamesOverride: string[]; + private readonly workspaceDir: string; + + private config?: Config; + private telemetrySettings?: TelemetrySettings; + private isWorkspaceTrusted: boolean; + private requestConsent: (consent: string) => Promise; + + constructor(options: ExtensionManagerOptions) { + this.workspaceDir = options.workspaceDir ?? process.cwd(); + this.enabledExtensionNamesOverride = + options.enabledExtensionOverrides?.map((name) => name.toLowerCase()) ?? + []; + this.configDir = ExtensionStorage.getUserExtensionsDir(); + this.configFilePath = path.join( + this.configDir, + 'extension-enablement.json', + ); + this.requestConsent = + options.requestConsent || (() => Promise.resolve(true)); + this.config = options.config; + this.telemetrySettings = options.telemetrySettings; + this.isWorkspaceTrusted = options.isWorkspaceTrusted; + } + + setRequestConsent( + requestConsent: (consent: string) => Promise, + ): void { + this.requestConsent = requestConsent; + } + + // ========================================================================== + // Enablement functionality (directly implemented) + // ========================================================================== + + /** + * Validates that override extension names exist in the extensions list. + */ + validateExtensionOverrides(extensions: Extension[]): void { + for (const name of this.enabledExtensionNamesOverride) { + if (name === 'none') continue; + if ( + !extensions.some( + (ext) => ext.config.name.toLowerCase() === name.toLowerCase(), + ) + ) { + console.error(`Extension not found: ${name}`); + } + } + } + + /** + * Determines if an extension is enabled based on its name and the current path. + */ + isEnabled(extensionName: string, currentPath?: string): boolean { + const checkPath = currentPath ?? this.workspaceDir; + + // If we have a single override called 'none', this disables all extensions. + if ( + this.enabledExtensionNamesOverride.length === 1 && + this.enabledExtensionNamesOverride[0] === 'none' + ) { + return false; + } + + // If we have explicit overrides, only enable those extensions. + if (this.enabledExtensionNamesOverride.length > 0) { + return this.enabledExtensionNamesOverride.includes( + extensionName.toLowerCase(), + ); + } + + // Otherwise, use the configuration settings + const config = this.readEnablementConfig(); + const extensionConfig = config[extensionName]; + let enabled = true; + const allOverrides = extensionConfig?.overrides ?? []; + for (const rule of allOverrides) { + const override = Override.fromFileRule(rule); + if (override.matchesPath(ensureLeadingAndTrailingSlash(checkPath))) { + enabled = !override.isDisable; + } + } + return enabled; + } + + /** + * Enables an extension at the specified scope. + */ + enableExtension(name: string, scope: SettingScope, cwd?: string): void { + const currentDir = cwd ?? this.workspaceDir; + if ( + scope === SettingScope.System || + scope === SettingScope.SystemDefaults + ) { + throw new Error('System and SystemDefaults scopes are not supported.'); + } + const extension = this.loadExtensionByName(name, currentDir); + if (!extension) { + throw new Error(`Extension with name ${name} does not exist.`); + } + const scopePath = + scope === SettingScope.Workspace ? currentDir : os.homedir(); + this.enableByPath(name, true, scopePath); + const config = getTelemetryConfig(currentDir, this.telemetrySettings); + logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); + } + + /** + * Disables an extension at the specified scope. + */ + disableExtension(name: string, scope: SettingScope, cwd?: string): void { + const currentDir = cwd ?? this.workspaceDir; + const config = getTelemetryConfig(currentDir, this.telemetrySettings); + if ( + scope === SettingScope.System || + scope === SettingScope.SystemDefaults + ) { + throw new Error('System and SystemDefaults scopes are not supported.'); + } + const extension = this.loadExtensionByName(name, currentDir); + if (!extension) { + throw new Error(`Extension with name ${name} does not exist.`); + } + const scopePath = + scope === SettingScope.Workspace ? currentDir : os.homedir(); + this.disableByPath(name, true, scopePath); + logExtensionDisable(config, new ExtensionDisableEvent(name, scope)); + } + + /** + * Removes enablement configuration for an extension. + */ + removeEnablementConfig(extensionName: string): void { + const config = this.readEnablementConfig(); + if (config[extensionName]) { + delete config[extensionName]; + this.writeEnablementConfig(config); + } + } + + private enableByPath( + extensionName: string, + includeSubdirs: boolean, + scopePath: string, + ): void { + const config = this.readEnablementConfig(); + if (!config[extensionName]) { + config[extensionName] = { overrides: [] }; + } + const override = Override.fromInput(scopePath, includeSubdirs); + const overrides = config[extensionName].overrides.filter((rule) => { + const fileOverride = Override.fromFileRule(rule); + if ( + fileOverride.conflictsWith(override) || + fileOverride.isEqualTo(override) + ) { + return false; + } + return !fileOverride.isChildOf(override); + }); + overrides.push(override.output()); + config[extensionName].overrides = overrides; + this.writeEnablementConfig(config); + } + + private disableByPath( + extensionName: string, + includeSubdirs: boolean, + scopePath: string, + ): void { + this.enableByPath(extensionName, includeSubdirs, `!${scopePath}`); + } + + private readEnablementConfig(): AllExtensionsEnablementConfig { + try { + const content = fs.readFileSync(this.configFilePath, 'utf-8'); + return JSON.parse(content); + } catch (error) { + if ( + error instanceof Error && + 'code' in error && + error.code === 'ENOENT' + ) { + return {}; + } + console.error('Error reading extension enablement config:', error); + return {}; + } + } + + private writeEnablementConfig(config: AllExtensionsEnablementConfig): void { + fs.mkdirSync(this.configDir, { recursive: true }); + fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2)); + } + + // ========================================================================== + // Cache management (reference: SkillManager) + // ========================================================================== + + /** + * Refreshes the extension cache from disk. + */ + async refreshCache(): Promise { + this.extensionCache = new Map(); + this.extensionCache.set('user', await this.loadExtensionsAtLevel('user')); + this.extensionCache.set( + 'project', + await this.loadExtensionsAtLevel('project'), + ); + } + + getLoadedExtensions(): Extension[] { + if (!this.extensionCache) { + return []; + } + return [ + ...(this.extensionCache?.get('user') ?? []), + ...(this.extensionCache?.get('project') ?? []), + ]; + } + + /** + * Lists extensions at a specific level. + */ + listExtensionsAtLevel(level: ExtensionLevel): Extension[] { + if (!this.extensionCache) { + return []; + } + return this.extensionCache?.get(level) ?? []; + } + + private async loadExtensionsAtLevel( + level: ExtensionLevel, + ): Promise { + if (level === 'user') { + return await this.loadExtensionsFromDir(os.homedir()); + } else { + // project level + if (path.resolve(this.workspaceDir) === path.resolve(os.homedir())) { + return []; + } + return await this.loadExtensionsFromDir(this.workspaceDir); + } + } + + // ========================================================================== + // Extension loading methods + // ========================================================================== + + /** + * Loads an extension by name. + */ + async loadExtensionByName( + name: string, + workspaceDir?: string, + ): Promise { + const cwd = workspaceDir ?? this.workspaceDir; + const userExtensionsDir = ExtensionStorage.getUserExtensionsDir(); + if (!fs.existsSync(userExtensionsDir)) { + return null; + } + + for (const subdir of fs.readdirSync(userExtensionsDir)) { + const extensionDir = path.join(userExtensionsDir, subdir); + if (!fs.statSync(extensionDir).isDirectory()) { + continue; + } + const extension = await this.loadExtension({ + extensionDir, + workspaceDir: cwd, + }); + if ( + extension && + extension.config.name.toLowerCase() === name.toLowerCase() + ) { + return extension; + } + } + + return null; + } + + async loadExtensionsFromDir(dir: string): Promise { + const storage = new Storage(dir); + const extensionsDir = storage.getExtensionsDir(); + if (!fs.existsSync(extensionsDir)) { + return []; + } + + const extensions: Extension[] = []; + for (const subdir of fs.readdirSync(extensionsDir)) { + const extensionDir = path.join(extensionsDir, subdir); + + const extension = await this.loadExtension({ + extensionDir, + workspaceDir: dir, + }); + if (extension != null) { + extensions.push(extension); + } + } + return extensions; + } + + async loadExtension( + context: LoadExtensionContext, + ): Promise { + const { extensionDir, workspaceDir } = context; + if (!fs.statSync(extensionDir).isDirectory()) { + return null; + } + + const installMetadata = this.loadInstallMetadata(extensionDir); + let effectiveExtensionPath = extensionDir; + + if (installMetadata?.type === 'link') { + effectiveExtensionPath = installMetadata.source; + } + + try { + let config = this.loadExtensionConfig({ + extensionDir: effectiveExtensionPath, + workspaceDir, + }); + + config = resolveEnvVarsInObject(config); + + const extension: Extension = { + id: getExtensionId(config, installMetadata), + name: config.name, + version: config.version, + path: effectiveExtensionPath, + installMetadata, + isActive: this.isEnabled(config.name, this.workspaceDir), + config, + settings: config.settings, + contextFiles: [], + }; + + if (config.mcpServers) { + extension.mcpServers = Object.fromEntries( + Object.entries(config.mcpServers).map(([key, value]) => [ + key, + filterMcpConfig(value), + ]), + ); + } + + extension.contextFiles = getContextFileNames(config) + .map((contextFileName) => + path.join(effectiveExtensionPath, contextFileName), + ) + .filter((contextFilePath) => fs.existsSync(contextFilePath)); + + if (this.config) { + extension.skills = await this.config + .getSkillManager() + .loadSkillsFromDir(effectiveExtensionPath, 'extension'); + extension.agents = await this.config + .getSubagentManager() + .loadSubagentFromDir(effectiveExtensionPath, 'extension'); + } + + return extension; + } catch (e) { + console.error( + `Warning: Skipping extension in ${effectiveExtensionPath}: ${getErrorMessage( + e, + )}`, + ); + return null; + } + } + + loadInstallMetadata( + extensionDir: string, + ): ExtensionInstallMetadata | undefined { + const metadataFilePath = path.join(extensionDir, INSTALL_METADATA_FILENAME); + try { + const configContent = fs.readFileSync(metadataFilePath, 'utf-8'); + const metadata = JSON.parse(configContent) as ExtensionInstallMetadata; + return metadata; + } catch (_e) { + return undefined; + } + } + + loadExtensionConfig(context: LoadExtensionContext): ExtensionConfig { + const { extensionDir, workspaceDir = this.workspaceDir } = context; + const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); + if (!fs.existsSync(configFilePath)) { + throw new Error(`Configuration file not found at ${configFilePath}`); + } + try { + const configContent = fs.readFileSync(configFilePath, 'utf-8'); + const config = recursivelyHydrateStrings(JSON.parse(configContent), { + extensionPath: extensionDir, + CLAUDE_PLUGIN_ROOT: extensionDir, + workspacePath: workspaceDir, + '/': path.sep, + pathSeparator: path.sep, + }) as unknown as ExtensionConfig; + + if (!config.name || !config.version) { + throw new Error( + `Invalid configuration in ${configFilePath}: missing ${!config.name ? '"name"' : '"version"'}`, + ); + } + validateName(config.name); + return config; + } catch (e) { + throw new Error( + `Failed to load extension config from ${configFilePath}: ${getErrorMessage( + e, + )}`, + ); + } + } + + // ========================================================================== + // Extension installation/uninstallation + // ========================================================================== + + /** + * Installs an extension. + */ + async installExtension( + installMetadata: ExtensionInstallMetadata, + requestConsent?: (consent: string) => Promise, + cwd?: string, + previousExtensionConfig?: ExtensionConfig, + ): Promise { + const currentDir = cwd ?? this.workspaceDir; + const telemetryConfig = getTelemetryConfig( + currentDir, + this.telemetrySettings, + ); + let extension: Extension | null; + + const isUpdate = !!previousExtensionConfig; + let newExtensionConfig: ExtensionConfig | null = null; + let localSourcePath: string | undefined; + + try { + if (!this.isWorkspaceTrusted) { + throw new Error( + `Could not install extension from untrusted folder at ${installMetadata.source}`, + ); + } + + const extensionsDir = ExtensionStorage.getUserExtensionsDir(); + await fs.promises.mkdir(extensionsDir, { recursive: true }); + + if ( + !path.isAbsolute(installMetadata.source) && + (installMetadata.type === 'local' || installMetadata.type === 'link') + ) { + installMetadata.source = path.resolve( + currentDir, + installMetadata.source, + ); + } + + let tempDir: string | undefined; + + // Handle marketplace installation + if (installMetadata.type === 'marketplace') { + const marketplaceParsed = parseMarketplaceSource( + installMetadata.source, + ); + if (!marketplaceParsed) { + throw new Error( + `Invalid marketplace source format: ${installMetadata.source}. Expected format: marketplace-url:plugin-name`, + ); + } + + tempDir = await ExtensionStorage.createTmpDir(); + const marketplaceResult = await installFromMarketplace({ + marketplaceUrl: marketplaceParsed.marketplaceSource, + pluginName: marketplaceParsed.pluginName, + tempDir, + requestConsent: requestConsent || this.requestConsent, + }); + + newExtensionConfig = marketplaceResult.config; + localSourcePath = marketplaceResult.sourcePath; + installMetadata = marketplaceResult.installMetadata; + } else if ( + installMetadata.type === 'git' || + installMetadata.type === 'github-release' + ) { + tempDir = await ExtensionStorage.createTmpDir(); + try { + const result = await downloadFromGitHubRelease( + installMetadata, + tempDir, + ); + installMetadata.type = result.type; + installMetadata.releaseTag = result.tagName; + } catch (_error) { + await cloneFromGit(installMetadata, tempDir); + installMetadata.type = 'git'; + } + localSourcePath = tempDir; + } else if ( + installMetadata.type === 'local' || + installMetadata.type === 'link' + ) { + localSourcePath = installMetadata.source; + } else { + throw new Error(`Unsupported install type: ${installMetadata.type}`); + } + + try { + localSourcePath = await convertGeminiOrClaudeExtension(localSourcePath); + if (!newExtensionConfig) { + newExtensionConfig = this.loadExtensionConfig({ + extensionDir: localSourcePath, + workspaceDir: currentDir, + }); + } + + if (isUpdate && installMetadata.autoUpdate) { + const oldSettings = new Set( + previousExtensionConfig.settings?.map((s) => s.name) || [], + ); + const newSettings = new Set( + newExtensionConfig.settings?.map((s) => s.name) || [], + ); + + const settingsAreEqual = + oldSettings.size === newSettings.size && + [...oldSettings].every((value) => newSettings.has(value)); + + if (!settingsAreEqual && installMetadata.autoUpdate) { + throw new Error( + `Extension "${newExtensionConfig.name}" has settings changes and cannot be auto-updated. Please update manually.`, + ); + } + } + + const newExtensionName = newExtensionConfig.name; + const previous = this.getLoadedExtensions().find( + (installed) => installed.name === newExtensionName, + ); + if (isUpdate && !previous) { + throw new Error( + `Extension "${newExtensionName}" was not already installed, cannot update it.`, + ); + } else if (!isUpdate && previous) { + throw new Error( + `Extension "${newExtensionName}" is already installed. Please uninstall it first.`, + ); + } + + const commands = await loadCommandsFromDir( + `${localSourcePath}/commands`, + newExtensionConfig.name, + ); + + await maybeRequestConsentOrFail( + newExtensionConfig, + requestConsent || this.requestConsent, + commands, + previousExtensionConfig, + ); + + const extensionStorage = new ExtensionStorage(newExtensionName); + const destinationPath = extensionStorage.getExtensionDir(); + const extensionId = getExtensionId(newExtensionConfig, installMetadata); + let previousSettings: Record | undefined; + if (isUpdate) { + previousSettings = await getEnvContents( + previousExtensionConfig, + extensionId, + ); + await this.uninstallExtension(newExtensionName, isUpdate); + } + await fs.promises.mkdir(destinationPath, { recursive: true }); + + if (isUpdate) { + await maybePromptForSettings( + newExtensionConfig, + extensionId, + promptForSetting, + previousExtensionConfig, + previousSettings, + ); + } else { + await maybePromptForSettings( + newExtensionConfig, + extensionId, + promptForSetting, + ); + } + + if ( + installMetadata.type === 'local' || + installMetadata.type === 'git' || + installMetadata.type === 'github-release' + ) { + await copyExtension(localSourcePath, destinationPath); + } + + const metadataString = JSON.stringify(installMetadata, null, 2); + const metadataPath = path.join( + destinationPath, + INSTALL_METADATA_FILENAME, + ); + await fs.promises.writeFile(metadataPath, metadataString); + + extension = await this.loadExtension({ extensionDir: destinationPath }); + if (!extension) { + throw new Error(`Extension not found`); + } + + if (isUpdate) { + logExtensionUpdateEvent( + telemetryConfig, + new ExtensionUpdateEvent( + newExtensionConfig.name, + getExtensionId(newExtensionConfig, installMetadata), + newExtensionConfig.version, + previousExtensionConfig.version, + installMetadata.type, + 'success', + ), + ); + } else { + logExtensionInstallEvent( + telemetryConfig, + new ExtensionInstallEvent( + newExtensionConfig.name, + newExtensionConfig!.version, + installMetadata.source, + 'success', + ), + ); + this.enableExtension(newExtensionConfig.name, SettingScope.User); + } + } finally { + if (tempDir) { + await fs.promises.rm(tempDir, { recursive: true, force: true }); + } + if (localSourcePath !== tempDir) { + await fs.promises.rm(localSourcePath, { + recursive: true, + force: true, + }); + } + } + return extension; + } catch (error) { + if (!newExtensionConfig && localSourcePath) { + try { + newExtensionConfig = this.loadExtensionConfig({ + extensionDir: localSourcePath, + workspaceDir: currentDir, + }); + } catch { + // Ignore error + } + } + const config = newExtensionConfig ?? previousExtensionConfig; + const extensionId = config + ? getExtensionId(config, installMetadata) + : undefined; + if (isUpdate) { + logExtensionUpdateEvent( + telemetryConfig, + new ExtensionUpdateEvent( + config?.name ?? '', + extensionId ?? '', + newExtensionConfig?.version ?? '', + previousExtensionConfig.version, + installMetadata.type, + 'error', + ), + ); + } else { + logExtensionInstallEvent( + telemetryConfig, + new ExtensionInstallEvent( + newExtensionConfig?.name ?? '', + newExtensionConfig?.version ?? '', + installMetadata.source, + 'error', + ), + ); + } + throw error; + } + } + + /** + * Uninstalls an extension. + */ + async uninstallExtension( + extensionIdentifier: string, + isUpdate: boolean, + cwd?: string, + ): Promise { + const currentDir = cwd ?? this.workspaceDir; + const telemetryConfig = getTelemetryConfig( + currentDir, + this.telemetrySettings, + ); + const installedExtensions = this.getLoadedExtensions(); + const extension = installedExtensions.find( + (installed) => + installed.config.name.toLowerCase() === + extensionIdentifier.toLowerCase() || + installed.installMetadata?.source.toLowerCase() === + extensionIdentifier.toLowerCase(), + ); + if (!extension) { + throw new Error(`Extension not found.`); + } + const storage = new ExtensionStorage( + extension.installMetadata?.type === 'link' + ? extension.name + : path.basename(extension.path), + ); + + await fs.promises.rm(storage.getExtensionDir(), { + recursive: true, + force: true, + }); + + if (isUpdate) return; + + this.removeEnablementConfig(extension.name); + + logExtensionUninstall( + telemetryConfig, + new ExtensionUninstallEvent(extension.name, 'success'), + ); + } + + /** + * Converts an extension to output string. + */ + toOutputString(extension: Extension, workspaceDir?: string): string { + const cwd = workspaceDir ?? this.workspaceDir; + const userEnabled = this.isEnabled(extension.config.name, os.homedir()); + const workspaceEnabled = this.isEnabled(extension.config.name, cwd); + + const status = workspaceEnabled ? chalk.green('✓') : chalk.red('✗'); + let output = `${status} ${extension.config.name} (${extension.config.version})`; + output += `\n Path: ${extension.path}`; + if (extension.installMetadata) { + output += `\n Source: ${extension.installMetadata.source} (Type: ${extension.installMetadata.type})`; + if (extension.installMetadata.ref) { + output += `\n Ref: ${extension.installMetadata.ref}`; + } + if (extension.installMetadata.releaseTag) { + output += `\n Release tag: ${extension.installMetadata.releaseTag}`; + } + } + output += `\n Enabled (User): ${userEnabled}`; + output += `\n Enabled (Workspace): ${workspaceEnabled}`; + if (extension.contextFiles.length > 0) { + output += `\n Context files:`; + extension.contextFiles.forEach((contextFile) => { + output += `\n ${contextFile}`; + }); + } + if (extension.config.mcpServers) { + output += `\n MCP servers:`; + Object.keys(extension.config.mcpServers).forEach((key) => { + output += `\n ${key}`; + }); + } + if (extension.config.excludeTools) { + output += `\n Excluded tools:`; + extension.config.excludeTools.forEach((tool) => { + output += `\n ${tool}`; + }); + } + return output; + } + + async performWorkspaceExtensionMigration( + extensions: Extension[], + requestConsent: (consent: string) => Promise, + ): Promise { + const failedInstallNames: string[] = []; + + for (const extension of extensions) { + try { + const installMetadata: ExtensionInstallMetadata = { + source: extension.path, + type: 'local', + }; + await this.installExtension(installMetadata, requestConsent); + } catch (_) { + failedInstallNames.push(extension.config.name); + } + } + return failedInstallNames; + } + + async checkForAllExtensionUpdates( + callback: (extensionName: string, state: ExtensionUpdateState) => void, + ): Promise { + const extensions = this.getLoadedExtensions(); + const promises: Array> = []; + for (const extension of extensions) { + if (!extension.installMetadata) { + callback(extension.name, ExtensionUpdateState.NOT_UPDATABLE); + continue; + } + callback(extension.name, ExtensionUpdateState.CHECKING_FOR_UPDATES); + promises.push( + checkForExtensionUpdate(extension, this).then((state) => + callback(extension.name, state), + ), + ); + } + await Promise.all(promises); + } + + async updateExtension( + extension: Extension, + currentState: ExtensionUpdateState, + callback: (extensionName: string, state: ExtensionUpdateState) => void, + enableExtensionReloading?: boolean, + ): Promise { + if (currentState === ExtensionUpdateState.UPDATING) { + return undefined; + } + callback(extension.name, ExtensionUpdateState.UPDATING); + const installMetadata = this.loadInstallMetadata(extension.path); + + if (!installMetadata?.type) { + callback(extension.name, ExtensionUpdateState.ERROR); + throw new Error( + `Extension ${extension.name} cannot be updated, type is unknown.`, + ); + } + if (installMetadata?.type === 'link') { + callback(extension.name, ExtensionUpdateState.UP_TO_DATE); + throw new Error(`Extension is linked so does not need to be updated`); + } + const originalVersion = extension.version; + + const tempDir = await ExtensionStorage.createTmpDir(); + try { + const previousExtensionConfig = this.loadExtensionConfig({ + extensionDir: extension.path, + }); + let updatedExtension: Extension; + try { + updatedExtension = await this.installExtension( + installMetadata, + undefined, + undefined, + previousExtensionConfig, + ); + } catch (e) { + callback(extension.name, ExtensionUpdateState.ERROR); + throw new Error( + `Updated extension not found after installation, got error:\n${e}`, + ); + } + const updatedVersion = updatedExtension.version; + callback( + extension.name, + enableExtensionReloading + ? ExtensionUpdateState.UPDATED + : ExtensionUpdateState.UPDATED_NEEDS_RESTART, + ); + return { + name: extension.name, + originalVersion, + updatedVersion, + }; + } catch (e) { + console.error( + `Error updating extension, rolling back. ${getErrorMessage(e)}`, + ); + callback(extension.name, ExtensionUpdateState.ERROR); + await copyExtension(tempDir, extension.path); + throw e; + } finally { + await fs.promises.rm(tempDir, { recursive: true, force: true }); + } + } + + async updateAllUpdatableExtensions( + extensionsState: Map, + callback: (extensionName: string, state: ExtensionUpdateState) => void, + enableExtensionReloading?: boolean, + ): Promise { + const extensions = this.getLoadedExtensions(); + return ( + await Promise.all( + extensions + .filter( + (extension) => + extensionsState.get(extension.name)?.status === + ExtensionUpdateState.UPDATE_AVAILABLE, + ) + .map((extension) => + this.updateExtension( + extension, + extensionsState.get(extension.name)!.status, + callback, + enableExtensionReloading, + ), + ), + ) + ).filter((updateInfo) => !!updateInfo); + } +} + +export async function copyExtension( + source: string, + destination: string, +): Promise { + await fs.promises.cp(source, destination, { recursive: true }); +} + +export function getExtensionId( + config: ExtensionConfig, + installMetadata?: ExtensionInstallMetadata, +): string { + let idValue = config.name; + const githubUrlParts = + installMetadata && + (installMetadata.type === 'git' || + installMetadata.type === 'github-release') + ? parseGitHubRepoForReleases(installMetadata.source) + : null; + if (githubUrlParts) { + idValue = `https://github.com/${githubUrlParts.owner}/${githubUrlParts.repo}`; + } else { + idValue = installMetadata?.source ?? config.name; + } + return hashValue(idValue); +} + +export function hashValue(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +export function validateName(name: string) { + if (!/^[a-zA-Z0-9-]+$/.test(name)) { + throw new Error( + `Invalid extension name: "${name}". Only letters (a-z, A-Z), numbers (0-9), and dashes (-) are allowed.`, + ); + } +} + +/** + * Builds a consent string for installing an extension based on it's + * extensionConfig. + */ +export function extensionConsentString( + extensionConfig: ExtensionConfig, + commands?: string[], +): string { + const output: string[] = []; + const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); + output.push(`Installing extension "${extensionConfig.name}".`); + output.push( + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + ); + + if (mcpServerEntries.length) { + output.push('This extension will run the following MCP servers:'); + for (const [key, mcpServer] of mcpServerEntries) { + const isLocal = !!mcpServer.command; + const source = + mcpServer.httpUrl ?? + `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; + output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); + } + } + if (commands && commands.length > 0) { + output.push( + `This extension will add the following commands: ${commands.join(', ')}.`, + ); + } + if (extensionConfig.contextFileName) { + output.push( + `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, + ); + } + if (extensionConfig.excludeTools) { + output.push( + `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, + ); + } + return output.join('\n'); +} + +/** + * Requests consent from the user to install an extension (extensionConfig), if + * there is any difference between the consent string for `extensionConfig` and + * `previousExtensionConfig`. + * + * Always requests consent if previousExtensionConfig is null. + * + * Throws if the user does not consent. + */ +export async function maybeRequestConsentOrFail( + extensionConfig: ExtensionConfig, + requestConsent: (consent: string) => Promise, + commands: string[], + previousExtensionConfig?: ExtensionConfig, +) { + const extensionConsent = extensionConsentString(extensionConfig, commands); + if (previousExtensionConfig) { + const previousExtensionConsent = extensionConsentString( + previousExtensionConfig, + ); + if (previousExtensionConsent === extensionConsent) { + return; + } + } + if (!(await requestConsent(extensionConsent))) { + throw new Error(`Installation cancelled for "${extensionConfig.name}".`); + } +} + +export async function parseInstallSource( + source: string, +): Promise { + let installMetadata: ExtensionInstallMetadata; + const marketplaceParsed = parseMarketplaceSource(source); + if (marketplaceParsed) { + installMetadata = { + source, + type: 'marketplace', + marketplace: marketplaceParsed, + }; + } else if ( + source.startsWith('http://') || + source.startsWith('https://') || + source.startsWith('git@') || + source.startsWith('sso://') + ) { + installMetadata = { + source, + type: 'git', + }; + } else { + try { + await stat(source); + installMetadata = { + source, + type: 'local', + }; + } catch { + throw new Error('Install source not found.'); + } + } + return installMetadata; +} + +export { checkForExtensionUpdate }; diff --git a/packages/cli/src/config/extensions/extensionSettings.test.ts b/packages/core/src/extension/extensionSettings.test.ts similarity index 99% rename from packages/cli/src/config/extensions/extensionSettings.test.ts rename to packages/core/src/extension/extensionSettings.test.ts index 01fc631352b..4d185f896cc 100644 --- a/packages/cli/src/config/extensions/extensionSettings.test.ts +++ b/packages/core/src/extension/extensionSettings.test.ts @@ -10,12 +10,12 @@ import { ExtensionSettingScope, getScopedEnvContents, } from './extensionSettings.js'; -import type { ExtensionConfig } from '../extension.js'; +import type { ExtensionConfig } from './extensionManager.js'; import { ExtensionStorage } from './storage.js'; import prompts from 'prompts'; import * as fsPromises from 'node:fs/promises'; import * as fs from 'node:fs'; -import { KeychainTokenStorage } from '@qwen-code/qwen-code-core'; +import { KeychainTokenStorage } from '../mcp/token-storage/keychain-token-storage.js'; import { EXTENSION_SETTINGS_FILENAME } from './variables.js'; vi.mock('prompts'); diff --git a/packages/cli/src/config/extensions/extensionSettings.ts b/packages/core/src/extension/extensionSettings.ts similarity index 98% rename from packages/cli/src/config/extensions/extensionSettings.ts rename to packages/core/src/extension/extensionSettings.ts index 13561180d29..d35573d52d2 100644 --- a/packages/cli/src/config/extensions/extensionSettings.ts +++ b/packages/core/src/extension/extensionSettings.ts @@ -9,10 +9,10 @@ import * as fsSync from 'node:fs'; import * as dotenv from 'dotenv'; import * as path from 'node:path'; import { ExtensionStorage } from './storage.js'; -import type { ExtensionConfig } from '../extension.js'; +import type { ExtensionConfig } from './extensionManager.js'; import prompts from 'prompts'; import { EXTENSION_SETTINGS_FILENAME } from './variables.js'; -import { KeychainTokenStorage } from '@qwen-code/qwen-code-core'; +import { KeychainTokenStorage } from '../mcp/token-storage/keychain-token-storage.js'; export enum ExtensionSettingScope { USER = 'user', diff --git a/packages/cli/src/config/extensions/gemini-converter.test.ts b/packages/core/src/extension/gemini-converter.test.ts similarity index 100% rename from packages/cli/src/config/extensions/gemini-converter.test.ts rename to packages/core/src/extension/gemini-converter.test.ts diff --git a/packages/cli/src/config/extensions/gemini-converter.ts b/packages/core/src/extension/gemini-converter.ts similarity index 96% rename from packages/cli/src/config/extensions/gemini-converter.ts rename to packages/core/src/extension/gemini-converter.ts index ccba248f3ca..7d3c4488307 100644 --- a/packages/cli/src/config/extensions/gemini-converter.ts +++ b/packages/core/src/extension/gemini-converter.ts @@ -11,9 +11,9 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { glob } from 'glob'; -import type { ExtensionConfig, ExtensionSetting } from '../extension.js'; -import { ExtensionStorage } from '../extensions/storage.js'; -import { convertTomlToMarkdown } from '../../services/toml-to-markdown-converter.js'; +import type { ExtensionConfig, ExtensionSetting } from './extensionManager.js'; +import { ExtensionStorage } from './storage.js'; +import { convertTomlToMarkdown } from '../utils/toml-to-markdown-converter.js'; export interface GeminiExtensionConfig { name: string; diff --git a/packages/cli/src/config/extensions/github.test.ts b/packages/core/src/extension/github.test.ts similarity index 99% rename from packages/cli/src/config/extensions/github.test.ts rename to packages/core/src/extension/github.test.ts index 3bd1f1fdc6c..77cfd19278a 100644 --- a/packages/cli/src/config/extensions/github.test.ts +++ b/packages/core/src/extension/github.test.ts @@ -13,7 +13,6 @@ import { parseGitHubRepoForReleases, } from './github.js'; import { simpleGit, type SimpleGit } from 'simple-git'; -import { ExtensionUpdateState } from '../../ui/state/extensions.js'; import * as os from 'node:os'; import * as fs from 'node:fs/promises'; import * as fsSync from 'node:fs'; @@ -21,6 +20,7 @@ import * as path from 'node:path'; import * as tar from 'tar'; import * as archiver from 'archiver'; import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; +import type { ExtensionUpdateState } from './update.js'; const mockPlatform = vi.hoisted(() => vi.fn()); const mockArch = vi.hoisted(() => vi.fn()); diff --git a/packages/cli/src/config/extensions/github.ts b/packages/core/src/extension/github.ts similarity index 85% rename from packages/cli/src/config/extensions/github.ts rename to packages/core/src/extension/github.ts index 4db75c18aee..db2f0e80ea5 100644 --- a/packages/cli/src/config/extensions/github.ts +++ b/packages/core/src/extension/github.ts @@ -5,20 +5,38 @@ */ import { simpleGit } from 'simple-git'; -import { getErrorMessage } from '../../utils/errors.js'; -import type { - ExtensionInstallMetadata, - GeminiCLIExtension, -} from '@qwen-code/qwen-code-core'; -import { ExtensionUpdateState } from '../../ui/state/extensions.js'; +import { getErrorMessage } from '../utils/errors.js'; +import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; import * as os from 'node:os'; import * as https from 'node:https'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { loadExtension } from '../extension.js'; import { EXTENSIONS_CONFIG_FILENAME } from './variables.js'; import * as tar from 'tar'; import extract from 'extract-zip'; +import { + ExtensionUpdateState, + type Extension, + type ExtensionConfig, + type ExtensionManager, +} from './extensionManager.js'; + +interface GithubReleaseData { + assets: Asset[]; + tag_name: string; + tarball_url?: string; + zipball_url?: string; +} + +interface Asset { + name: string; + browser_download_url: string; +} + +export interface GitHubDownloadResult { + tagName: string; + type: 'git' | 'github-release'; +} function getGitHubToken(): string | undefined { return process.env['GITHUB_TOKEN']; @@ -116,38 +134,40 @@ async function fetchReleaseFromGithub( } export async function checkForExtensionUpdate( - extension: GeminiCLIExtension, - setExtensionUpdateState: (updateState: ExtensionUpdateState) => void, - cwd: string = process.cwd(), -): Promise { - setExtensionUpdateState(ExtensionUpdateState.CHECKING_FOR_UPDATES); + extension: Extension, + extensionManager: ExtensionManager, +): Promise { const installMetadata = extension.installMetadata; if (installMetadata?.type === 'local') { - const newExtension = loadExtension({ - extensionDir: installMetadata.source, - workspaceDir: cwd, - }); - if (!newExtension) { + let latestConfig: ExtensionConfig | undefined; + try { + latestConfig = extensionManager.loadExtensionConfig({ + extensionDir: installMetadata.source, + }); + } catch (e) { + console.error( + `Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}. Error: ${getErrorMessage(e)}`, + ); + return ExtensionUpdateState.NOT_UPDATABLE; + } + + if (!latestConfig) { console.error( `Failed to check for update for local extension "${extension.name}". Could not load extension from source path: ${installMetadata.source}`, ); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.NOT_UPDATABLE; } - if (newExtension.config.version !== extension.version) { - setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE); - return; + if (latestConfig.version !== extension.version) { + return ExtensionUpdateState.UPDATE_AVAILABLE; } - setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE); - return; + return ExtensionUpdateState.UP_TO_DATE; } if ( !installMetadata || (installMetadata.type !== 'git' && installMetadata.type !== 'github-release') ) { - setExtensionUpdateState(ExtensionUpdateState.NOT_UPDATABLE); - return; + return ExtensionUpdateState.NOT_UPDATABLE; } try { if (installMetadata.type === 'git') { @@ -155,14 +175,12 @@ export async function checkForExtensionUpdate( const remotes = await git.getRemotes(true); if (remotes.length === 0) { console.error('No git remotes found.'); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } const remoteUrl = remotes[0].refs.fetch; if (!remoteUrl) { console.error(`No fetch URL found for git remote ${remotes[0].name}.`); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } // Determine the ref to check on the remote. @@ -172,8 +190,7 @@ export async function checkForExtensionUpdate( if (typeof lsRemoteOutput !== 'string' || lsRemoteOutput.trim() === '') { console.error(`Git ref ${refToCheck} not found.`); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } const remoteHash = lsRemoteOutput.split('\t')[0]; @@ -183,21 +200,17 @@ export async function checkForExtensionUpdate( console.error( `Unable to parse hash from git ls-remote output "${lsRemoteOutput}"`, ); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } if (remoteHash === localHash) { - setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE); - return; + return ExtensionUpdateState.UP_TO_DATE; } - setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE); - return; + return ExtensionUpdateState.UPDATE_AVAILABLE; } else { const { source, releaseTag } = installMetadata; if (!source) { console.error(`No "source" provided for extension.`); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } const { owner, repo } = parseGitHubRepoForReleases(source); @@ -207,30 +220,28 @@ export async function checkForExtensionUpdate( installMetadata.ref, ); if (releaseData.tag_name !== releaseTag) { - setExtensionUpdateState(ExtensionUpdateState.UPDATE_AVAILABLE); - return; + return ExtensionUpdateState.UPDATE_AVAILABLE; } - setExtensionUpdateState(ExtensionUpdateState.UP_TO_DATE); - return; + return ExtensionUpdateState.UP_TO_DATE; } } catch (error) { console.error( `Failed to check for updates for extension "${installMetadata.source}": ${getErrorMessage(error)}`, ); - setExtensionUpdateState(ExtensionUpdateState.ERROR); - return; + return ExtensionUpdateState.ERROR; } } -export interface GitHubDownloadResult { - tagName: string; - type: 'git' | 'github-release'; -} + export async function downloadFromGitHubRelease( installMetadata: ExtensionInstallMetadata, destination: string, ): Promise { - const { source, ref } = installMetadata; - const { owner, repo } = parseGitHubRepoForReleases(source); + const { source, ref, marketplace, type } = installMetadata; + const { owner, repo } = parseGitHubRepoForReleases( + type === 'marketplace' && marketplace + ? marketplace.marketplaceSource + : source, + ); try { const releaseData = await fetchReleaseFromGithub(owner, repo, ref); @@ -314,18 +325,6 @@ export async function downloadFromGitHubRelease( } } -interface GithubReleaseData { - assets: Asset[]; - tag_name: string; - tarball_url?: string; - zipball_url?: string; -} - -interface Asset { - name: string; - browser_download_url: string; -} - export function findReleaseAsset(assets: Asset[]): Asset | undefined { const platform = os.platform(); const arch = os.arch(); diff --git a/packages/cli/src/config/extensions/marketplace.test.ts b/packages/core/src/extension/marketplace.test.ts similarity index 87% rename from packages/cli/src/config/extensions/marketplace.test.ts rename to packages/core/src/extension/marketplace.test.ts index 151aa9efab6..5a69bf388d3 100644 --- a/packages/cli/src/config/extensions/marketplace.test.ts +++ b/packages/core/src/extension/marketplace.test.ts @@ -14,7 +14,7 @@ describe('Marketplace Installation', () => { 'http://example.com/marketplace:my-plugin', ); expect(result).toEqual({ - marketplaceUrl: 'http://example.com/marketplace', + marketplaceSource: 'http://example.com/marketplace', pluginName: 'my-plugin', }); }); @@ -24,7 +24,7 @@ describe('Marketplace Installation', () => { 'https://github.com/example/marketplace:awesome-plugin', ); expect(result).toEqual({ - marketplaceUrl: 'https://github.com/example/marketplace', + marketplaceSource: 'https://github.com/example/marketplace', pluginName: 'awesome-plugin', }); }); @@ -34,7 +34,7 @@ describe('Marketplace Installation', () => { 'https://example.com:my-super-plugin', ); expect(result).toEqual({ - marketplaceUrl: 'https://example.com', + marketplaceSource: 'https://example.com', pluginName: 'my-super-plugin', }); }); @@ -44,7 +44,7 @@ describe('Marketplace Installation', () => { 'https://example.com:8080/marketplace:plugin', ); expect(result).toEqual({ - marketplaceUrl: 'https://example.com:8080/marketplace', + marketplaceSource: 'https://example.com:8080/marketplace', pluginName: 'plugin', }); }); @@ -70,7 +70,7 @@ describe('Marketplace Installation', () => { 'https://example.com:8080:my-plugin', ); expect(result).toEqual({ - marketplaceUrl: 'https://example.com:8080', + marketplaceSource: 'https://example.com:8080', pluginName: 'my-plugin', }); }); diff --git a/packages/cli/src/config/extensions/marketplace.ts b/packages/core/src/extension/marketplace.ts similarity index 95% rename from packages/cli/src/config/extensions/marketplace.ts rename to packages/core/src/extension/marketplace.ts index e254ca41ffa..0f90a5e5e90 100644 --- a/packages/cli/src/config/extensions/marketplace.ts +++ b/packages/core/src/extension/marketplace.ts @@ -13,7 +13,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import type { ExtensionConfig } from '../extension.js'; +import type { ExtensionConfig } from './extensionManager.js'; import { convertClaudeToQwenConfig, mergeClaudeConfigs, @@ -42,7 +42,7 @@ export interface MarketplaceInstallResult { * Format: marketplace-url:plugin-name */ export function parseMarketplaceSource(source: string): { - marketplaceUrl: string; + marketplaceSource: string; pluginName: string; } | null { // Check if source contains a colon separator @@ -52,13 +52,13 @@ export function parseMarketplaceSource(source: string): { } // Split at the last colon to separate URL from plugin name - const marketplaceUrl = source.substring(0, lastColonIndex); + const marketplaceSource = source.substring(0, lastColonIndex); const pluginName = source.substring(lastColonIndex + 1); // Validate that marketplace URL looks like a URL if ( - !marketplaceUrl.startsWith('http://') && - !marketplaceUrl.startsWith('https://') + !marketplaceSource.startsWith('http://') && + !marketplaceSource.startsWith('https://') ) { return null; } @@ -67,7 +67,7 @@ export function parseMarketplaceSource(source: string): { return null; } - return { marketplaceUrl, pluginName }; + return { marketplaceSource, pluginName }; } /** diff --git a/packages/core/src/extension/override.test.ts b/packages/core/src/extension/override.test.ts new file mode 100644 index 00000000000..5e7a9b46722 --- /dev/null +++ b/packages/core/src/extension/override.test.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { Override } from './override.js'; + +describe('Override', () => { + it('should create an override from input', () => { + const override = Override.fromInput('/path/to/dir', true); + expect(override.baseRule).toBe(`/path/to/dir/`); + expect(override.isDisable).toBe(false); + expect(override.includeSubdirs).toBe(true); + }); + + it('should create a disable override from input', () => { + const override = Override.fromInput('!/path/to/dir', false); + expect(override.baseRule).toBe(`/path/to/dir/`); + expect(override.isDisable).toBe(true); + expect(override.includeSubdirs).toBe(false); + }); + + it('should create an override from a file rule', () => { + const override = Override.fromFileRule('/path/to/dir'); + expect(override.baseRule).toBe('/path/to/dir'); + expect(override.isDisable).toBe(false); + expect(override.includeSubdirs).toBe(false); + }); + + it('should create a disable override from a file rule', () => { + const override = Override.fromFileRule('!/path/to/dir/'); + expect(override.isDisable).toBe(true); + expect(override.baseRule).toBe('/path/to/dir/'); + expect(override.includeSubdirs).toBe(false); + }); + + it('should create an override with subdirs from a file rule', () => { + const override = Override.fromFileRule('/path/to/dir/*'); + expect(override.baseRule).toBe('/path/to/dir/'); + expect(override.isDisable).toBe(false); + expect(override.includeSubdirs).toBe(true); + }); + + it('should correctly identify conflicting overrides', () => { + const override1 = Override.fromInput('/path/to/dir', true); + const override2 = Override.fromInput('/path/to/dir', false); + expect(override1.conflictsWith(override2)).toBe(true); + }); + + it('should correctly identify non-conflicting overrides', () => { + const override1 = Override.fromInput('/path/to/dir', true); + const override2 = Override.fromInput('/path/to/another/dir', true); + expect(override1.conflictsWith(override2)).toBe(false); + }); + + it('should correctly identify equal overrides', () => { + const override1 = Override.fromInput('/path/to/dir', true); + const override2 = Override.fromInput('/path/to/dir', true); + expect(override1.isEqualTo(override2)).toBe(true); + }); + + it('should correctly identify unequal overrides', () => { + const override1 = Override.fromInput('/path/to/dir', true); + const override2 = Override.fromInput('!/path/to/dir', true); + expect(override1.isEqualTo(override2)).toBe(false); + }); + + it('should generate the correct regex', () => { + const override = Override.fromInput('/path/to/dir', true); + const regex = override.asRegex(); + expect(regex.test('/path/to/dir/')).toBe(true); + expect(regex.test('/path/to/dir/subdir')).toBe(true); + expect(regex.test('/path/to/another/dir')).toBe(false); + }); + + it('should correctly identify child overrides', () => { + const parent = Override.fromInput('/path/to/dir', true); + const child = Override.fromInput('/path/to/dir/subdir', false); + expect(child.isChildOf(parent)).toBe(true); + }); + + it('should correctly identify child overrides with glob', () => { + const parent = Override.fromInput('/path/to/dir/*', true); + const child = Override.fromInput('/path/to/dir/subdir', false); + expect(child.isChildOf(parent)).toBe(true); + }); + + it('should correctly identify non-child overrides', () => { + const parent = Override.fromInput('/path/to/dir', true); + const other = Override.fromInput('/path/to/another/dir', false); + expect(other.isChildOf(parent)).toBe(false); + }); + + it('should generate the correct output string', () => { + const override = Override.fromInput('/path/to/dir', true); + expect(override.output()).toBe(`/path/to/dir/*`); + }); + + it('should generate the correct output string for a disable override', () => { + const override = Override.fromInput('!/path/to/dir', false); + expect(override.output()).toBe(`!/path/to/dir/`); + }); + + it('should disable a path based on a disable override rule', () => { + const override = Override.fromInput('!/path/to/dir', false); + expect(override.output()).toBe(`!/path/to/dir/`); + }); +}); diff --git a/packages/core/src/extension/override.ts b/packages/core/src/extension/override.ts new file mode 100644 index 00000000000..caafe001ae6 --- /dev/null +++ b/packages/core/src/extension/override.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +export interface ExtensionEnablementConfig { + overrides: string[]; +} + +export interface AllExtensionsEnablementConfig { + [extensionName: string]: ExtensionEnablementConfig; +} + +export class Override { + constructor( + public baseRule: string, + public isDisable: boolean, + public includeSubdirs: boolean, + ) {} + + static fromInput(inputRule: string, includeSubdirs: boolean): Override { + const isDisable = inputRule.startsWith('!'); + let baseRule = isDisable ? inputRule.substring(1) : inputRule; + baseRule = ensureLeadingAndTrailingSlash(baseRule); + return new Override(baseRule, isDisable, includeSubdirs); + } + + static fromFileRule(fileRule: string): Override { + const isDisable = fileRule.startsWith('!'); + let baseRule = isDisable ? fileRule.substring(1) : fileRule; + const includeSubdirs = baseRule.endsWith('*'); + baseRule = includeSubdirs + ? baseRule.substring(0, baseRule.length - 1) + : baseRule; + return new Override(baseRule, isDisable, includeSubdirs); + } + + conflictsWith(other: Override): boolean { + if (this.baseRule === other.baseRule) { + return ( + this.includeSubdirs !== other.includeSubdirs || + this.isDisable !== other.isDisable + ); + } + return false; + } + + isEqualTo(other: Override): boolean { + return ( + this.baseRule === other.baseRule && + this.includeSubdirs === other.includeSubdirs && + this.isDisable === other.isDisable + ); + } + + asRegex(): RegExp { + return globToRegex(`${this.baseRule}${this.includeSubdirs ? '*' : ''}`); + } + + isChildOf(parent: Override) { + if (!parent.includeSubdirs) { + return false; + } + return parent.asRegex().test(this.baseRule); + } + + output(): string { + return `${this.isDisable ? '!' : ''}${this.baseRule}${this.includeSubdirs ? '*' : ''}`; + } + + matchesPath(path: string) { + return this.asRegex().test(path); + } +} + +const ensureLeadingAndTrailingSlash = function (dirPath: string): string { + // Normalize separators to forward slashes for consistent matching across platforms. + let result = dirPath.replace(/\\/g, '/'); + if (result.charAt(0) !== '/') { + result = '/' + result; + } + if (result.charAt(result.length - 1) !== '/') { + result = result + '/'; + } + return result; +}; + +/** + * Converts a glob pattern to a RegExp object. + * This is a simplified implementation that supports `*`. + * + * @param glob The glob pattern to convert. + * @returns A RegExp object. + */ +function globToRegex(glob: string): RegExp { + const regexString = glob + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters + .replace(/(\/?)\*/g, '($1.*)?'); // Convert * to optional group + + return new RegExp(`^${regexString}$`); +} diff --git a/packages/cli/src/config/extensions/settings.test.ts b/packages/core/src/extension/settings.test.ts similarity index 98% rename from packages/cli/src/config/extensions/settings.test.ts rename to packages/core/src/extension/settings.test.ts index cdd9517261d..cef81dd01a1 100644 --- a/packages/cli/src/config/extensions/settings.test.ts +++ b/packages/core/src/extension/settings.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect } from 'vitest'; import { parseEnvFile, generateEnvFile, validateSettings } from './settings.js'; -import type { ExtensionSetting } from '../extension.js'; +import type { ExtensionSetting } from './extensionManager.js'; describe('Extension Settings', () => { describe('parseEnvFile', () => { diff --git a/packages/cli/src/config/extensions/settings.ts b/packages/core/src/extension/settings.ts similarity index 98% rename from packages/cli/src/config/extensions/settings.ts rename to packages/core/src/extension/settings.ts index baff07338ae..522ffd0916a 100644 --- a/packages/cli/src/config/extensions/settings.ts +++ b/packages/core/src/extension/settings.ts @@ -11,7 +11,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import type { ExtensionSetting } from '../extension.js'; +import type { ExtensionSetting } from './extensionManager.js'; /** * Parse .env file content into key-value pairs. diff --git a/packages/cli/src/config/extensions/storage.test.ts b/packages/core/src/extension/storage.test.ts similarity index 100% rename from packages/cli/src/config/extensions/storage.test.ts rename to packages/core/src/extension/storage.test.ts diff --git a/packages/cli/src/config/extensions/storage.ts b/packages/core/src/extension/storage.ts similarity index 100% rename from packages/cli/src/config/extensions/storage.ts rename to packages/core/src/extension/storage.ts diff --git a/packages/cli/src/config/extensions/variableSchema.ts b/packages/core/src/extension/variableSchema.ts similarity index 85% rename from packages/cli/src/config/extensions/variableSchema.ts rename to packages/core/src/extension/variableSchema.ts index f38e1b1f81e..e509eb05d36 100644 --- a/packages/cli/src/config/extensions/variableSchema.ts +++ b/packages/core/src/extension/variableSchema.ts @@ -17,7 +17,7 @@ export interface VariableSchema { export interface LoadExtensionContext { extensionDir: string; - workspaceDir: string; + workspaceDir?: string; } const PATH_SEPARATOR_DEFINITION = { @@ -30,6 +30,10 @@ export const VARIABLE_SCHEMA = { type: 'string', description: 'The path of the extension in the filesystem.', }, + CLAUDE_PLUGIN_ROOT: { + type: 'string', + description: 'The path of the extension in the filesystem.', + }, workspacePath: { type: 'string', description: 'The absolute path of the current workspace.', diff --git a/packages/cli/src/config/extensions/variables.test.ts b/packages/core/src/extension/variables.test.ts similarity index 100% rename from packages/cli/src/config/extensions/variables.test.ts rename to packages/core/src/extension/variables.test.ts diff --git a/packages/cli/src/config/extensions/variables.ts b/packages/core/src/extension/variables.ts similarity index 100% rename from packages/cli/src/config/extensions/variables.ts rename to packages/core/src/extension/variables.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 36656b9b2a7..8d93c35ce71 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -83,6 +83,9 @@ export * from './subagents/index.js'; // Export skills export * from './skills/index.js'; +// Export extension +export * from './extension/extensionManager.js'; + // Export prompt logic export * from './prompts/mcp-prompts.js'; diff --git a/packages/core/src/skills/skill-manager-extension.test.ts b/packages/core/src/skills/skill-manager-extension.test.ts deleted file mode 100644 index 142872cbfe5..00000000000 --- a/packages/core/src/skills/skill-manager-extension.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @license - * Copyright 2025 Qwen - * SPDX-License-Identifier: Apache-2.0 - */ - -import { describe, it, expect, beforeEach } from 'vitest'; -import { SkillManager, type Extension } from './skill-manager.js'; -import type { Config } from '../config/config.js'; -import * as fs from 'fs/promises'; -import * as path from 'path'; -import * as os from 'os'; - -describe('SkillManager - Extension Support', () => { - let manager: SkillManager; - let mockConfig: Config; - let tmpDir: string; - - beforeEach(async () => { - // Create a temporary directory for testing - tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'skill-manager-test-')); - - mockConfig = { - getProjectRoot: () => tmpDir, - } as Config; - - manager = new SkillManager(mockConfig); - }); - - describe('listSkillsFromExtensions', () => { - it('should return empty array when no extensions provided', async () => { - const skills = await manager.listSkillsFromExtensions([]); - expect(skills).toEqual([]); - }); - - it('should return empty array when extensions have no skills paths', async () => { - const extensions: Extension[] = [ - { - path: '/path/to/extension', - config: { name: 'test', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [], - }, - ]; - - const skills = await manager.listSkillsFromExtensions(extensions); - expect(skills).toEqual([]); - }); - - it('should load skills from extension directories', async () => { - // Create test extension with a skill - const extensionDir = path.join(tmpDir, 'test-extension'); - const skillsDir = path.join(extensionDir, 'skills'); - const skillDir = path.join(skillsDir, 'test-skill'); - await fs.mkdir(skillDir, { recursive: true }); - - const skillContent = `--- -name: test-skill -description: A test skill from extension ---- - -This is a test skill from an extension.`; - - await fs.writeFile(path.join(skillDir, 'SKILL.md'), skillContent); - - const extensions: Extension[] = [ - { - path: extensionDir, - config: { name: 'test-extension', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [skillsDir], - }, - ]; - - const skills = await manager.listSkillsFromExtensions(extensions); - expect(skills).toHaveLength(1); - expect(skills[0].name).toBe('test-skill'); - expect(skills[0].description).toBe('A test skill from extension'); - expect(skills[0].level).toBe('extension'); - expect(skills[0].extensionName).toBe('test-extension'); - }); - - it('should load skills from multiple extensions', async () => { - // Create first extension - const ext1Dir = path.join(tmpDir, 'ext1'); - const skill1Dir = path.join(ext1Dir, 'skills', 'skill1'); - await fs.mkdir(skill1Dir, { recursive: true }); - await fs.writeFile( - path.join(skill1Dir, 'SKILL.md'), - '---\nname: skill1\ndescription: Skill 1\n---\nContent 1', - ); - - // Create second extension - const ext2Dir = path.join(tmpDir, 'ext2'); - const skill2Dir = path.join(ext2Dir, 'skills', 'skill2'); - await fs.mkdir(skill2Dir, { recursive: true }); - await fs.writeFile( - path.join(skill2Dir, 'SKILL.md'), - '---\nname: skill2\ndescription: Skill 2\n---\nContent 2', - ); - - const extensions: Extension[] = [ - { - path: ext1Dir, - config: { name: 'ext1', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [path.join(ext1Dir, 'skills')], - }, - { - path: ext2Dir, - config: { name: 'ext2', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [path.join(ext2Dir, 'skills')], - }, - ]; - - const skills = await manager.listSkillsFromExtensions(extensions); - expect(skills).toHaveLength(2); - expect(skills.map((s) => s.name)).toContain('skill1'); - expect(skills.map((s) => s.name)).toContain('skill2'); - }); - - it('should handle invalid skill files gracefully', async () => { - const extensionDir = path.join(tmpDir, 'test-extension'); - const skillsDir = path.join(extensionDir, 'skills'); - const skillDir = path.join(skillsDir, 'invalid-skill'); - await fs.mkdir(skillDir, { recursive: true }); - - // Create invalid skill file (missing name) - await fs.writeFile( - path.join(skillDir, 'SKILL.md'), - '---\ndescription: Invalid\n---\nContent', - ); - - const extensions: Extension[] = [ - { - path: extensionDir, - config: { name: 'test-extension', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [skillsDir], - }, - ]; - - const skills = await manager.listSkillsFromExtensions(extensions); - // Should skip invalid skill - expect(skills).toHaveLength(0); - }); - }); - - describe('listSkills with extensions', () => { - it('should include extension skills in list with correct precedence', async () => { - // Create project-level skill - const projectSkillsDir = path.join(tmpDir, '.qwen', 'skills'); - const projectSkillDir = path.join(projectSkillsDir, 'project-skill'); - await fs.mkdir(projectSkillDir, { recursive: true }); - await fs.writeFile( - path.join(projectSkillDir, 'SKILL.md'), - '---\nname: shared-skill\ndescription: Project skill\n---\nProject', - ); - - // Create extension skill with same name (should be overridden) - const extensionDir = path.join(tmpDir, 'test-extension'); - const extSkillsDir = path.join(extensionDir, 'skills'); - const extSkillDir = path.join(extSkillsDir, 'ext-skill'); - await fs.mkdir(extSkillDir, { recursive: true }); - await fs.writeFile( - path.join(extSkillDir, 'SKILL.md'), - '---\nname: shared-skill\ndescription: Extension skill\n---\nExtension', - ); - - const extensions: Extension[] = [ - { - path: extensionDir, - config: { name: 'test-extension', version: '1.0.0' }, - contextFiles: [], - skillsPaths: [extSkillsDir], - }, - ]; - - // Pass extensions to listSkills - manager.setExtensions(extensions); - const skills = await manager.listSkills(); - - // Project skill should take precedence - const sharedSkill = skills.find((s) => s.name === 'shared-skill'); - expect(sharedSkill).toBeDefined(); - expect(sharedSkill?.description).toBe('Project skill'); - expect(sharedSkill?.level).toBe('project'); - }); - }); -}); diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 27810fb4095..3f850323595 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -21,21 +21,6 @@ const QWEN_CONFIG_DIR = '.qwen'; const SKILLS_CONFIG_DIR = 'skills'; const SKILL_MANIFEST_FILE = 'SKILL.md'; -/** - * Simplified Extension interface for SkillManager. - * Avoids circular dependency with cli package. - */ -export interface Extension { - path: string; - config: { - name: string; - version: string; - }; - /** Absolute paths to skills directories from this extension */ - skillsPaths?: string[]; - contextFiles?: string[]; -} - /** * Manages skill configurations stored as directories containing SKILL.md files. * Provides discovery, parsing, validation, and caching for skills. @@ -44,20 +29,9 @@ export class SkillManager { private skillsCache: Map | null = null; private readonly changeListeners: Set<() => void> = new Set(); private parseErrors: Map = new Map(); - private extensions: Extension[] = []; constructor(private readonly config: Config) {} - /** - * Sets the extensions to load skills from. - * Should be called before listSkills() to include extension skills. - */ - setExtensions(extensions: Extension[]): void { - this.extensions = extensions; - // Invalidate cache when extensions change - this.skillsCache = null; - } - /** * Adds a listener that will be called when skills change. * @returns A function to remove the listener. @@ -236,123 +210,17 @@ export class SkillManager { const skillsCache = new Map(); this.parseErrors.clear(); - const levels: SkillLevel[] = ['project', 'user']; + const levels: SkillLevel[] = ['project', 'user', 'extension']; for (const level of levels) { const levelSkills = await this.listSkillsAtLevel(level); skillsCache.set(level, levelSkills); } - // Load extension skills - const extensionSkills = await this.listSkillsFromExtensions( - this.extensions, - ); - skillsCache.set('extension', extensionSkills); - this.skillsCache = skillsCache; this.notifyChangeListeners(); } - /** - * Lists skills from all extensions. - * - * @param extensions - Array of extensions to load skills from - * @returns Array of skill configurations from extensions - */ - async listSkillsFromExtensions( - extensions: Extension[], - ): Promise { - const skills: SkillConfig[] = []; - - for (const extension of extensions) { - if (!extension.skillsPaths || extension.skillsPaths.length === 0) { - continue; - } - - for (const skillsPath of extension.skillsPaths) { - try { - const entries = await fs.readdir(skillsPath, { withFileTypes: true }); - - for (const entry of entries) { - // Only process directories (each skill is a directory) - if (!entry.isDirectory()) continue; - - const skillDir = path.join(skillsPath, entry.name); - const skillManifest = path.join(skillDir, SKILL_MANIFEST_FILE); - - try { - // Check if SKILL.md exists - await fs.access(skillManifest); - - const config = await this.parseSkillFileInternal( - skillManifest, - 'extension', - ); - config.extensionName = extension.config.name; - skills.push(config); - } catch (error) { - // Skip directories without valid SKILL.md - if (error instanceof SkillError) { - // Parse error was already recorded - console.warn( - `Failed to parse skill at ${skillDir}: ${error.message}`, - ); - } - continue; - } - } - } catch (error) { - // Directory doesn't exist or can't be read, skip this path - console.warn( - `Failed to read skills from extension ${extension.config.name} at ${skillsPath}: ${error instanceof Error ? error.message : 'Unknown error'}`, - ); - continue; - } - } - } - - return skills; - } - - /** - * Lists skills from directory. - * - * @param dir - provided directory - * @returns Array of skill configurations - */ - // async parseSkillsFromDir(dir: string): Promise { - // const discoveredSkills: SkillConfig[] = []; - - // try { - // const absoluteSearchPath = path.resolve(dir); - // const stats = await fs.stat(absoluteSearchPath).catch(() => null); - // if (!stats || !stats.isDirectory()) { - // return []; - // } - - // const skillFiles = await glob('*/SKILL.md', { - // cwd: absoluteSearchPath, - // absolute: true, - // nodir: true, - // }); - - // for (const skillFile of skillFiles) { - // const metadata = await this.parseSkillFile(skillFile, 'extension'); - // if (metadata) { - // discoveredSkills.push(metadata); - // } - // } - // } catch (error) { - // coreEvents.emitFeedback( - // 'warning', - // `Error discovering skills in ${dir}:`, - // error, - // ); - // } - - // return discoveredSkills; - // } - /** * Parses a SKILL.md file and returns the configuration. * @@ -508,12 +376,22 @@ export class SkillManager { return []; } + // if (level === 'extension') { + // const extensions = this.config.getExtensions(); + // } + const baseDir = this.getSkillsBaseDir(level); + const skills = await this.loadSkillsFromDir(baseDir, level); + return skills; + } + async loadSkillsFromDir( + baseDir: string, + level: SkillLevel, + ): Promise { try { const entries = await fs.readdir(baseDir, { withFileTypes: true }); const skills: SkillConfig[] = []; - for (const entry of entries) { // Only process directories (each skill is a directory) if (!entry.isDirectory()) continue; @@ -541,7 +419,6 @@ export class SkillManager { continue; } } - return skills; } catch (_error) { // Directory doesn't exist or can't be read diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index abe9b3a1851..303292e8954 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -345,7 +345,7 @@ export class SubagentManager { // Normal mode: load from project, user, and builtin levels const levelsToCheck: SubagentLevel[] = options.level ? [options.level] - : ['project', 'user', 'builtin']; + : ['project', 'user', 'builtin', 'extension']; // Check if we should use cache or force refresh const shouldUseCache = !options.force && this.subagentsCache !== null; @@ -443,7 +443,7 @@ export class SubagentManager { private async refreshCache(): Promise { const subagentsCache = new Map(); - const levels: SubagentLevel[] = ['project', 'user', 'builtin']; + const levels: SubagentLevel[] = ['project', 'user', 'builtin', 'extension']; for (const level of levels) { const levelSubagents = await this.listSubagentsAtLevel(level); @@ -832,6 +832,14 @@ export class SubagentManager { let baseDir = level === 'project' ? projectRoot : homeDir; baseDir = path.join(baseDir, QWEN_CONFIG_DIR, AGENT_CONFIG_DIR); + const subagents = await this.loadSubagentFromDir(baseDir, level); + return subagents; + } + + async loadSubagentFromDir( + baseDir: string, + level: SubagentLevel, + ): Promise { try { const files = await fs.readdir(baseDir); const subagents: SubagentConfig[] = []; diff --git a/packages/core/src/telemetry/constants.ts b/packages/core/src/telemetry/constants.ts index acbf560258f..fe65d798d90 100644 --- a/packages/core/src/telemetry/constants.ts +++ b/packages/core/src/telemetry/constants.ts @@ -17,6 +17,7 @@ export const EVENT_EXTENSION_DISABLE = 'qwen-code.extension_disable'; export const EVENT_EXTENSION_ENABLE = 'qwen-code.extension_enable'; export const EVENT_EXTENSION_INSTALL = 'qwen-code.extension_install'; export const EVENT_EXTENSION_UNINSTALL = 'qwen-code.extension_uninstall'; +export const EVENT_EXTENSION_UPDATE = 'qwen-code.extension_update'; export const EVENT_FLASH_FALLBACK = 'qwen-code.flash_fallback'; export const EVENT_RIPGREP_FALLBACK = 'qwen-code.ripgrep_fallback'; export const EVENT_NEXT_SPEAKER_CHECK = 'qwen-code.next_speaker_check'; diff --git a/packages/core/src/telemetry/index.ts b/packages/core/src/telemetry/index.ts index d0feb0202fc..5a8139a336e 100644 --- a/packages/core/src/telemetry/index.ts +++ b/packages/core/src/telemetry/index.ts @@ -41,6 +41,8 @@ export { logExtensionEnable, logExtensionInstallEvent, logExtensionUninstall, + logExtensionDisable, + logExtensionUpdateEvent, logRipgrepFallback, logNextSpeakerCheck, logAuth, diff --git a/packages/core/src/telemetry/loggers.ts b/packages/core/src/telemetry/loggers.ts index 16b4dc5a709..82e4444d2df 100644 --- a/packages/core/src/telemetry/loggers.ts +++ b/packages/core/src/telemetry/loggers.ts @@ -38,6 +38,7 @@ import { EVENT_INVALID_CHUNK, EVENT_AUTH, EVENT_SKILL_LAUNCH, + EVENT_EXTENSION_UPDATE, } from './constants.js'; import { recordApiErrorMetrics, @@ -79,6 +80,7 @@ import type { ExtensionDisableEvent, ExtensionEnableEvent, ExtensionUninstallEvent, + ExtensionUpdateEvent, ExtensionInstallEvent, ModelSlashCommandEvent, SubagentExecutionEvent, @@ -800,6 +802,32 @@ export function logExtensionUninstall( logger.emit(logRecord); } +export async function logExtensionUpdateEvent( + config: Config, + event: ExtensionUpdateEvent, +): Promise { + QwenLogger.getInstance(config)?.logExtensionUpdateEvent(event); + + const attributes: LogAttributes = { + ...getCommonAttributes(config), + ...event, + 'event.name': EVENT_EXTENSION_UPDATE, + 'event.timestamp': new Date().toISOString(), + extension_name: event.extension_name, + extension_id: event.extension_id, + extension_previous_version: event.extension_previous_version, + extension_version: event.extension_version, + extension_source: event.extension_source, + }; + + const logger = logs.getLogger(SERVICE_NAME); + const logRecord: LogRecord = { + body: `Updated extension ${event.extension_name} from ${event.extension_previous_version} to ${event.extension_version}`, + attributes, + }; + logger.emit(logRecord); +} + export function logExtensionEnable( config: Config, event: ExtensionEnableEvent, diff --git a/packages/core/src/telemetry/qwen-logger/qwen-logger.ts b/packages/core/src/telemetry/qwen-logger/qwen-logger.ts index e63511df80f..af6e1e1786d 100644 --- a/packages/core/src/telemetry/qwen-logger/qwen-logger.ts +++ b/packages/core/src/telemetry/qwen-logger/qwen-logger.ts @@ -41,6 +41,7 @@ import type { SkillLaunchEvent, RipgrepFallbackEvent, EndSessionEvent, + ExtensionUpdateEvent, } from '../types.js'; import type { RumEvent, @@ -739,6 +740,22 @@ export class QwenLogger { this.flushIfNeeded(); } + logExtensionUpdateEvent(event: ExtensionUpdateEvent): void { + const rumEvent = this.createActionEvent('extension', 'extension_update', { + properties: { + extension_name: event.extension_name, + status: event.status, + extension_id: event.extension_id, + extension_previous_version: event.extension_previous_version, + extension_version: event.extension_version, + extension_source: event.extension_source, + }, + }); + + this.enqueueLogEvent(rumEvent); + this.flushIfNeeded(); + } + logExtensionEnableEvent(event: ExtensionEnableEvent): void { const rumEvent = this.createActionEvent('extension', 'extension_enable', { properties: { diff --git a/packages/core/src/telemetry/types.ts b/packages/core/src/telemetry/types.ts index 4158c9053d4..ad19f763efc 100644 --- a/packages/core/src/telemetry/types.ts +++ b/packages/core/src/telemetry/types.ts @@ -666,6 +666,35 @@ export class ExtensionUninstallEvent implements BaseTelemetryEvent { } } +export class ExtensionUpdateEvent implements BaseTelemetryEvent { + 'event.name': 'extension_update'; + 'event.timestamp': string; + extension_name: string; + extension_id: string; + extension_previous_version: string; + extension_version: string; + extension_source: string; + status: 'success' | 'error'; + + constructor( + extension_name: string, + extension_id: string, + extension_version: string, + extension_previous_version: string, + extension_source: string, + status: 'success' | 'error', + ) { + this['event.name'] = 'extension_update'; + this['event.timestamp'] = new Date().toISOString(); + this.extension_name = extension_name; + this.extension_id = extension_id; + this.extension_version = extension_version; + this.extension_previous_version = extension_previous_version; + this.extension_source = extension_source; + this.status = status; + } +} + export class ExtensionEnableEvent implements BaseTelemetryEvent { 'event.name': 'extension_enable'; 'event.timestamp': string; diff --git a/packages/core/src/utils/envVarResolver.test.ts b/packages/core/src/utils/envVarResolver.test.ts new file mode 100644 index 00000000000..a45b65b1b98 --- /dev/null +++ b/packages/core/src/utils/envVarResolver.test.ts @@ -0,0 +1,297 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { + resolveEnvVarsInString, + resolveEnvVarsInObject, +} from './envVarResolver.js'; + +describe('resolveEnvVarsInString', () => { + let originalEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + originalEnv = { ...process.env }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it('should resolve $VAR_NAME format', () => { + process.env['TEST_VAR'] = 'test-value'; + + const result = resolveEnvVarsInString('Value is $TEST_VAR'); + + expect(result).toBe('Value is test-value'); + }); + + it('should resolve ${VAR_NAME} format', () => { + process.env['TEST_VAR'] = 'test-value'; + + const result = resolveEnvVarsInString('Value is ${TEST_VAR}'); + + expect(result).toBe('Value is test-value'); + }); + + it('should resolve multiple variables in the same string', () => { + process.env['HOST'] = 'localhost'; + process.env['PORT'] = '3000'; + + const result = resolveEnvVarsInString('URL: http://$HOST:${PORT}/api'); + + expect(result).toBe('URL: http://localhost:3000/api'); + }); + + it('should leave undefined variables unchanged', () => { + const result = resolveEnvVarsInString('Value is $UNDEFINED_VAR'); + + expect(result).toBe('Value is $UNDEFINED_VAR'); + }); + + it('should leave undefined variables with braces unchanged', () => { + const result = resolveEnvVarsInString('Value is ${UNDEFINED_VAR}'); + + expect(result).toBe('Value is ${UNDEFINED_VAR}'); + }); + + it('should handle empty string', () => { + const result = resolveEnvVarsInString(''); + + expect(result).toBe(''); + }); + + it('should handle string without variables', () => { + const result = resolveEnvVarsInString('No variables here'); + + expect(result).toBe('No variables here'); + }); + + it('should handle mixed defined and undefined variables', () => { + process.env['DEFINED'] = 'value'; + + const result = resolveEnvVarsInString('$DEFINED and $UNDEFINED mixed'); + + expect(result).toBe('value and $UNDEFINED mixed'); + }); +}); + +describe('resolveEnvVarsInObject', () => { + let originalEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + originalEnv = { ...process.env }; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it('should resolve variables in nested objects', () => { + process.env['API_KEY'] = 'secret-123'; + process.env['DB_URL'] = 'postgresql://localhost/test'; + + const config = { + server: { + auth: { + key: '$API_KEY', + }, + database: '${DB_URL}', + }, + port: 3000, + }; + + const result = resolveEnvVarsInObject(config); + + expect(result).toEqual({ + server: { + auth: { + key: 'secret-123', + }, + database: 'postgresql://localhost/test', + }, + port: 3000, + }); + }); + + it('should resolve variables in arrays', () => { + process.env['ENV'] = 'production'; + process.env['VERSION'] = '1.0.0'; + + const config = { + tags: ['$ENV', 'app', '${VERSION}'], + metadata: { + env: '$ENV', + }, + }; + + const result = resolveEnvVarsInObject(config); + + expect(result).toEqual({ + tags: ['production', 'app', '1.0.0'], + metadata: { + env: 'production', + }, + }); + }); + + it('should preserve non-string types', () => { + const config = { + enabled: true, + count: 42, + value: null, + data: undefined, + tags: ['item1', 'item2'], + }; + + const result = resolveEnvVarsInObject(config); + + expect(result).toEqual(config); + }); + + it('should handle MCP server config structure', () => { + process.env['API_TOKEN'] = 'token-123'; + process.env['SERVER_PORT'] = '8080'; + + const extensionConfig = { + name: 'test-extension', + version: '1.0.0', + mcpServers: { + 'test-server': { + command: 'node', + args: ['server.js', '--port', '${SERVER_PORT}'], + env: { + API_KEY: '$API_TOKEN', + STATIC_VALUE: 'unchanged', + }, + timeout: 5000, + }, + }, + }; + + const result = resolveEnvVarsInObject(extensionConfig); + + expect(result).toEqual({ + name: 'test-extension', + version: '1.0.0', + mcpServers: { + 'test-server': { + command: 'node', + args: ['server.js', '--port', '8080'], + env: { + API_KEY: 'token-123', + STATIC_VALUE: 'unchanged', + }, + timeout: 5000, + }, + }, + }); + }); + + it('should handle empty and null values', () => { + const config = { + empty: '', + nullValue: null, + undefinedValue: undefined, + zero: 0, + false: false, + }; + + const result = resolveEnvVarsInObject(config); + + expect(result).toEqual(config); + }); + + it('should handle circular references in objects without infinite recursion', () => { + process.env['TEST_VAR'] = 'resolved-value'; + + type ConfigWithCircularRef = { + name: string; + value: number; + self?: ConfigWithCircularRef; + }; + + const config: ConfigWithCircularRef = { + name: '$TEST_VAR', + value: 42, + }; + // Create circular reference + config.self = config; + + const result = resolveEnvVarsInObject(config); + + expect(result.name).toBe('resolved-value'); + expect(result.value).toBe(42); + expect(result.self).toBeDefined(); + expect(result.self?.name).toBe('$TEST_VAR'); // Circular reference should be shallow copied + expect(result.self?.value).toBe(42); + // Verify it doesn't create infinite recursion by checking it's not the same object + expect(result.self).not.toBe(result); + }); + + it('should handle circular references in arrays without infinite recursion', () => { + process.env['ARRAY_VAR'] = 'array-value'; + + type ArrayWithCircularRef = Array; + const arr: ArrayWithCircularRef = ['$ARRAY_VAR', 123]; + // Create circular reference + arr.push(arr); + + const result = resolveEnvVarsInObject(arr) as ArrayWithCircularRef; + + expect(result[0]).toBe('array-value'); + expect(result[1]).toBe(123); + expect(Array.isArray(result[2])).toBe(true); + const subArray = result[2] as ArrayWithCircularRef; + expect(subArray[0]).toBe('$ARRAY_VAR'); // Circular reference should be shallow copied + expect(subArray[1]).toBe(123); + // Verify it doesn't create infinite recursion + expect(result[2]).not.toBe(result); + }); + + it('should handle complex nested circular references', () => { + process.env['NESTED_VAR'] = 'nested-resolved'; + + type ObjWithRef = { + name: string; + id: number; + ref?: ObjWithRef; + }; + + const obj1: ObjWithRef = { name: '$NESTED_VAR', id: 1 }; + const obj2: ObjWithRef = { name: 'static', id: 2 }; + + // Create cross-references + obj1.ref = obj2; + obj2.ref = obj1; + + const config = { + primary: obj1, + secondary: obj2, + value: '$NESTED_VAR', + }; + + const result = resolveEnvVarsInObject(config); + + expect(result.value).toBe('nested-resolved'); + expect(result.primary.name).toBe('nested-resolved'); + expect(result.primary.id).toBe(1); + expect(result.secondary.name).toBe('static'); + expect(result.secondary.id).toBe(2); + + // Check that circular references are handled (shallow copied) + expect(result.primary.ref).toBeDefined(); + expect(result.secondary.ref).toBeDefined(); + expect(result.primary.ref?.name).toBe('static'); // Should be shallow copy + expect(result.secondary.ref?.name).toBe('nested-resolved'); // The shallow copy still gets processed + + // Most importantly: verify no infinite recursion by checking objects are different + expect(result.primary.ref).not.toBe(result.secondary); + expect(result.secondary.ref).not.toBe(result.primary); + expect(result.primary).not.toBe(obj1); // New object created + expect(result.secondary).not.toBe(obj2); // New object created + }); +}); diff --git a/packages/core/src/utils/envVarResolver.ts b/packages/core/src/utils/envVarResolver.ts new file mode 100644 index 00000000000..096b5549ec0 --- /dev/null +++ b/packages/core/src/utils/envVarResolver.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Resolves environment variables in a string. + * Replaces $VAR_NAME and ${VAR_NAME} with their corresponding environment variable values. + * If the environment variable is not defined, the original placeholder is preserved. + * + * @param value - The string that may contain environment variable placeholders + * @returns The string with environment variables resolved + * + * @example + * resolveEnvVarsInString("Token: $API_KEY") // Returns "Token: secret-123" + * resolveEnvVarsInString("URL: ${BASE_URL}/api") // Returns "URL: https://api.example.com/api" + * resolveEnvVarsInString("Missing: $UNDEFINED_VAR") // Returns "Missing: $UNDEFINED_VAR" + */ +export function resolveEnvVarsInString( + value: string, + customEnv?: Record, +): string { + const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g; // Find $VAR_NAME or ${VAR_NAME} + return value.replace(envVarRegex, (match, varName1, varName2) => { + const varName = varName1 || varName2; + if (customEnv && typeof customEnv[varName] === 'string') { + return customEnv[varName]; + } + if (process && process.env && typeof process.env[varName] === 'string') { + return process.env[varName]!; + } + return match; + }); +} + +/** + * Recursively resolves environment variables in an object of any type. + * Handles strings, arrays, nested objects, and preserves other primitive types. + * Protected against circular references using a WeakSet to track visited objects. + * + * @param obj - The object to process for environment variable resolution + * @returns A new object with environment variables resolved + * + * @example + * const config = { + * server: { + * host: "$HOST", + * port: "${PORT}", + * enabled: true, + * tags: ["$ENV", "api"] + * } + * }; + * const resolved = resolveEnvVarsInObject(config); + */ +export function resolveEnvVarsInObject( + obj: T, + customEnv?: Record, +): T { + return resolveEnvVarsInObjectInternal(obj, new WeakSet(), customEnv); +} + +/** + * Internal implementation of resolveEnvVarsInObject with circular reference protection. + * + * @param obj - The object to process + * @param visited - WeakSet to track visited objects and prevent circular references + * @returns A new object with environment variables resolved + */ +function resolveEnvVarsInObjectInternal( + obj: T, + visited: WeakSet, + customEnv?: Record, +): T { + if ( + obj === null || + obj === undefined || + typeof obj === 'boolean' || + typeof obj === 'number' + ) { + return obj; + } + + if (typeof obj === 'string') { + return resolveEnvVarsInString(obj, customEnv) as unknown as T; + } + + if (Array.isArray(obj)) { + // Check for circular reference + if (visited.has(obj)) { + // Return a shallow copy to break the cycle + return [...obj] as unknown as T; + } + + visited.add(obj); + const result = obj.map((item) => + resolveEnvVarsInObjectInternal(item, visited, customEnv), + ) as unknown as T; + visited.delete(obj); + return result; + } + + if (typeof obj === 'object') { + // Check for circular reference + if (visited.has(obj as object)) { + // Return a shallow copy to break the cycle + return { ...obj } as T; + } + + visited.add(obj as object); + const newObj = { ...obj } as T; + for (const key in newObj) { + if (Object.prototype.hasOwnProperty.call(newObj, key)) { + newObj[key] = resolveEnvVarsInObjectInternal( + newObj[key], + visited, + customEnv, + ); + } + } + visited.delete(obj as object); + return newObj; + } + + return obj; +} diff --git a/packages/cli/src/services/toml-to-markdown-converter.test.ts b/packages/core/src/utils/toml-to-markdown-converter.test.ts similarity index 100% rename from packages/cli/src/services/toml-to-markdown-converter.test.ts rename to packages/core/src/utils/toml-to-markdown-converter.test.ts diff --git a/packages/cli/src/services/toml-to-markdown-converter.ts b/packages/core/src/utils/toml-to-markdown-converter.ts similarity index 100% rename from packages/cli/src/services/toml-to-markdown-converter.ts rename to packages/core/src/utils/toml-to-markdown-converter.ts From 70991e474fc5f9783e939974f3edc92db3ddf659 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 14 Jan 2026 15:42:50 +0800 Subject: [PATCH 06/30] fix/lint error --- .../cli/src/services/FileCommandLoader.ts | 3 +- .../cli/src/ui/components/DialogManager.tsx | 10 -- .../components/WorkspaceMigrationDialog.tsx | 119 ------------------ .../core/src/extension/extensionManager.ts | 2 - packages/core/src/extension/index.ts | 3 + packages/core/src/index.ts | 2 +- 6 files changed, 5 insertions(+), 134 deletions(-) delete mode 100644 packages/cli/src/ui/components/WorkspaceMigrationDialog.tsx create mode 100644 packages/core/src/extension/index.ts diff --git a/packages/cli/src/services/FileCommandLoader.ts b/packages/cli/src/services/FileCommandLoader.ts index 8095a72e306..ef81f9e695b 100644 --- a/packages/cli/src/services/FileCommandLoader.ts +++ b/packages/cli/src/services/FileCommandLoader.ts @@ -11,7 +11,7 @@ import toml from '@iarna/toml'; import { glob } from 'glob'; import { z } from 'zod'; import type { Config } from '@qwen-code/qwen-code-core'; -import { Storage } from '@qwen-code/qwen-code-core'; +import { EXTENSIONS_CONFIG_FILENAME, Storage } from '@qwen-code/qwen-code-core'; import type { ICommandLoader } from './types.js'; import { parseMarkdownCommand, @@ -22,7 +22,6 @@ import { type CommandDefinition, } from './command-factory.js'; import type { SlashCommand } from '../ui/commands/types.js'; -import { EXTENSIONS_CONFIG_FILENAME } from '../config/extensions/variables.js'; interface CommandDirectory { path: string; diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index a87192ab2a3..694c77d6469 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -17,7 +17,6 @@ import { QwenOAuthProgress } from './QwenOAuthProgress.js'; import { AuthDialog } from '../auth/AuthDialog.js'; import { OpenAIKeyPrompt } from './OpenAIKeyPrompt.js'; import { EditorSettingsDialog } from './EditorSettingsDialog.js'; -import { WorkspaceMigrationDialog } from './WorkspaceMigrationDialog.js'; import { PermissionsModifyTrustDialog } from './PermissionsModifyTrustDialog.js'; import { ModelDialog } from './ModelDialog.js'; import { ApprovalModeDialog } from './ApprovalModeDialog.js'; @@ -78,15 +77,6 @@ export const DialogManager = ({ if (uiState.showIdeRestartPrompt) { return ; } - if (uiState.showWorkspaceMigrationDialog) { - return ( - - ); - } if (uiState.shouldShowIdePrompt) { return ( void; - onClose: () => void; -}) { - const { workspaceExtensions, onOpen, onClose } = props; - const [migrationComplete, setMigrationComplete] = useState(false); - const [failedExtensions, setFailedExtensions] = useState([]); - onOpen(); - const onMigrate = async () => { - const failed = await performWorkspaceExtensionMigration( - workspaceExtensions, - // We aren't updating extensions, just moving them around, don't need to ask for consent. - async (_) => true, - ); - setFailedExtensions(failed); - setMigrationComplete(true); - }; - - useKeypress( - (key) => { - if (migrationComplete && key.sequence === 'q') { - process.exit(0); - } - }, - { isActive: true }, - ); - - if (migrationComplete) { - return ( - - {failedExtensions.length > 0 ? ( - <> - - The following extensions failed to migrate. Please try installing - them manually. To see other changes, Qwen Code must be restarted. - Press 'q' to quit. - - - {failedExtensions.map((failed) => ( - - {failed} - ))} - - - ) : ( - - Migration complete. To see changes, Qwen Code must be restarted. - Press 'q' to quit. - - )} - - ); - } - - return ( - - - Workspace-level extensions are deprecated{'\n'} - - - Would you like to install them at the user level? - - - The extension definition will remain in your workspace directory. - - - If you opt to skip, you can install them manually using the extensions - install command. - - - - {workspaceExtensions.map((extension) => ( - - {extension.config.name} - ))} - - - { - if (value === 'migrate') { - onMigrate(); - } else { - onClose(); - } - }} - /> - - - ); -} diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 5b2922e5bdc..1fab09498e2 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -1334,5 +1334,3 @@ export async function parseInstallSource( } return installMetadata; } - -export { checkForExtensionUpdate }; diff --git a/packages/core/src/extension/index.ts b/packages/core/src/extension/index.ts new file mode 100644 index 00000000000..dd4b413fb53 --- /dev/null +++ b/packages/core/src/extension/index.ts @@ -0,0 +1,3 @@ +export * from './extensionManager.js'; +export * from './variables.js'; +export * from './github.js'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8d93c35ce71..fb14dc61065 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -84,7 +84,7 @@ export * from './subagents/index.js'; export * from './skills/index.js'; // Export extension -export * from './extension/extensionManager.js'; +export * from './extension/index.js'; // Export prompt logic export * from './prompts/mcp-prompts.js'; From 0a88dd78616fa142cb962e842c389ed1cd3e0cf9 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 14 Jan 2026 16:50:59 +0800 Subject: [PATCH 07/30] fix: fix tests --- .../FileCommandLoader-extension.test.ts | 35 +- .../src/services/command-migration-tool.ts | 2 +- .../src/services/markdown-command-parser.ts | 2 +- .../cli/src/test-utils/createExtension.ts | 49 - .../components/views/ExtensionsList.test.tsx | 12 +- .../src/ui/hooks/useExtensionUpdates.test.ts | 305 ++-- .../core/src/extension/claude-converter.ts | 2 +- .../src/extension/extensionManager.test.ts | 1436 ++++------------- .../src/extension/extensionSettings.test.ts | 21 +- packages/core/src/extension/github.test.ts | 83 +- packages/core/src/extension/github.ts | 2 +- packages/core/src/extension/marketplace.ts | 2 +- packages/core/src/extension/storage.test.ts | 2 +- packages/core/src/extension/storage.ts | 2 +- packages/core/src/extension/variables.ts | 2 +- packages/core/src/index.ts | 2 + 16 files changed, 522 insertions(+), 1437 deletions(-) delete mode 100644 packages/cli/src/test-utils/createExtension.ts diff --git a/packages/cli/src/services/FileCommandLoader-extension.test.ts b/packages/cli/src/services/FileCommandLoader-extension.test.ts index c579bf20a37..38af0865d5f 100644 --- a/packages/cli/src/services/FileCommandLoader-extension.test.ts +++ b/packages/cli/src/services/FileCommandLoader-extension.test.ts @@ -62,10 +62,13 @@ describe('FileCommandLoader - Extension Commands Support', () => { // Mock config to return the extension mockConfig.getExtensions = () => [ { + id: 'test-ext', + config: extensionConfig, name: 'test-ext', version: '1.0.0', isActive: true, path: extensionDir, + contextFiles: [], }, ]; @@ -111,6 +114,9 @@ describe('FileCommandLoader - Extension Commands Support', () => { // Mock config to return the extension mockConfig.getExtensions = () => [ { + id: 'multi-ext', + config: extensionConfig, + contextFiles: [], name: 'multi-ext', version: '1.0.0', isActive: true, @@ -156,6 +162,9 @@ describe('FileCommandLoader - Extension Commands Support', () => { // Mock config to return the extension mockConfig.getExtensions = () => [ { + id: 'default-ext', + config: extensionConfig, + contextFiles: [], name: 'default-ext', version: '1.0.0', isActive: true, @@ -193,6 +202,9 @@ describe('FileCommandLoader - Extension Commands Support', () => { // Mock config to return the extension mockConfig.getExtensions = () => [ { + id: 'no-cmds-ext', + config: extensionConfig, + contextFiles: [], name: 'no-cmds-ext', version: '1.0.0', isActive: true, @@ -234,6 +246,9 @@ describe('FileCommandLoader - Extension Commands Support', () => { mockConfig.getExtensions = () => [ { + id: 'prefix-ext', + config: extensionConfig, + contextFiles: [], name: 'prefix-ext', version: '1.0.0', isActive: true, @@ -281,8 +296,24 @@ describe('FileCommandLoader - Extension Commands Support', () => { ); mockConfig.getExtensions = () => [ - { name: 'ext-b', version: '1.0.0', isActive: true, path: ext1Dir }, - { name: 'ext-a', version: '1.0.0', isActive: true, path: ext2Dir }, + { + id: 'ext-b', + config: { name: 'ext-b', version: '1.0.0' }, + contextFiles: [], + name: 'ext-b', + version: '1.0.0', + isActive: true, + path: ext1Dir, + }, + { + id: 'ext-a', + config: { name: 'ext-a', version: '1.0.0' }, + contextFiles: [], + name: 'ext-a', + version: '1.0.0', + isActive: true, + path: ext2Dir, + }, ]; const loader = new FileCommandLoader(mockConfig as Config); diff --git a/packages/cli/src/services/command-migration-tool.ts b/packages/cli/src/services/command-migration-tool.ts index 670632522c3..e8f32b61361 100644 --- a/packages/cli/src/services/command-migration-tool.ts +++ b/packages/cli/src/services/command-migration-tool.ts @@ -11,7 +11,7 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; import { glob } from 'glob'; -import { convertTomlToMarkdown } from '@qwen-code/qwen-code-core/src/utils/toml-to-markdown-converter.js'; +import { convertTomlToMarkdown } from '@qwen-code/qwen-code-core'; export interface MigrationResult { success: boolean; diff --git a/packages/cli/src/services/markdown-command-parser.ts b/packages/cli/src/services/markdown-command-parser.ts index 92e0d9573af..5b6ed38bf2f 100644 --- a/packages/cli/src/services/markdown-command-parser.ts +++ b/packages/cli/src/services/markdown-command-parser.ts @@ -5,7 +5,7 @@ */ import { z } from 'zod'; -import { parse as parseYaml } from '@qwen-code/qwen-code-core/src/utils/yaml-parser.js'; +import { parse as parseYaml } from '@qwen-code/qwen-code-core'; /** * Defines the Zod schema for a Markdown command definition file. diff --git a/packages/cli/src/test-utils/createExtension.ts b/packages/cli/src/test-utils/createExtension.ts deleted file mode 100644 index 7366c3cf665..00000000000 --- a/packages/cli/src/test-utils/createExtension.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { - type MCPServerConfig, - type ExtensionInstallMetadata, -} from '@qwen-code/qwen-code-core'; -import { - EXTENSIONS_CONFIG_FILENAME, - INSTALL_METADATA_FILENAME, -} from '../config/extensions/variables.js'; - -export function createExtension({ - extensionsDir = 'extensions-dir', - name = 'my-extension', - version = '1.0.0', - addContextFile = false, - contextFileName = undefined as string | undefined, - mcpServers = {} as Record, - installMetadata = undefined as ExtensionInstallMetadata | undefined, -} = {}): string { - const extDir = path.join(extensionsDir, name); - fs.mkdirSync(extDir, { recursive: true }); - fs.writeFileSync( - path.join(extDir, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify({ name, version, contextFileName, mcpServers }), - ); - - if (addContextFile) { - fs.writeFileSync(path.join(extDir, 'QWEN.md'), 'context'); - } - - if (contextFileName) { - fs.writeFileSync(path.join(extDir, contextFileName), 'context'); - } - - if (installMetadata) { - fs.writeFileSync( - path.join(extDir, INSTALL_METADATA_FILENAME), - JSON.stringify(installMetadata), - ); - } - return extDir; -} diff --git a/packages/cli/src/ui/components/views/ExtensionsList.test.tsx b/packages/cli/src/ui/components/views/ExtensionsList.test.tsx index 9067e34738b..fe67396ad4a 100644 --- a/packages/cli/src/ui/components/views/ExtensionsList.test.tsx +++ b/packages/cli/src/ui/components/views/ExtensionsList.test.tsx @@ -18,7 +18,6 @@ const mockUseUIState = vi.mocked(useUIState); const mockExtensions = [ { name: 'ext-one', version: '1.0.0', isActive: true }, { name: 'ext-two', version: '2.1.0', isActive: true }, - { name: 'ext-disabled', version: '3.0.0', isActive: false }, ]; describe('', () => { @@ -29,7 +28,6 @@ describe('', () => { const mockUIState = ( extensions: unknown[], extensionsUpdateState: Map, - disabledExtensions: string[] = [], ) => { mockUseUIState.mockReturnValue({ commandContext: createMockCommandContext({ @@ -37,13 +35,6 @@ describe('', () => { config: { getExtensions: () => extensions, }, - settings: { - merged: { - extensions: { - disabled: disabledExtensions, - }, - }, - }, }, }), extensionsUpdateState, @@ -58,12 +49,11 @@ describe('', () => { }); it('should render a list of extensions with their version and status', () => { - mockUIState(mockExtensions, new Map(), ['ext-disabled']); + mockUIState(mockExtensions, new Map()); const { lastFrame } = render(); const output = lastFrame(); expect(output).toContain('ext-one (v1.0.0) - active'); expect(output).toContain('ext-two (v2.1.0) - active'); - expect(output).toContain('ext-disabled (v3.0.0) - disabled'); }); it('should display "unknown state" if an extension has no update state', () => { diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts index 3f21c019c5d..0475b0badb9 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts @@ -4,27 +4,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { vi } from 'vitest'; +import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { - annotateActiveExtensions, - loadExtension, - ExtensionManager, -} from '../../config/extension.js'; -import { createExtension } from '../../test-utils/createExtension.js'; + import { useExtensionUpdates } from './useExtensionUpdates.js'; -import { QWEN_DIR, type GeminiCLIExtension } from '@qwen-code/qwen-code-core'; +import { + QWEN_DIR, + type ExtensionManager, + type Extension, + type ExtensionUpdateInfo, + ExtensionUpdateState, +} from '@qwen-code/qwen-code-core'; import { renderHook, waitFor } from '@testing-library/react'; import { MessageType } from '../types.js'; -import { - checkForAllExtensionUpdates, - updateExtension, -} from '../../config/extensions/update.js'; -import { ExtensionUpdateState } from '../state/extensions.js'; - vi.mock('os', async (importOriginal) => { const mockedOs = await importOriginal(); return { @@ -33,63 +28,85 @@ vi.mock('os', async (importOriginal) => { }; }); -vi.mock('../../config/extensions/update.js', () => ({ - checkForAllExtensionUpdates: vi.fn(), - updateExtension: vi.fn(), -})); +function createMockExtension(overrides: Partial = {}): Extension { + return { + id: 'test-extension-id', + name: 'test-extension', + version: '1.0.0', + path: '/some/path', + isActive: true, + config: { + name: 'test-extension', + version: '1.0.0', + }, + contextFiles: [], + installMetadata: { + type: 'git', + source: 'https://some/repo', + autoUpdate: false, + }, + ...overrides, + }; +} + +function createMockExtensionManager( + extensions: Extension[], + checkCallback?: ( + callback: (extensionName: string, state: ExtensionUpdateState) => void, + ) => Promise, + updateResult?: ExtensionUpdateInfo | undefined, +): ExtensionManager { + return { + getLoadedExtensions: vi.fn(() => extensions), + checkForAllExtensionUpdates: vi.fn( + async ( + callback: (extensionName: string, state: ExtensionUpdateState) => void, + ) => { + if (checkCallback) { + await checkCallback(callback); + } + }, + ), + updateExtension: vi.fn(async () => updateResult), + } as unknown as ExtensionManager; +} describe('useExtensionUpdates', () => { let tempHomeDir: string; let userExtensionsDir: string; beforeEach(() => { - tempHomeDir = fs.mkdtempSync( - path.join(os.tmpdir(), 'gemini-cli-test-home-'), - ); + tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'qwen-cli-test-home-')); vi.mocked(os.homedir).mockReturnValue(tempHomeDir); userExtensionsDir = path.join(tempHomeDir, QWEN_DIR, 'extensions'); fs.mkdirSync(userExtensionsDir, { recursive: true }); - vi.mocked(checkForAllExtensionUpdates).mockReset(); - vi.mocked(updateExtension).mockReset(); }); afterEach(() => { fs.rmSync(tempHomeDir, { recursive: true, force: true }); + vi.clearAllMocks(); }); it('should check for updates and log a message if an update is available', async () => { - const extensions = [ - { - name: 'test-extension', + const extension = createMockExtension({ + name: 'test-extension', + installMetadata: { type: 'git', - version: '1.0.0', - path: '/some/path', - isActive: true, - installMetadata: { - type: 'git', - source: 'https://some/repo', - autoUpdate: false, - }, + source: 'https://some/repo', + autoUpdate: false, }, - ]; + }); const addItem = vi.fn(); const cwd = '/test/cwd'; - vi.mocked(checkForAllExtensionUpdates).mockImplementation( - async (extensions, dispatch) => { - dispatch({ - type: 'SET_STATE', - payload: { - name: 'test-extension', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); + const extensionManager = createMockExtensionManager( + [extension], + async (callback) => { + callback('test-extension', ExtensionUpdateState.UPDATE_AVAILABLE); }, ); - renderHook(() => - useExtensionUpdates(extensions as GeminiCLIExtension[], addItem, cwd), - ); + renderHook(() => useExtensionUpdates(extensionManager, addItem, cwd)); await waitFor(() => { expect(addItem).toHaveBeenCalledWith( @@ -103,43 +120,32 @@ describe('useExtensionUpdates', () => { }); it('should check for updates and automatically update if autoUpdate is true', async () => { - const extensionDir = createExtension({ - extensionsDir: userExtensionsDir, + const extension = createMockExtension({ name: 'test-extension', - version: '1.0.0', installMetadata: { - source: 'https://some.git/repo', type: 'git', + source: 'https://some.git/repo', autoUpdate: true, }, }); - const extension = annotateActiveExtensions( - [loadExtension({ extensionDir, workspaceDir: tempHomeDir })!], - tempHomeDir, - new ExtensionManager(), - )[0]; const addItem = vi.fn(); - vi.mocked(checkForAllExtensionUpdates).mockImplementation( - async (extensions, dispatch) => { - dispatch({ - type: 'SET_STATE', - payload: { - name: 'test-extension', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); + const extensionManager = createMockExtensionManager( + [extension], + async (callback) => { + callback('test-extension', ExtensionUpdateState.UPDATE_AVAILABLE); + }, + { + originalVersion: '1.0.0', + updatedVersion: '1.1.0', + name: 'test-extension', }, ); - vi.mocked(updateExtension).mockResolvedValue({ - originalVersion: '1.0.0', - updatedVersion: '1.1.0', - name: '', - }); - - renderHook(() => useExtensionUpdates([extension], addItem, tempHomeDir)); + renderHook(() => + useExtensionUpdates(extensionManager, addItem, tempHomeDir), + ); await waitFor( () => { @@ -156,76 +162,63 @@ describe('useExtensionUpdates', () => { }); it('should batch update notifications for multiple extensions', async () => { - const extensionDir1 = createExtension({ - extensionsDir: userExtensionsDir, + const extension1 = createMockExtension({ + id: 'test-extension-1-id', name: 'test-extension-1', version: '1.0.0', installMetadata: { - source: 'https://some.git/repo1', type: 'git', + source: 'https://some.git/repo1', autoUpdate: true, }, }); - const extensionDir2 = createExtension({ - extensionsDir: userExtensionsDir, + const extension2 = createMockExtension({ + id: 'test-extension-2-id', name: 'test-extension-2', version: '2.0.0', installMetadata: { - source: 'https://some.git/repo2', type: 'git', + source: 'https://some.git/repo2', autoUpdate: true, }, }); - const extensions = annotateActiveExtensions( - [ - loadExtension({ - extensionDir: extensionDir1, - workspaceDir: tempHomeDir, - })!, - loadExtension({ - extensionDir: extensionDir2, - workspaceDir: tempHomeDir, - })!, - ], - tempHomeDir, - new ExtensionManager(), - ); - const addItem = vi.fn(); + let updateCallCount = 0; - vi.mocked(checkForAllExtensionUpdates).mockImplementation( - async (extensions, dispatch) => { - dispatch({ - type: 'SET_STATE', - payload: { + const extensionManager = { + getLoadedExtensions: vi.fn(() => [extension1, extension2]), + checkForAllExtensionUpdates: vi.fn( + async ( + callback: ( + extensionName: string, + state: ExtensionUpdateState, + ) => void, + ) => { + callback('test-extension-1', ExtensionUpdateState.UPDATE_AVAILABLE); + callback('test-extension-2', ExtensionUpdateState.UPDATE_AVAILABLE); + }, + ), + updateExtension: vi.fn(async () => { + updateCallCount++; + if (updateCallCount === 1) { + return { + originalVersion: '1.0.0', + updatedVersion: '1.1.0', name: 'test-extension-1', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); - dispatch({ - type: 'SET_STATE', - payload: { - name: 'test-extension-2', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); - }, - ); - - vi.mocked(updateExtension) - .mockResolvedValueOnce({ - originalVersion: '1.0.0', - updatedVersion: '1.1.0', - name: '', - }) - .mockResolvedValueOnce({ - originalVersion: '2.0.0', - updatedVersion: '2.1.0', - name: '', - }); + }; + } + return { + originalVersion: '2.0.0', + updatedVersion: '2.1.0', + name: 'test-extension-2', + }; + }), + } as unknown as ExtensionManager; - renderHook(() => useExtensionUpdates(extensions, addItem, tempHomeDir)); + renderHook(() => + useExtensionUpdates(extensionManager, addItem, tempHomeDir), + ); await waitFor( () => { @@ -250,60 +243,40 @@ describe('useExtensionUpdates', () => { }); it('should batch update notifications for multiple extensions with autoUpdate: false', async () => { - const extensions = [ - { - name: 'test-extension-1', + const extension1 = createMockExtension({ + id: 'test-extension-1-id', + name: 'test-extension-1', + version: '1.0.0', + installMetadata: { type: 'git', - version: '1.0.0', - path: '/some/path1', - isActive: true, - installMetadata: { - type: 'git', - source: 'https://some/repo1', - autoUpdate: false, - }, + source: 'https://some/repo1', + autoUpdate: false, }, - { - name: 'test-extension-2', + }); + const extension2 = createMockExtension({ + id: 'test-extension-2-id', + name: 'test-extension-2', + version: '2.0.0', + installMetadata: { type: 'git', - version: '2.0.0', - path: '/some/path2', - isActive: true, - installMetadata: { - type: 'git', - source: 'https://some/repo2', - autoUpdate: false, - }, + source: 'https://some/repo2', + autoUpdate: false, }, - ]; + }); + const addItem = vi.fn(); const cwd = '/test/cwd'; - vi.mocked(checkForAllExtensionUpdates).mockImplementation( - async (extensions, dispatch) => { - dispatch({ type: 'BATCH_CHECK_START' }); - dispatch({ - type: 'SET_STATE', - payload: { - name: 'test-extension-1', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); + const extensionManager = createMockExtensionManager( + [extension1, extension2], + async (callback) => { + callback('test-extension-1', ExtensionUpdateState.UPDATE_AVAILABLE); await new Promise((r) => setTimeout(r, 50)); - dispatch({ - type: 'SET_STATE', - payload: { - name: 'test-extension-2', - state: ExtensionUpdateState.UPDATE_AVAILABLE, - }, - }); - dispatch({ type: 'BATCH_CHECK_END' }); + callback('test-extension-2', ExtensionUpdateState.UPDATE_AVAILABLE); }, ); - renderHook(() => - useExtensionUpdates(extensions as GeminiCLIExtension[], addItem, cwd), - ); + renderHook(() => useExtensionUpdates(extensionManager, addItem, cwd)); await waitFor(() => { expect(addItem).toHaveBeenCalledTimes(1); diff --git a/packages/core/src/extension/claude-converter.ts b/packages/core/src/extension/claude-converter.ts index 9e6cead541b..c5833286c5a 100644 --- a/packages/core/src/extension/claude-converter.ts +++ b/packages/core/src/extension/claude-converter.ts @@ -11,8 +11,8 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { glob } from 'glob'; import type { ExtensionConfig } from './extensionManager.js'; -import type { MCPServerConfig } from '@qwen-code/qwen-code-core'; import { ExtensionStorage } from './storage.js'; +import type { MCPServerConfig } from '../config/config.js'; export interface ClaudePluginConfig { name: string; diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index a3a85ee40e5..1bebae39d8b 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -4,40 +4,21 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { vi } from 'vitest'; +import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { - annotateActiveExtensions, - disableExtension, - enableExtension, - installExtension, - loadExtension, - loadExtensionConfig, - loadExtensions, - performWorkspaceExtensionMigration, - requestConsentNonInteractive, - uninstallExtension, - type Extension, -} from './extension.js'; import { INSTALL_METADATA_FILENAME, EXTENSIONS_CONFIG_FILENAME, -} from './extensions/variables.js'; -import { ExtensionStorage } from './extensions/storage.js'; +} from './variables.js'; +import { QWEN_DIR } from '../config/storage.js'; import { - QWEN_DIR, - type GeminiCLIExtension, - ExtensionUninstallEvent, - ExtensionDisableEvent, - ExtensionEnableEvent, -} from '@qwen-code/qwen-code-core'; -import { execSync } from 'node:child_process'; -import { SettingScope } from './settings.js'; -import { isWorkspaceTrusted } from './trustedFolders.js'; -import { createExtension } from '../test-utils/createExtension.js'; -import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; + ExtensionManager, + SettingScope, + type ExtensionManagerOptions, +} from './extensionManager.js'; +import type { MCPServerConfig, ExtensionInstallMetadata } from '../index.js'; const mockGit = { clone: vi.fn(), @@ -46,8 +27,6 @@ const mockGit = { checkout: vi.fn(), listRemote: vi.fn(), revparse: vi.fn(), - // Not a part of the actual API, but we need to use this to do the correct - // file system interactions. path: vi.fn(), }; @@ -58,9 +37,8 @@ vi.mock('simple-git', () => ({ }), })); -vi.mock('./extensions/github.js', async (importOriginal) => { - const actual = - await importOriginal(); +vi.mock('./github.js', async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, downloadFromGitHubRelease: vi @@ -69,19 +47,12 @@ vi.mock('./extensions/github.js', async (importOriginal) => { }; }); +const mockHomedir = vi.hoisted(() => vi.fn()); vi.mock('os', async (importOriginal) => { const mockedOs = await importOriginal(); return { ...mockedOs, - homedir: vi.fn(), - }; -}); - -vi.mock('./trustedFolders.js', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - isWorkspaceTrusted: vi.fn(), + homedir: mockHomedir, }; }); @@ -89,41 +60,58 @@ const mockLogExtensionEnable = vi.hoisted(() => vi.fn()); const mockLogExtensionInstallEvent = vi.hoisted(() => vi.fn()); const mockLogExtensionUninstall = vi.hoisted(() => vi.fn()); const mockLogExtensionDisable = vi.hoisted(() => vi.fn()); -vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { - const actual = - await importOriginal(); +const mockLogExtensionUpdateEvent = vi.hoisted(() => vi.fn()); +vi.mock('../telemetry/loggers.js', () => ({ + logExtensionEnable: mockLogExtensionEnable, + logExtensionUpdateEvent: mockLogExtensionUpdateEvent, +})); + +vi.mock('../index.js', async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, logExtensionEnable: mockLogExtensionEnable, logExtensionInstallEvent: mockLogExtensionInstallEvent, logExtensionUninstall: mockLogExtensionUninstall, logExtensionDisable: mockLogExtensionDisable, - ExtensionEnableEvent: vi.fn(), - ExtensionInstallEvent: vi.fn(), - ExtensionUninstallEvent: vi.fn(), - ExtensionDisableEvent: vi.fn(), }; }); -vi.mock('child_process', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - execSync: vi.fn(), - }; -}); - -const mockQuestion = vi.hoisted(() => vi.fn()); -const mockClose = vi.hoisted(() => vi.fn()); -vi.mock('node:readline', () => ({ - createInterface: vi.fn(() => ({ - question: mockQuestion, - close: mockClose, - })), -})); - const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); +function createExtension({ + extensionsDir = 'extensions-dir', + name = 'my-extension', + version = '1.0.0', + addContextFile = false, + contextFileName = undefined as string | undefined, + mcpServers = {} as Record, + installMetadata = undefined as ExtensionInstallMetadata | undefined, +} = {}): string { + const extDir = path.join(extensionsDir, name); + fs.mkdirSync(extDir, { recursive: true }); + fs.writeFileSync( + path.join(extDir, EXTENSIONS_CONFIG_FILENAME), + JSON.stringify({ name, version, contextFileName, mcpServers }), + ); + + if (addContextFile) { + fs.writeFileSync(path.join(extDir, 'QWEN.md'), 'context'); + } + + if (contextFileName) { + fs.writeFileSync(path.join(extDir, contextFileName), 'context'); + } + + if (installMetadata) { + fs.writeFileSync( + path.join(extDir, INSTALL_METADATA_FILENAME), + JSON.stringify(installMetadata), + ); + } + return extDir; +} + describe('extension tests', () => { let tempHomeDir: string; let tempWorkspaceDir: string; @@ -139,24 +127,28 @@ describe('extension tests', () => { userExtensionsDir = path.join(tempHomeDir, EXTENSIONS_DIRECTORY_NAME); fs.mkdirSync(userExtensionsDir, { recursive: true }); - vi.mocked(os.homedir).mockReturnValue(tempHomeDir); - vi.mocked(isWorkspaceTrusted).mockReturnValue(true); + mockHomedir.mockReturnValue(tempHomeDir); vi.spyOn(process, 'cwd').mockReturnValue(tempWorkspaceDir); - mockQuestion.mockImplementation((_query, callback) => callback('y')); - vi.mocked(execSync).mockClear(); Object.values(mockGit).forEach((fn) => fn.mockReset()); }); afterEach(() => { fs.rmSync(tempHomeDir, { recursive: true, force: true }); - fs.rmSync(tempWorkspaceDir, { recursive: true, force: true }); vi.restoreAllMocks(); - mockQuestion.mockClear(); - mockClose.mockClear(); }); - describe('loadExtensions', () => { - it('should include extension path in loaded extension', () => { + function createExtensionManager( + options: Partial = {}, + ): ExtensionManager { + return new ExtensionManager({ + workspaceDir: tempWorkspaceDir, + isWorkspaceTrusted: true, + ...options, + }); + } + + describe('loadExtension', () => { + it('should include extension path in loaded extension', async () => { const extensionDir = path.join(userExtensionsDir, 'test-extension'); fs.mkdirSync(extensionDir, { recursive: true }); @@ -166,15 +158,16 @@ describe('extension tests', () => { version: '1.0.0', }); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); + expect(extensions).toHaveLength(1); expect(extensions[0].path).toBe(extensionDir); expect(extensions[0].config.name).toBe('test-extension'); }); - it('should load context file path when QWEN.md is present', () => { + it('should load context file path when QWEN.md is present', async () => { createExtension({ extensionsDir: userExtensionsDir, name: 'ext1', @@ -187,9 +180,9 @@ describe('extension tests', () => { version: '2.0.0', }); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); expect(extensions).toHaveLength(2); const ext1 = extensions.find((e) => e.config.name === 'ext1'); @@ -200,7 +193,7 @@ describe('extension tests', () => { expect(ext2?.contextFiles).toEqual([]); }); - it('should load context file path from the extension config', () => { + it('should load context file path from the extension config', async () => { createExtension({ extensionsDir: userExtensionsDir, name: 'ext1', @@ -209,9 +202,9 @@ describe('extension tests', () => { contextFileName: 'my-context-file.md', }); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); expect(extensions).toHaveLength(1); const ext1 = extensions.find((e) => e.config.name === 'ext1'); @@ -220,199 +213,7 @@ describe('extension tests', () => { ]); }); - it('should filter out disabled extensions', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'disabled-extension', - version: '1.0.0', - }); - createExtension({ - extensionsDir: userExtensionsDir, - name: 'enabled-extension', - version: '2.0.0', - }); - disableExtension( - 'disabled-extension', - SettingScope.User, - tempWorkspaceDir, - ); - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ); - const extensions = loadExtensions(manager); - const activeExtensions = annotateActiveExtensions( - extensions, - tempWorkspaceDir, - manager, - ).filter((e) => e.isActive); - expect(activeExtensions).toHaveLength(1); - expect(activeExtensions[0].name).toBe('enabled-extension'); - }); - - it('should hydrate variables', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'test-extension', - version: '1.0.0', - addContextFile: false, - contextFileName: undefined, - mcpServers: { - 'test-server': { - cwd: '${extensionPath}${/}server', - }, - }, - }); - - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - expect(extensions).toHaveLength(1); - const loadedConfig = extensions[0].config; - const expectedCwd = path.join( - userExtensionsDir, - 'test-extension', - 'server', - ); - expect(loadedConfig.mcpServers?.['test-server'].cwd).toBe(expectedCwd); - }); - - it('should load a linked extension correctly', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempWorkspaceDir, - name: 'my-linked-extension', - version: '1.0.0', - contextFileName: 'context.md', - }); - fs.writeFileSync(path.join(sourceExtDir, 'context.md'), 'linked context'); - - const extensionName = await installExtension( - { - source: sourceExtDir, - type: 'link', - }, - async (_) => true, - ); - - expect(extensionName).toEqual('my-linked-extension'); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - expect(extensions).toHaveLength(1); - - const linkedExt = extensions[0]; - expect(linkedExt.config.name).toBe('my-linked-extension'); - - expect(linkedExt.path).toBe(sourceExtDir); - expect(linkedExt.installMetadata).toEqual({ - source: sourceExtDir, - type: 'link', - }); - expect(linkedExt.contextFiles).toEqual([ - path.join(sourceExtDir, 'context.md'), - ]); - }); - - it('should resolve environment variables in extension configuration', () => { - process.env.TEST_API_KEY = 'test-api-key-123'; - process.env.TEST_DB_URL = 'postgresql://localhost:5432/testdb'; - - try { - const userExtensionsDir = path.join( - tempHomeDir, - EXTENSIONS_DIRECTORY_NAME, - ); - fs.mkdirSync(userExtensionsDir, { recursive: true }); - - const extDir = path.join(userExtensionsDir, 'test-extension'); - fs.mkdirSync(extDir); - - // Write config to a separate file for clarity and good practices - const configPath = path.join(extDir, EXTENSIONS_CONFIG_FILENAME); - const extensionConfig = { - name: 'test-extension', - version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - env: { - API_KEY: '$TEST_API_KEY', - DATABASE_URL: '${TEST_DB_URL}', - STATIC_VALUE: 'no-substitution', - }, - }, - }, - }; - fs.writeFileSync(configPath, JSON.stringify(extensionConfig)); - - const extensions = loadExtensions( - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ); - - expect(extensions).toHaveLength(1); - const extension = extensions[0]; - expect(extension.config.name).toBe('test-extension'); - expect(extension.config.mcpServers).toBeDefined(); - - const serverConfig = extension.config.mcpServers?.['test-server']; - expect(serverConfig).toBeDefined(); - expect(serverConfig?.env).toBeDefined(); - expect(serverConfig?.env?.API_KEY).toBe('test-api-key-123'); - expect(serverConfig?.env?.DATABASE_URL).toBe( - 'postgresql://localhost:5432/testdb', - ); - expect(serverConfig?.env?.STATIC_VALUE).toBe('no-substitution'); - } finally { - delete process.env.TEST_API_KEY; - delete process.env.TEST_DB_URL; - } - }); - - it('should handle missing environment variables gracefully', () => { - const userExtensionsDir = path.join( - tempHomeDir, - EXTENSIONS_DIRECTORY_NAME, - ); - fs.mkdirSync(userExtensionsDir, { recursive: true }); - - const extDir = path.join(userExtensionsDir, 'test-extension'); - fs.mkdirSync(extDir); - - const extensionConfig = { - name: 'test-extension', - version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - env: { - MISSING_VAR: '$UNDEFINED_ENV_VAR', - MISSING_VAR_BRACES: '${ALSO_UNDEFINED}', - }, - }, - }, - }; - - fs.writeFileSync( - path.join(extDir, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify(extensionConfig), - ); - - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - - expect(extensions).toHaveLength(1); - const extension = extensions[0]; - const serverConfig = extension.config.mcpServers!['test-server']; - expect(serverConfig.env).toBeDefined(); - expect(serverConfig.env!.MISSING_VAR).toBe('$UNDEFINED_ENV_VAR'); - expect(serverConfig.env!.MISSING_VAR_BRACES).toBe('${ALSO_UNDEFINED}'); - }); - - it('should skip extensions with invalid JSON and log a warning', () => { + it('should skip extensions with invalid JSON and log a warning', async () => { const consoleSpy = vi .spyOn(console, 'error') .mockImplementation(() => {}); @@ -430,22 +231,20 @@ describe('extension tests', () => { const badConfigPath = path.join(badExtDir, EXTENSIONS_CONFIG_FILENAME); fs.writeFileSync(badConfigPath, '{ "name": "bad-ext"'); // Malformed - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); expect(extensions).toHaveLength(1); expect(extensions[0].config.name).toBe('good-ext'); expect(consoleSpy).toHaveBeenCalledWith( - expect.stringContaining( - `Warning: Skipping extension in ${badExtDir}: Failed to load extension config from ${badConfigPath}`, - ), + expect.stringContaining(`Warning: Skipping extension in ${badExtDir}`), ); consoleSpy.mockRestore(); }); - it('should skip extensions with missing name and log a warning', () => { + it('should skip extensions with missing name and log a warning', async () => { const consoleSpy = vi .spyOn(console, 'error') .mockImplementation(() => {}); @@ -463,22 +262,20 @@ describe('extension tests', () => { const badConfigPath = path.join(badExtDir, EXTENSIONS_CONFIG_FILENAME); fs.writeFileSync(badConfigPath, JSON.stringify({ version: '1.0.0' })); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); expect(extensions).toHaveLength(1); expect(extensions[0].config.name).toBe('good-ext'); expect(consoleSpy).toHaveBeenCalledWith( - expect.stringContaining( - `Warning: Skipping extension in ${badExtDir}: Failed to load extension config from ${badConfigPath}: Invalid configuration in ${badConfigPath}: missing "name"`, - ), + expect.stringContaining(`Warning: Skipping extension in ${badExtDir}`), ); consoleSpy.mockRestore(); }); - it('should filter trust out of mcp servers', () => { + it('should filter trust out of mcp servers', async () => { createExtension({ extensionsDir: userExtensionsDir, name: 'test-extension', @@ -488,978 +285,319 @@ describe('extension tests', () => { command: 'node', args: ['server.js'], trust: true, - }, + } as MCPServerConfig, }, }); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - expect(extensions).toHaveLength(1); - const loadedConfig = extensions[0].config; - expect(loadedConfig.mcpServers?.['test-server'].trust).toBeUndefined(); - }); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); - it('should throw an error for invalid extension names', () => { - const consoleSpy = vi - .spyOn(console, 'error') - .mockImplementation(() => {}); - const badExtDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'bad_name', - version: '1.0.0', - }); - - const extension = loadExtension({ - extensionDir: badExtDir, - workspaceDir: tempWorkspaceDir, - }); - - expect(extension).toBeNull(); - expect(consoleSpy).toHaveBeenCalledWith( - expect.stringContaining('Invalid extension name: "bad_name"'), - ); - consoleSpy.mockRestore(); - }); - }); - - describe('annotateActiveExtensions', () => { - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { name: 'ext1', version: '1.0.0' }, - contextFiles: [], - }, - { - path: '/path/to/ext2', - config: { name: 'ext2', version: '1.0.0' }, - contextFiles: [], - }, - { - path: '/path/to/ext3', - config: { name: 'ext3', version: '1.0.0' }, - contextFiles: [], - }, - ]; - - it('should mark all extensions as active if no enabled extensions are provided', () => { - const activeExtensions = annotateActiveExtensions( - extensions, - '/path/to/workspace', - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - expect(activeExtensions).toHaveLength(3); - expect(activeExtensions.every((e) => e.isActive)).toBe(true); - }); - - it('should mark only the enabled extensions as active', () => { - const activeExtensions = annotateActiveExtensions( - extensions, - '/path/to/workspace', - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ['ext1', 'ext3'], - ), - ); - expect(activeExtensions).toHaveLength(3); - expect(activeExtensions.find((e) => e.name === 'ext1')?.isActive).toBe( - true, - ); - expect(activeExtensions.find((e) => e.name === 'ext2')?.isActive).toBe( - false, - ); - expect(activeExtensions.find((e) => e.name === 'ext3')?.isActive).toBe( - true, - ); - }); - - it('should mark all extensions as inactive when "none" is provided', () => { - const activeExtensions = annotateActiveExtensions( - extensions, - '/path/to/workspace', - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ['none'], - ), - ); - expect(activeExtensions).toHaveLength(3); - expect(activeExtensions.every((e) => !e.isActive)).toBe(true); - }); - - it('should handle case-insensitivity', () => { - const activeExtensions = annotateActiveExtensions( - extensions, - '/path/to/workspace', - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ['EXT1'], - ), - ); - expect(activeExtensions.find((e) => e.name === 'ext1')?.isActive).toBe( + expect(extensions).toHaveLength(1); + // trust should be filtered from extension.mcpServers (not config.mcpServers) + expect(extensions[0].mcpServers?.['test-server']?.trust).toBeUndefined(); + // config.mcpServers should still have trust (original config) + expect(extensions[0].config.mcpServers?.['test-server']?.trust).toBe( true, ); }); - - it('should log an error for unknown extensions', () => { - const consoleSpy = vi - .spyOn(console, 'error') - .mockImplementation(() => {}); - annotateActiveExtensions( - extensions, - '/path/to/workspace', - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ['ext4'], - ), - ); - expect(consoleSpy).toHaveBeenCalledWith('Extension not found: ext4'); - consoleSpy.mockRestore(); - }); - - describe('autoUpdate', () => { - it('should be false if autoUpdate is not set in install metadata', () => { - const activeExtensions = annotateActiveExtensions( - extensions, - tempHomeDir, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ); - expect( - activeExtensions.every( - (e) => e.installMetadata?.autoUpdate === false, - ), - ).toBe(false); - }); - - it('should be true if autoUpdate is true in install metadata', () => { - const extensionsWithAutoUpdate: Extension[] = extensions.map((e) => ({ - ...e, - installMetadata: { - ...e.installMetadata!, - autoUpdate: true, - }, - })); - const activeExtensions = annotateActiveExtensions( - extensionsWithAutoUpdate, - tempHomeDir, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ); - expect( - activeExtensions.every((e) => e.installMetadata?.autoUpdate === true), - ).toBe(true); - }); - - it('should respect the per-extension settings from install metadata', () => { - const extensionsWithAutoUpdate: Extension[] = [ - { - path: '/path/to/ext1', - config: { name: 'ext1', version: '1.0.0' }, - contextFiles: [], - installMetadata: { - source: 'test', - type: 'local', - autoUpdate: true, - }, - }, - { - path: '/path/to/ext2', - config: { name: 'ext2', version: '1.0.0' }, - contextFiles: [], - installMetadata: { - source: 'test', - type: 'local', - autoUpdate: false, - }, - }, - { - path: '/path/to/ext3', - config: { name: 'ext3', version: '1.0.0' }, - contextFiles: [], - }, - ]; - const activeExtensions = annotateActiveExtensions( - extensionsWithAutoUpdate, - tempHomeDir, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ); - expect( - activeExtensions.find((e) => e.name === 'ext1')?.installMetadata - ?.autoUpdate, - ).toBe(true); - expect( - activeExtensions.find((e) => e.name === 'ext2')?.installMetadata - ?.autoUpdate, - ).toBe(false); - expect( - activeExtensions.find((e) => e.name === 'ext3')?.installMetadata - ?.autoUpdate, - ).toBe(undefined); - }); - }); }); - describe('installExtension', () => { - it('should install an extension from a local path', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', - version: '1.0.0', - }); - const targetExtDir = path.join(userExtensionsDir, 'my-local-extension'); - const metadataPath = path.join(targetExtDir, INSTALL_METADATA_FILENAME); - - await installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ); - - expect(fs.existsSync(targetExtDir)).toBe(true); - expect(fs.existsSync(metadataPath)).toBe(true); - const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); - expect(metadata).toEqual({ - source: sourceExtDir, - type: 'local', - }); - fs.rmSync(targetExtDir, { recursive: true, force: true }); - }); - - it('should throw an error if the extension already exists', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', + describe('enableExtension / disableExtension', () => { + it('should disable an extension at the user scope', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'my-extension', version: '1.0.0', }); - await installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ); - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ), - ).rejects.toThrow( - 'Extension "my-local-extension" is already installed. Please uninstall it first.', - ); - }); - - it('should throw an error and cleanup if qwen-extension.json is missing', async () => { - const sourceExtDir = path.join(tempHomeDir, 'bad-extension'); - fs.mkdirSync(sourceExtDir, { recursive: true }); - const configPath = path.join(sourceExtDir, EXTENSIONS_CONFIG_FILENAME); - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ), - ).rejects.toThrow(`Configuration file not found at ${configPath}`); + const manager = createExtensionManager(); + await manager.refreshCache(); - const targetExtDir = path.join(userExtensionsDir, 'bad-extension'); - expect(fs.existsSync(targetExtDir)).toBe(false); + manager.disableExtension('my-extension', SettingScope.User); + expect(manager.isEnabled('my-extension', tempWorkspaceDir)).toBe(false); }); - it('should throw an error for invalid JSON in qwen-extension.json', async () => { - const sourceExtDir = path.join(tempHomeDir, 'bad-json-ext'); - fs.mkdirSync(sourceExtDir, { recursive: true }); - const configPath = path.join(sourceExtDir, EXTENSIONS_CONFIG_FILENAME); - fs.writeFileSync(configPath, '{ "name": "bad-json", "version": "1.0.0"'); // Malformed JSON - - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ), - ).rejects.toThrow( - new RegExp( - `^Failed to load extension config from ${configPath.replace( - /\\/g, - '\\\\', - )}`, - ), - ); - }); - - it('should throw an error for missing name in qwen-extension.json', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'missing-name-ext', + it('should disable an extension at the workspace scope', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'my-extension', version: '1.0.0', }); - const configPath = path.join(sourceExtDir, EXTENSIONS_CONFIG_FILENAME); - // Overwrite with invalid config - fs.writeFileSync(configPath, JSON.stringify({ version: '1.0.0' })); - - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ), - ).rejects.toThrow( - `Invalid configuration in ${configPath}: missing "name"`, - ); - }); - - it('should install an extension from a git URL', async () => { - const gitUrl = 'https://github.com/google/gemini-extensions.git'; - const extensionName = 'qwen-extensions'; - const targetExtDir = path.join(userExtensionsDir, extensionName); - const metadataPath = path.join(targetExtDir, INSTALL_METADATA_FILENAME); - - mockGit.clone.mockImplementation(async (_, destination) => { - fs.mkdirSync(path.join(mockGit.path(), destination), { - recursive: true, - }); - fs.writeFileSync( - path.join(mockGit.path(), destination, EXTENSIONS_CONFIG_FILENAME), - JSON.stringify({ name: extensionName, version: '1.0.0' }), - ); - }); - mockGit.getRemotes.mockResolvedValue([{ name: 'origin' }]); - - await installExtension( - { source: gitUrl, type: 'git' }, - async (_) => true, - ); - expect(fs.existsSync(targetExtDir)).toBe(true); - expect(fs.existsSync(metadataPath)).toBe(true); - const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); - expect(metadata).toEqual({ - source: gitUrl, - type: 'git', - }); - fs.rmSync(targetExtDir, { recursive: true, force: true }); - }); + const manager = createExtensionManager(); + await manager.refreshCache(); - it('should install a linked extension', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-linked-extension', - version: '1.0.0', - }); - const targetExtDir = path.join(userExtensionsDir, 'my-linked-extension'); - const metadataPath = path.join(targetExtDir, INSTALL_METADATA_FILENAME); - const configPath = path.join(targetExtDir, EXTENSIONS_CONFIG_FILENAME); - - await installExtension( - { source: sourceExtDir, type: 'link' }, - async (_) => true, + manager.disableExtension( + 'my-extension', + SettingScope.Workspace, + tempWorkspaceDir, ); - expect(fs.existsSync(targetExtDir)).toBe(true); - expect(fs.existsSync(metadataPath)).toBe(true); - - expect(fs.existsSync(configPath)).toBe(false); - - const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); - expect(metadata).toEqual({ - source: sourceExtDir, - type: 'link', - }); - fs.rmSync(targetExtDir, { recursive: true, force: true }); + expect(manager.isEnabled('my-extension', tempHomeDir)).toBe(true); + expect(manager.isEnabled('my-extension', tempWorkspaceDir)).toBe(false); }); - it('should log to clearcut on successful install', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', + it('should handle disabling the same extension twice', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'my-extension', version: '1.0.0', }); - await installExtension( - { source: sourceExtDir, type: 'local' }, - async (_) => true, - ); + const manager = createExtensionManager(); + await manager.refreshCache(); - expect(mockLogExtensionInstallEvent).toHaveBeenCalled(); + manager.disableExtension('my-extension', SettingScope.User); + manager.disableExtension('my-extension', SettingScope.User); + expect(manager.isEnabled('my-extension', tempWorkspaceDir)).toBe(false); }); - it('should show users information on their mcp server when installing', async () => { - const consoleInfoSpy = vi.spyOn(console, 'info'); - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', - version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - description: 'a local mcp server', - }, - 'test-server-2': { - description: 'a remote mcp server', - httpUrl: 'https://google.com', - }, - }, - }); - - mockQuestion.mockImplementation((_query, callback) => callback('y')); - - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - requestConsentNonInteractive, - ), - ).resolves.toBe('my-local-extension'); - - expect(consoleInfoSpy).toHaveBeenCalledWith( - `Installing extension "my-local-extension". -**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.** -This extension will run the following MCP servers: - * test-server (local): node server.js - * test-server-2 (remote): https://google.com`, - ); - }); - - it('should continue installation if user accepts prompt for local extension with mcp servers', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', + it('should throw an error if you request system scope', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'my-extension', version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - }, - }, }); - mockQuestion.mockImplementation((_query, callback) => callback('y')); + const manager = createExtensionManager(); + await manager.refreshCache(); - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - requestConsentNonInteractive, - ), - ).resolves.toBe('my-local-extension'); - - expect(mockQuestion).toHaveBeenCalledWith( - expect.stringContaining('Do you want to continue? [Y/n]: '), - expect.any(Function), - ); + expect(() => + manager.disableExtension('my-extension', SettingScope.System), + ).toThrow('System and SystemDefaults scopes are not supported.'); }); - it('should cancel installation if user declines prompt for local extension with mcp servers', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', + it('should enable an extension at the user scope', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'ext1', version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - }, - }, }); - mockQuestion.mockImplementation((_query, callback) => callback('n')); + const manager = createExtensionManager(); + await manager.refreshCache(); - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - requestConsentNonInteractive, - ), - ).rejects.toThrow('Installation cancelled for "my-local-extension".'); - - expect(mockQuestion).toHaveBeenCalledWith( - expect.stringContaining('Do you want to continue? [Y/n]: '), - expect.any(Function), - ); - }); - - it('should save the autoUpdate flag to the install metadata', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', - version: '1.0.0', - }); - const targetExtDir = path.join(userExtensionsDir, 'my-local-extension'); - const metadataPath = path.join(targetExtDir, INSTALL_METADATA_FILENAME); - - await installExtension( - { - source: sourceExtDir, - type: 'local', - autoUpdate: true, - }, - async (_) => true, - ); + manager.disableExtension('ext1', SettingScope.User); + expect(manager.isEnabled('ext1')).toBe(false); - expect(fs.existsSync(targetExtDir)).toBe(true); - expect(fs.existsSync(metadataPath)).toBe(true); - const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); - expect(metadata).toEqual({ - source: sourceExtDir, - type: 'local', - autoUpdate: true, - }); - fs.rmSync(targetExtDir, { recursive: true, force: true }); + manager.enableExtension('ext1', SettingScope.User); + expect(manager.isEnabled('ext1')).toBe(true); }); - it('should ignore consent flow if not required', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'my-local-extension', + it('should enable an extension at the workspace scope', async () => { + createExtension({ + extensionsDir: userExtensionsDir, + name: 'ext1', version: '1.0.0', - mcpServers: { - 'test-server': { - command: 'node', - args: ['server.js'], - }, - }, }); - const mockRequestConsent = vi.fn(); - - await expect( - installExtension( - { source: sourceExtDir, type: 'local' }, - mockRequestConsent, - process.cwd(), - // Provide its own existing config as the previous config. - await loadExtensionConfig({ - extensionDir: sourceExtDir, - workspaceDir: process.cwd(), - }), - ), - ).resolves.toBe('my-local-extension'); - - expect(mockRequestConsent).not.toHaveBeenCalled(); - }); + const manager = createExtensionManager(); + await manager.refreshCache(); - it('should throw an error for invalid extension names', async () => { - const sourceExtDir = createExtension({ - extensionsDir: tempHomeDir, - name: 'bad_name', - version: '1.0.0', - }); + manager.disableExtension('ext1', SettingScope.Workspace); + expect(manager.isEnabled('ext1', tempWorkspaceDir)).toBe(false); - await expect( - installExtension({ source: sourceExtDir, type: 'local' }), - ).rejects.toThrow('Invalid extension name: "bad_name"'); + manager.enableExtension('ext1', SettingScope.Workspace); + expect(manager.isEnabled('ext1', tempWorkspaceDir)).toBe(true); }); }); - describe('uninstallExtension', () => { - it('should uninstall an extension by name', async () => { - const sourceExtDir = createExtension({ - extensionsDir: userExtensionsDir, - name: 'my-local-extension', - version: '1.0.0', - }); - - await uninstallExtension('my-local-extension'); - - expect(fs.existsSync(sourceExtDir)).toBe(false); - }); - - it('should uninstall an extension by name and retain existing extensions', async () => { - const sourceExtDir = createExtension({ + describe('validateExtensionOverrides', () => { + it('should mark all extensions as active if no enabled extensions are provided', async () => { + createExtension({ extensionsDir: userExtensionsDir, - name: 'my-local-extension', + name: 'ext1', version: '1.0.0', }); - const otherExtDir = createExtension({ + createExtension({ extensionsDir: userExtensionsDir, - name: 'other-extension', + name: 'ext2', version: '1.0.0', }); - await uninstallExtension('my-local-extension'); - - expect(fs.existsSync(sourceExtDir)).toBe(false); - expect( - loadExtensions( - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ), - ).toHaveLength(1); - expect(fs.existsSync(otherExtDir)).toBe(true); - }); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); - it('should throw an error if the extension does not exist', async () => { - await expect(uninstallExtension('nonexistent-extension')).rejects.toThrow( - 'Extension not found.', - ); + expect(extensions).toHaveLength(2); + expect(extensions.every((e) => e.isActive)).toBe(true); }); - it('should log uninstall event', async () => { + it('should mark only the enabled extensions as active', async () => { createExtension({ extensionsDir: userExtensionsDir, - name: 'my-local-extension', + name: 'ext1', version: '1.0.0', }); - - await uninstallExtension('my-local-extension'); - - expect(mockLogExtensionUninstall).toHaveBeenCalled(); - expect(ExtensionUninstallEvent).toHaveBeenCalledWith( - 'my-local-extension', - 'success', - ); - }); - - it('should uninstall an extension by its source URL', async () => { - const gitUrl = 'https://github.com/google/gemini-sql-extension.git'; - const sourceExtDir = createExtension({ + createExtension({ extensionsDir: userExtensionsDir, - name: 'gemini-sql-extension', + name: 'ext2', version: '1.0.0', - installMetadata: { - source: gitUrl, - type: 'git', - }, }); - - await uninstallExtension(gitUrl); - - expect(fs.existsSync(sourceExtDir)).toBe(false); - expect(mockLogExtensionUninstall).toHaveBeenCalled(); - expect(ExtensionUninstallEvent).toHaveBeenCalledWith( - 'gemini-sql-extension', - 'success', - ); - }); - - it('should fail to uninstall by URL if an extension has no install metadata', async () => { createExtension({ extensionsDir: userExtensionsDir, - name: 'no-metadata-extension', + name: 'ext3', version: '1.0.0', - // No installMetadata provided - }); - - await expect( - uninstallExtension('https://github.com/google/no-metadata-extension'), - ).rejects.toThrow('Extension not found.'); - }); - }); - - describe('performWorkspaceExtensionMigration', () => { - let workspaceExtensionsDir: string; - - beforeEach(() => { - workspaceExtensionsDir = path.join( - tempWorkspaceDir, - EXTENSIONS_DIRECTORY_NAME, - ); - fs.mkdirSync(workspaceExtensionsDir, { recursive: true }); - }); - - afterEach(() => { - fs.rmSync(workspaceExtensionsDir, { recursive: true, force: true }); - }); - - describe('folder trust', () => { - it('refuses to install extensions from untrusted folders', async () => { - vi.mocked(isWorkspaceTrusted).mockReturnValue(false); - const ext1Path = createExtension({ - extensionsDir: workspaceExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - - const failed = await performWorkspaceExtensionMigration([ - loadExtension({ - extensionDir: ext1Path, - workspaceDir: tempWorkspaceDir, - })!, - ]); - - expect(failed).toEqual(['ext1']); }); - it('does not copy extensions to the user dir', async () => { - vi.mocked(isWorkspaceTrusted).mockReturnValue(false); - const ext1Path = createExtension({ - extensionsDir: workspaceExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - - await performWorkspaceExtensionMigration( - [ - loadExtension({ - extensionDir: ext1Path, - workspaceDir: tempWorkspaceDir, - })!, - ], - async (_) => true, - ); - - const userExtensionsDir = path.join( - tempHomeDir, - QWEN_DIR, - 'extensions', - ); - expect(fs.readdirSync(userExtensionsDir).length).toBe(0); + const manager = createExtensionManager({ + enabledExtensionOverrides: ['ext1', 'ext3'], }); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); - it('does not load any extensions in the workspace config', async () => { - vi.mocked(isWorkspaceTrusted).mockReturnValue(false); - const ext1Path = createExtension({ - extensionsDir: workspaceExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - - await performWorkspaceExtensionMigration( - [ - loadExtension({ - extensionDir: ext1Path, - workspaceDir: tempWorkspaceDir, - })!, - ], - async (_) => true, - ); - const extensions = loadExtensions( - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ), - ); - - expect(extensions).toEqual([]); - }); + expect(extensions.find((e) => e.name === 'ext1')?.isActive).toBe(true); + expect(extensions.find((e) => e.name === 'ext2')?.isActive).toBe(false); + expect(extensions.find((e) => e.name === 'ext3')?.isActive).toBe(true); }); - it('should install the extensions in the user directory', async () => { - const ext1Path = createExtension({ - extensionsDir: workspaceExtensionsDir, + it('should mark all extensions as inactive when "none" is provided', async () => { + createExtension({ + extensionsDir: userExtensionsDir, name: 'ext1', version: '1.0.0', }); - const ext2Path = createExtension({ - extensionsDir: workspaceExtensionsDir, + createExtension({ + extensionsDir: userExtensionsDir, name: 'ext2', version: '1.0.0', }); - const extensionsToMigrate: Extension[] = [ - loadExtension({ - extensionDir: ext1Path, - workspaceDir: tempWorkspaceDir, - })!, - loadExtension({ - extensionDir: ext2Path, - workspaceDir: tempWorkspaceDir, - })!, - ]; - const failed = await performWorkspaceExtensionMigration( - extensionsToMigrate, - async (_) => true, - ); - - expect(failed).toEqual([]); - const userExtensionsDir = path.join(tempHomeDir, QWEN_DIR, 'extensions'); - const userExt1Path = path.join(userExtensionsDir, 'ext1'); - const extensions = loadExtensions( - new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()), - ); - - expect(extensions).toHaveLength(2); - const metadataPath = path.join(userExt1Path, INSTALL_METADATA_FILENAME); - expect(fs.existsSync(metadataPath)).toBe(true); - const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); - expect(metadata).toEqual({ - source: ext1Path, - type: 'local', - }); - }); - - it('should return the names of failed installations', async () => { - const ext1Path = createExtension({ - extensionsDir: workspaceExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - - const extensions: Extension[] = [ - loadExtension({ - extensionDir: ext1Path, - workspaceDir: tempWorkspaceDir, - })!, - { - path: '/ext/path/1', - config: { name: 'ext2', version: '1.0.0' }, - contextFiles: [], - }, - ]; - - const failed = await performWorkspaceExtensionMigration( - extensions, - async (_) => true, - ); - expect(failed).toEqual(['ext2']); - }); - }); - - describe('disableExtension', () => { - it('should disable an extension at the user scope', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'my-extension', - version: '1.0.0', + const manager = createExtensionManager({ + enabledExtensionOverrides: ['none'], }); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); - disableExtension('my-extension', SettingScope.User); - expect( - isEnabled({ - name: 'my-extension', - configDir: userExtensionsDir, - enabledForPath: tempWorkspaceDir, - }), - ).toBe(false); + expect(extensions.every((e) => !e.isActive)).toBe(true); }); - it('should disable an extension at the workspace scope', () => { + it('should handle case-insensitivity', async () => { createExtension({ extensionsDir: userExtensionsDir, - name: 'my-extension', + name: 'ext1', version: '1.0.0', }); - disableExtension( - 'my-extension', - SettingScope.Workspace, - tempWorkspaceDir, - ); - expect( - isEnabled({ - name: 'my-extension', - configDir: userExtensionsDir, - enabledForPath: tempHomeDir, - }), - ).toBe(true); - expect( - isEnabled({ - name: 'my-extension', - configDir: userExtensionsDir, - enabledForPath: tempWorkspaceDir, - }), - ).toBe(false); - }); - - it('should handle disabling the same extension twice', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'my-extension', - version: '1.0.0', + const manager = createExtensionManager({ + enabledExtensionOverrides: ['EXT1'], }); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); - disableExtension('my-extension', SettingScope.User); - disableExtension('my-extension', SettingScope.User); - expect( - isEnabled({ - name: 'my-extension', - configDir: userExtensionsDir, - enabledForPath: tempWorkspaceDir, - }), - ).toBe(false); + expect(extensions.find((e) => e.name === 'ext1')?.isActive).toBe(true); }); - it('should throw an error if you request system scope', () => { - expect(() => - disableExtension('my-extension', SettingScope.System), - ).toThrow('System and SystemDefaults scopes are not supported.'); - }); + it('should log an error for unknown extensions', async () => { + const consoleSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}); - it('should log a disable event', () => { createExtension({ extensionsDir: userExtensionsDir, name: 'ext1', version: '1.0.0', }); - disableExtension('ext1', SettingScope.Workspace); + const manager = createExtensionManager({ + enabledExtensionOverrides: ['ext4'], + }); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); + manager.validateExtensionOverrides(extensions); - expect(mockLogExtensionDisable).toHaveBeenCalled(); - expect(ExtensionDisableEvent).toHaveBeenCalledWith( - 'ext1', - SettingScope.Workspace, - ); + expect(consoleSpy).toHaveBeenCalledWith('Extension not found: ext4'); + consoleSpy.mockRestore(); }); }); - describe('enableExtension', () => { - afterAll(() => { - vi.restoreAllMocks(); - }); + describe('loadExtensionConfig', () => { + it('should resolve environment variables in extension configuration', async () => { + process.env['TEST_API_KEY'] = 'test-api-key-123'; + process.env['TEST_DB_URL'] = 'postgresql://localhost:5432/testdb'; - const getActiveExtensions = (): GeminiCLIExtension[] => { - const manager = new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - ); - const extensions = loadExtensions(manager); - const activeExtensions = annotateActiveExtensions( - extensions, - tempWorkspaceDir, - manager, - ); - return activeExtensions.filter((e) => e.isActive); - }; + try { + const extDir = path.join(userExtensionsDir, 'test-extension'); + fs.mkdirSync(extDir); - it('should enable an extension at the user scope', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - disableExtension('ext1', SettingScope.User); - let activeExtensions = getActiveExtensions(); - expect(activeExtensions).toHaveLength(0); - - enableExtension('ext1', SettingScope.User); - activeExtensions = getActiveExtensions(); - expect(activeExtensions).toHaveLength(1); - expect(activeExtensions[0].name).toBe('ext1'); - }); + const extensionConfig = { + name: 'test-extension', + version: '1.0.0', + mcpServers: { + 'test-server': { + command: 'node', + args: ['server.js'], + env: { + API_KEY: '$TEST_API_KEY', + DATABASE_URL: '${TEST_DB_URL}', + STATIC_VALUE: 'no-substitution', + }, + }, + }, + }; + fs.writeFileSync( + path.join(extDir, EXTENSIONS_CONFIG_FILENAME), + JSON.stringify(extensionConfig), + ); - it('should enable an extension at the workspace scope', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'ext1', - version: '1.0.0', - }); - disableExtension('ext1', SettingScope.Workspace); - let activeExtensions = getActiveExtensions(); - expect(activeExtensions).toHaveLength(0); - - enableExtension('ext1', SettingScope.Workspace); - activeExtensions = getActiveExtensions(); - expect(activeExtensions).toHaveLength(1); - expect(activeExtensions[0].name).toBe('ext1'); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); + + expect(extensions).toHaveLength(1); + const extension = extensions[0]; + expect(extension.config.name).toBe('test-extension'); + expect(extension.config.mcpServers).toBeDefined(); + + const serverConfig = extension.config.mcpServers?.['test-server']; + expect(serverConfig).toBeDefined(); + expect(serverConfig?.env).toBeDefined(); + expect(serverConfig?.env?.['API_KEY']).toBe('test-api-key-123'); + expect(serverConfig?.env?.['DATABASE_URL']).toBe( + 'postgresql://localhost:5432/testdb', + ); + expect(serverConfig?.env?.['STATIC_VALUE']).toBe('no-substitution'); + } finally { + delete process.env['TEST_API_KEY']; + delete process.env['TEST_DB_URL']; + } }); - it('should log an enable event', () => { - createExtension({ - extensionsDir: userExtensionsDir, - name: 'ext1', + it('should handle missing environment variables gracefully', async () => { + const extDir = path.join(userExtensionsDir, 'test-extension'); + fs.mkdirSync(extDir); + + const extensionConfig = { + name: 'test-extension', version: '1.0.0', - }); - disableExtension('ext1', SettingScope.Workspace); - enableExtension('ext1', SettingScope.Workspace); + mcpServers: { + 'test-server': { + command: 'node', + args: ['server.js'], + env: { + MISSING_VAR: '$UNDEFINED_ENV_VAR', + MISSING_VAR_BRACES: '${ALSO_UNDEFINED}', + }, + }, + }, + }; - expect(mockLogExtensionEnable).toHaveBeenCalled(); - expect(ExtensionEnableEvent).toHaveBeenCalledWith( - 'ext1', - SettingScope.Workspace, + fs.writeFileSync( + path.join(extDir, EXTENSIONS_CONFIG_FILENAME), + JSON.stringify(extensionConfig), ); + + const manager = createExtensionManager(); + await manager.refreshCache(); + const extensions = manager.getLoadedExtensions(); + + expect(extensions).toHaveLength(1); + const extension = extensions[0]; + const serverConfig = extension.config.mcpServers!['test-server']; + expect(serverConfig.env).toBeDefined(); + expect(serverConfig.env!['MISSING_VAR']).toBe('$UNDEFINED_ENV_VAR'); + expect(serverConfig.env!['MISSING_VAR_BRACES']).toBe('${ALSO_UNDEFINED}'); }); }); }); - -function isEnabled(options: { - name: string; - configDir: string; - enabledForPath: string; -}) { - const manager = new ExtensionEnablementManager(options.configDir); - return manager.isEnabled(options.name, options.enabledForPath); -} diff --git a/packages/core/src/extension/extensionSettings.test.ts b/packages/core/src/extension/extensionSettings.test.ts index 4d185f896cc..3705be5bd8b 100644 --- a/packages/core/src/extension/extensionSettings.test.ts +++ b/packages/core/src/extension/extensionSettings.test.ts @@ -27,14 +27,19 @@ vi.mock('os', async (importOriginal) => { }; }); -vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { - const actual = - await importOriginal(); - return { - ...actual, - KeychainTokenStorage: vi.fn(), - }; -}); +vi.mock( + '../mcp/token-storage/keychain-token-storage.js', + async (importOriginal) => { + const actual = + await importOriginal< + typeof import('../mcp/token-storage/keychain-token-storage.js') + >(); + return { + ...actual, + KeychainTokenStorage: vi.fn(), + }; + }, +); describe('extensionSettings', () => { let tempHomeDir: string; diff --git a/packages/core/src/extension/github.test.ts b/packages/core/src/extension/github.test.ts index 77cfd19278a..d135f3e289f 100644 --- a/packages/core/src/extension/github.test.ts +++ b/packages/core/src/extension/github.test.ts @@ -19,8 +19,11 @@ import * as fsSync from 'node:fs'; import * as path from 'node:path'; import * as tar from 'tar'; import * as archiver from 'archiver'; -import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; -import type { ExtensionUpdateState } from './update.js'; +import { + ExtensionUpdateState, + type Extension, + type ExtensionManager, +} from './extensionManager.js'; const mockPlatform = vi.hoisted(() => vi.fn()); const mockArch = vi.hoisted(() => vi.fn()); @@ -123,116 +126,108 @@ describe('git extension helpers', () => { revparse: vi.fn(), }; + const mockExtensionManager = { + loadExtensionConfig: vi.fn(), + } as unknown as ExtensionManager; + beforeEach(() => { vi.mocked(simpleGit).mockReturnValue(mockGit as unknown as SimpleGit); }); - it('should return NOT_UPDATABLE for non-git extensions', async () => { - const extension: GeminiCLIExtension = { + function createExtension(overrides: Partial = {}): Extension { + return { + id: 'test-id', name: 'test', path: '/ext', version: '1.0.0', isActive: true, + config: { name: 'test', version: '1.0.0' }, + contextFiles: [], + ...overrides, + }; + } + + it('should return NOT_UPDATABLE for non-git extensions', async () => { + const extension = createExtension({ installMetadata: { type: 'link', source: '', }, - }; - let result: ExtensionUpdateState | undefined = undefined; - await checkForExtensionUpdate( + }); + const result = await checkForExtensionUpdate( extension, - (newState) => (result = newState), + mockExtensionManager, ); expect(result).toBe(ExtensionUpdateState.NOT_UPDATABLE); }); it('should return ERROR if no remotes found', async () => { - const extension: GeminiCLIExtension = { - name: 'test', - path: '/ext', - version: '1.0.0', - isActive: true, + const extension = createExtension({ installMetadata: { type: 'git', source: '', }, - }; + }); mockGit.getRemotes.mockResolvedValue([]); - let result: ExtensionUpdateState | undefined = undefined; - await checkForExtensionUpdate( + const result = await checkForExtensionUpdate( extension, - (newState) => (result = newState), + mockExtensionManager, ); expect(result).toBe(ExtensionUpdateState.ERROR); }); it('should return UPDATE_AVAILABLE when remote hash is different', async () => { - const extension: GeminiCLIExtension = { - name: 'test', - path: '/ext', - version: '1.0.0', - isActive: true, + const extension = createExtension({ installMetadata: { type: 'git', source: 'my/ext', }, - }; + }); mockGit.getRemotes.mockResolvedValue([ { name: 'origin', refs: { fetch: 'http://my-repo.com' } }, ]); mockGit.listRemote.mockResolvedValue('remote-hash\tHEAD'); mockGit.revparse.mockResolvedValue('local-hash'); - let result: ExtensionUpdateState | undefined = undefined; - await checkForExtensionUpdate( + const result = await checkForExtensionUpdate( extension, - (newState) => (result = newState), + mockExtensionManager, ); expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE); }); it('should return UP_TO_DATE when remote and local hashes are the same', async () => { - const extension: GeminiCLIExtension = { - name: 'test', - path: '/ext', - version: '1.0.0', - isActive: true, + const extension = createExtension({ installMetadata: { type: 'git', source: 'my/ext', }, - }; + }); mockGit.getRemotes.mockResolvedValue([ { name: 'origin', refs: { fetch: 'http://my-repo.com' } }, ]); mockGit.listRemote.mockResolvedValue('same-hash\tHEAD'); mockGit.revparse.mockResolvedValue('same-hash'); - let result: ExtensionUpdateState | undefined = undefined; - await checkForExtensionUpdate( + const result = await checkForExtensionUpdate( extension, - (newState) => (result = newState), + mockExtensionManager, ); expect(result).toBe(ExtensionUpdateState.UP_TO_DATE); }); it('should return ERROR on git error', async () => { - const extension: GeminiCLIExtension = { - name: 'test', - path: '/ext', - version: '1.0.0', - isActive: true, + const extension = createExtension({ installMetadata: { type: 'git', source: 'my/ext', }, - }; + }); mockGit.getRemotes.mockRejectedValue(new Error('git error')); - let result: ExtensionUpdateState | undefined = undefined; - await checkForExtensionUpdate( + const result = await checkForExtensionUpdate( extension, - (newState) => (result = newState), + mockExtensionManager, ); expect(result).toBe(ExtensionUpdateState.ERROR); }); diff --git a/packages/core/src/extension/github.ts b/packages/core/src/extension/github.ts index db2f0e80ea5..22d7d6f61ea 100644 --- a/packages/core/src/extension/github.ts +++ b/packages/core/src/extension/github.ts @@ -6,7 +6,6 @@ import { simpleGit } from 'simple-git'; import { getErrorMessage } from '../utils/errors.js'; -import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; import * as os from 'node:os'; import * as https from 'node:https'; import * as fs from 'node:fs'; @@ -20,6 +19,7 @@ import { type ExtensionConfig, type ExtensionManager, } from './extensionManager.js'; +import type { ExtensionInstallMetadata } from '../config/config.js'; interface GithubReleaseData { assets: Asset[]; diff --git a/packages/core/src/extension/marketplace.ts b/packages/core/src/extension/marketplace.ts index 0f90a5e5e90..ab3351546e4 100644 --- a/packages/core/src/extension/marketplace.ts +++ b/packages/core/src/extension/marketplace.ts @@ -22,7 +22,7 @@ import { type ClaudePluginConfig, } from './claude-converter.js'; import { cloneFromGit, downloadFromGitHubRelease } from './github.js'; -import type { ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; +import type { ExtensionInstallMetadata } from '../config/config.js'; export interface MarketplaceInstallOptions { marketplaceUrl: string; diff --git a/packages/core/src/extension/storage.test.ts b/packages/core/src/extension/storage.test.ts index 4f392f94e64..7f0b7df0e49 100644 --- a/packages/core/src/extension/storage.test.ts +++ b/packages/core/src/extension/storage.test.ts @@ -13,7 +13,7 @@ import { EXTENSION_SETTINGS_FILENAME, EXTENSIONS_CONFIG_FILENAME, } from './variables.js'; -import { Storage } from '@qwen-code/qwen-code-core'; +import { Storage } from '../config/storage.js'; vi.mock('node:os'); vi.mock('node:fs', async (importOriginal) => { diff --git a/packages/core/src/extension/storage.ts b/packages/core/src/extension/storage.ts index fec7b38d456..30d95b34e69 100644 --- a/packages/core/src/extension/storage.ts +++ b/packages/core/src/extension/storage.ts @@ -1,4 +1,4 @@ -import { Storage } from '@qwen-code/qwen-code-core'; +import { Storage } from '../config/storage.js'; import path from 'node:path'; import * as os from 'node:os'; import { diff --git a/packages/core/src/extension/variables.ts b/packages/core/src/extension/variables.ts index f905eea60f3..ccac1c65f4b 100644 --- a/packages/core/src/extension/variables.ts +++ b/packages/core/src/extension/variables.ts @@ -6,7 +6,7 @@ import { type VariableSchema, VARIABLE_SCHEMA } from './variableSchema.js'; import path from 'node:path'; -import { QWEN_DIR } from '@qwen-code/qwen-code-core'; +import { QWEN_DIR } from '../config/storage.js'; export const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); export const EXTENSIONS_CONFIG_FILENAME = 'qwen-extension.json'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fb14dc61065..4f40a8a07f9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -53,6 +53,8 @@ export * from './utils/subagentGenerator.js'; export * from './utils/projectSummary.js'; export * from './utils/promptIdContext.js'; export * from './utils/thoughtUtils.js'; +export * from './utils/toml-to-markdown-converter.js'; +export * from './utils/yaml-parser.js'; // Export services export * from './services/fileDiscoveryService.js'; From b37ede07e8a058c13ea59a1869ea0dcce04d851d Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 14 Jan 2026 17:48:25 +0800 Subject: [PATCH 08/30] fix/gemini extension install error --- .../cli/src/commands/extensions/install.ts | 6 +- .../src/extension/extensionManager.test.ts | 229 ++++++++++++++++++ packages/core/src/extension/github.test.ts | 59 +++++ packages/core/src/extension/github.ts | 34 +-- 4 files changed, 311 insertions(+), 17 deletions(-) diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index df3ba4b3447..2654ac98cb2 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -51,7 +51,7 @@ export async function handleInstall(args: InstallArgs) { }); await extensionManager.refreshCache(); - const name = await extensionManager.installExtension( + const extension = await extensionManager.installExtension( { ...installMetadata, ref: args.ref, @@ -60,7 +60,9 @@ export async function handleInstall(args: InstallArgs) { }, requestConsent, ); - console.log(`Extension "${name}" installed successfully and enabled.`); + console.log( + `Extension "${extension.name}" installed successfully and enabled.`, + ); } catch (error) { console.error(getErrorMessage(error)); process.exit(1); diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 1bebae39d8b..72197cda7bb 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -17,6 +17,13 @@ import { ExtensionManager, SettingScope, type ExtensionManagerOptions, + validateName, + getExtensionId, + hashValue, + extensionConsentString, + maybeRequestConsentOrFail, + parseInstallSource, + type ExtensionConfig, } from './extensionManager.js'; import type { MCPServerConfig, ExtensionInstallMetadata } from '../index.js'; @@ -601,3 +608,225 @@ describe('extension tests', () => { }); }); }); + +describe('extensionManager utility functions', () => { + describe('validateName', () => { + it('should accept valid extension names', () => { + expect(() => validateName('my-extension')).not.toThrow(); + expect(() => validateName('Extension123')).not.toThrow(); + expect(() => validateName('test-ext-1')).not.toThrow(); + expect(() => validateName('UPPERCASE')).not.toThrow(); + }); + + it('should reject names with invalid characters', () => { + expect(() => validateName('my_extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my.extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my@ext')).toThrow('Invalid extension name'); + }); + + it('should reject empty names', () => { + expect(() => validateName('')).toThrow('Invalid extension name'); + }); + }); + + describe('hashValue', () => { + it('should generate consistent hash for same input', () => { + const hash1 = hashValue('test-input'); + const hash2 = hashValue('test-input'); + expect(hash1).toBe(hash2); + }); + + it('should generate different hashes for different inputs', () => { + const hash1 = hashValue('input-1'); + const hash2 = hashValue('input-2'); + expect(hash1).not.toBe(hash2); + }); + + it('should generate a valid SHA256 hash', () => { + const hash = hashValue('test'); + expect(hash).toMatch(/^[a-f0-9]{64}$/); + }); + }); + + describe('getExtensionId', () => { + it('should use hashed name when no install metadata', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const id = getExtensionId(config); + expect(id).toBe(hashValue('test-ext')); + }); + + it('should use hashed source for local install', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const metadata = { type: 'local' as const, source: '/path/to/ext' }; + const id = getExtensionId(config, metadata); + expect(id).toBe(hashValue('/path/to/ext')); + }); + + it('should use GitHub URL for git install', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const metadata = { + type: 'git' as const, + source: 'https://github.com/owner/repo', + }; + const id = getExtensionId(config, metadata); + expect(id).toBe(hashValue('https://github.com/owner/repo')); + }); + }); + + describe('extensionConsentString', () => { + it('should generate basic consent string', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const consent = extensionConsentString(config); + expect(consent).toContain('Installing extension "test-ext"'); + expect(consent).toContain('Extensions may introduce unexpected behavior'); + }); + + it('should include MCP servers in consent string', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + mcpServers: { + 'my-server': { command: 'node', args: ['server.js'] }, + }, + }; + const consent = extensionConsentString(config); + expect(consent).toContain( + 'This extension will run the following MCP servers', + ); + expect(consent).toContain('my-server'); + }); + + it('should include commands in consent string', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const consent = extensionConsentString(config, ['cmd1', 'cmd2']); + expect(consent).toContain( + 'This extension will add the following commands', + ); + expect(consent).toContain('cmd1, cmd2'); + }); + + it('should include context file info', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + contextFileName: 'CONTEXT.md', + }; + const consent = extensionConsentString(config); + expect(consent).toContain('CONTEXT.md'); + }); + + it('should include excluded tools', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + excludeTools: ['tool1', 'tool2'], + }; + const consent = extensionConsentString(config); + expect(consent).toContain('exclude the following core tools'); + }); + }); + + describe('maybeRequestConsentOrFail', () => { + it('should request consent for new installation', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail(config, requestConsent, []); + + expect(requestConsent).toHaveBeenCalledTimes(1); + }); + + it('should throw if user declines consent', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const requestConsent = vi.fn().mockResolvedValue(false); + + await expect( + maybeRequestConsentOrFail(config, requestConsent, []), + ).rejects.toThrow('Installation cancelled'); + }); + + it('should skip consent if config unchanged during update', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '0.9.0', + }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail( + config, + requestConsent, + [], + previousConfig, + ); + + expect(requestConsent).not.toHaveBeenCalled(); + }); + + it('should request consent if config changed during update', async () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + mcpServers: { server: { command: 'node' } }, + }; + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '0.9.0', + }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail( + config, + requestConsent, + [], + previousConfig, + ); + + expect(requestConsent).toHaveBeenCalledTimes(1); + }); + }); + + describe('parseInstallSource', () => { + it('should parse HTTPS URL as git type', async () => { + const result = await parseInstallSource('https://github.com/owner/repo'); + expect(result.type).toBe('git'); + expect(result.source).toBe('https://github.com/owner/repo'); + }); + + it('should parse HTTP URL as git type', async () => { + const result = await parseInstallSource('http://example.com/repo'); + expect(result.type).toBe('git'); + }); + + it('should parse git@ URL as git type', async () => { + const result = await parseInstallSource('git@github.com:owner/repo.git'); + expect(result.type).toBe('git'); + }); + + it('should parse sso:// URL as git type', async () => { + const result = await parseInstallSource('sso://some/path'); + expect(result.type).toBe('git'); + }); + + it('should parse marketplace URL correctly', async () => { + const result = await parseInstallSource( + 'https://example.com/marketplace:plugin-name', + ); + expect(result.type).toBe('marketplace'); + expect(result.marketplace?.pluginName).toBe('plugin-name'); + }); + + it('should throw for non-existent local path', async () => { + await expect( + parseInstallSource('/nonexistent/path/to/extension'), + ).rejects.toThrow('Install source not found'); + }); + }); +}); diff --git a/packages/core/src/extension/github.test.ts b/packages/core/src/extension/github.test.ts index d135f3e289f..e98e6498a8f 100644 --- a/packages/core/src/extension/github.test.ts +++ b/packages/core/src/extension/github.test.ts @@ -231,6 +231,65 @@ describe('git extension helpers', () => { ); expect(result).toBe(ExtensionUpdateState.ERROR); }); + + it('should return UPDATE_AVAILABLE for local extension with different version', async () => { + const extension = createExtension({ + version: '1.0.0', + installMetadata: { + type: 'local', + source: '/path/to/source', + }, + }); + + const mockManager = { + loadExtensionConfig: vi.fn().mockReturnValue({ + name: 'test', + version: '2.0.0', + }), + } as unknown as ExtensionManager; + + const result = await checkForExtensionUpdate(extension, mockManager); + expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE); + }); + + it('should return UP_TO_DATE for local extension with same version', async () => { + const extension = createExtension({ + version: '1.0.0', + installMetadata: { + type: 'local', + source: '/path/to/source', + }, + }); + + const mockManager = { + loadExtensionConfig: vi.fn().mockReturnValue({ + name: 'test', + version: '1.0.0', + }), + } as unknown as ExtensionManager; + + const result = await checkForExtensionUpdate(extension, mockManager); + expect(result).toBe(ExtensionUpdateState.UP_TO_DATE); + }); + + it('should return NOT_UPDATABLE for local extension when source cannot be loaded', async () => { + const extension = createExtension({ + version: '1.0.0', + installMetadata: { + type: 'local', + source: '/path/to/source', + }, + }); + + const mockManager = { + loadExtensionConfig: vi.fn().mockImplementation(() => { + throw new Error('Cannot load config'); + }), + } as unknown as ExtensionManager; + + const result = await checkForExtensionUpdate(extension, mockManager); + expect(result).toBe(ExtensionUpdateState.NOT_UPDATABLE); + }); }); describe('findReleaseAsset', () => { diff --git a/packages/core/src/extension/github.ts b/packages/core/src/extension/github.ts index 22d7d6f61ea..7cbf796c8ec 100644 --- a/packages/core/src/extension/github.ts +++ b/packages/core/src/extension/github.ts @@ -288,28 +288,32 @@ export async function downloadFromGitHubRelease( // For regular github releases, the repository is put inside of a top level // directory. In this case we should see exactly two file in the destination // dir, the archive and the directory. If we see that, validate that the - // dir has a qwen extension configuration file and then move all files - // from the directory up one level into the destination directory. + // dir has a qwen extension configuration file (or gemini-extension.json + // which will be converted later) and then move all files from the directory + // up one level into the destination directory. const entries = await fs.promises.readdir(destination, { withFileTypes: true, }); if (entries.length === 2) { const lonelyDir = entries.find((entry) => entry.isDirectory()); - if ( - lonelyDir && - fs.existsSync( + if (lonelyDir) { + const hasQwenConfig = fs.existsSync( path.join(destination, lonelyDir.name, EXTENSIONS_CONFIG_FILENAME), - ) - ) { - const dirPathToExtract = path.join(destination, lonelyDir.name); - const extractedDirFiles = await fs.promises.readdir(dirPathToExtract); - for (const file of extractedDirFiles) { - await fs.promises.rename( - path.join(dirPathToExtract, file), - path.join(destination, file), - ); + ); + const hasGeminiConfig = fs.existsSync( + path.join(destination, lonelyDir.name, 'gemini-extension.json'), + ); + if (hasQwenConfig || hasGeminiConfig) { + const dirPathToExtract = path.join(destination, lonelyDir.name); + const extractedDirFiles = await fs.promises.readdir(dirPathToExtract); + for (const file of extractedDirFiles) { + await fs.promises.rename( + path.join(dirPathToExtract, file), + path.join(destination, file), + ); + } + await fs.promises.rmdir(dirPathToExtract); } - await fs.promises.rmdir(dirPathToExtract); } } From f00f76456cc5709bcc21bdf522374abc09d338a6 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Thu, 15 Jan 2026 20:00:09 +0800 Subject: [PATCH 09/30] feat: claude subagents transform --- packages/cli/src/ui/AppContainer.tsx | 2 +- .../subagents/manage/ActionSelectionStep.tsx | 6 +- .../subagents/manage/AgentSelectionStep.tsx | 130 +++++- .../subagents/manage/AgentsManagerDialog.tsx | 6 +- packages/core/src/config/config.ts | 17 +- .../core/src/extension/claude-converter.ts | 409 ++++++++++++++---- .../src/extension/extensionManager.test.ts | 4 + .../core/src/extension/extensionManager.ts | 141 ++++-- .../core/src/extension/gemini-converter.ts | 2 +- packages/core/src/extension/github.ts | 17 +- packages/core/src/extension/marketplace.ts | 198 --------- packages/core/src/skills/skill-load.ts | 148 +++++++ packages/core/src/skills/skill-manager.ts | 56 +-- .../core/src/subagents/subagent-manager.ts | 210 +++++---- 14 files changed, 891 insertions(+), 455 deletions(-) create mode 100644 packages/core/src/skills/skill-load.ts diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 117e3b9eefb..1bd40baa4e7 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -165,7 +165,7 @@ export const AppContainer = (props: AppContainerProps) => { const extensionManager = config.getExtensionManager(); - extensionManager.setRequestConsent((description) => + extensionManager.setRequestConsent(async (description) => requestConsentInteractive(description, addConfirmUpdateExtensionRequest), ); diff --git a/packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx b/packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx index 28393d08aa9..3cf453814ec 100644 --- a/packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx +++ b/packages/cli/src/ui/components/subagents/manage/ActionSelectionStep.tsx @@ -58,7 +58,11 @@ export const ActionSelectionStep = ({ }, ]; - const actions = selectedAgent?.isBuiltin + // Extension-level agents are also read-only (like builtin) + const isReadOnly = + selectedAgent?.isBuiltin || selectedAgent?.level === 'extension'; + + const actions = isReadOnly ? allActions.filter( (action) => action.value === 'view' || action.value === 'back', ) diff --git a/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx b/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx index a3a0c9af419..71d813fe822 100644 --- a/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx +++ b/packages/cli/src/ui/components/subagents/manage/AgentSelectionStep.tsx @@ -12,10 +12,11 @@ import { type SubagentConfig } from '@qwen-code/qwen-code-core'; import { t } from '../../../../i18n/index.js'; interface NavigationState { - currentBlock: 'project' | 'user' | 'builtin'; + currentBlock: 'project' | 'user' | 'builtin' | 'extension'; projectIndex: number; userIndex: number; builtinIndex: number; + extensionIndex: number; } interface AgentSelectionStepProps { @@ -32,6 +33,7 @@ export const AgentSelectionStep = ({ projectIndex: 0, userIndex: 0, builtinIndex: 0, + extensionIndex: 0, }); // Group agents by level @@ -47,6 +49,10 @@ export const AgentSelectionStep = ({ () => availableAgents.filter((agent) => agent.level === 'builtin'), [availableAgents], ); + const extensionAgents = useMemo( + () => availableAgents.filter((agent) => agent.level === 'extension'), + [availableAgents], + ); const projectNames = useMemo( () => new Set(projectAgents.map((agent) => agent.name)), [projectAgents], @@ -60,8 +66,10 @@ export const AgentSelectionStep = ({ setNavigation((prev) => ({ ...prev, currentBlock: 'user' })); } else if (builtinAgents.length > 0) { setNavigation((prev) => ({ ...prev, currentBlock: 'builtin' })); + } else if (extensionAgents.length > 0) { + setNavigation((prev) => ({ ...prev, currentBlock: 'extension' })); } - }, [projectAgents, userAgents, builtinAgents]); + }, [projectAgents, userAgents, builtinAgents, extensionAgents]); // Custom keyboard navigation useKeypress( @@ -87,6 +95,13 @@ export const AgentSelectionStep = ({ currentBlock: 'user', userIndex: userAgents.length - 1, }; + } else if (extensionAgents.length > 0) { + // Move to last item in extension block + return { + ...prev, + currentBlock: 'extension', + extensionIndex: extensionAgents.length - 1, + }; } else { // Wrap to last item in project block return { ...prev, projectIndex: projectAgents.length - 1 }; @@ -108,11 +123,18 @@ export const AgentSelectionStep = ({ currentBlock: 'builtin', builtinIndex: builtinAgents.length - 1, }; + } else if (extensionAgents.length > 0) { + // Move to last item in extension block + return { + ...prev, + currentBlock: 'extension', + extensionIndex: extensionAgents.length - 1, + }; } else { // Wrap to last item in user block return { ...prev, userIndex: userAgents.length - 1 }; } - } else { + } else if (prev.currentBlock === 'builtin') { // builtin block if (prev.builtinIndex > 0) { return { ...prev, builtinIndex: prev.builtinIndex - 1 }; @@ -130,10 +152,46 @@ export const AgentSelectionStep = ({ currentBlock: 'project', projectIndex: projectAgents.length - 1, }; + } else if (extensionAgents.length > 0) { + // Move to last item in extension block + return { + ...prev, + currentBlock: 'extension', + extensionIndex: extensionAgents.length - 1, + }; } else { // Wrap to last item in builtin block return { ...prev, builtinIndex: builtinAgents.length - 1 }; } + } else { + // extension block + if (prev.extensionIndex > 0) { + return { ...prev, extensionIndex: prev.extensionIndex - 1 }; + } else if (userAgents.length > 0) { + // Move to last item in user block + return { + ...prev, + currentBlock: 'user', + userIndex: userAgents.length - 1, + }; + } else if (projectAgents.length > 0) { + // Move to last item in project block + return { + ...prev, + currentBlock: 'project', + projectIndex: projectAgents.length - 1, + }; + } else if (builtinAgents.length > 0) { + // Move to last item in builtin block + return { + ...prev, + currentBlock: 'builtin', + builtinIndex: builtinAgents.length - 1, + }; + } else { + // Wrap to last item in extension block + return { ...prev, extensionIndex: extensionAgents.length - 1 }; + } } }); } else if (name === 'down' || name === 'j') { @@ -147,6 +205,9 @@ export const AgentSelectionStep = ({ } else if (builtinAgents.length > 0) { // Move to first item in builtin block return { ...prev, currentBlock: 'builtin', builtinIndex: 0 }; + } else if (extensionAgents.length > 0) { + // Move to first item in extension block + return { ...prev, currentBlock: 'extension', extensionIndex: 0 }; } else { // Wrap to first item in project block return { ...prev, projectIndex: 0 }; @@ -157,6 +218,9 @@ export const AgentSelectionStep = ({ } else if (builtinAgents.length > 0) { // Move to first item in builtin block return { ...prev, currentBlock: 'builtin', builtinIndex: 0 }; + } else if (extensionAgents.length > 0) { + // Move to first item in extension block + return { ...prev, currentBlock: 'extension', extensionIndex: 0 }; } else if (projectAgents.length > 0) { // Move to first item in project block return { ...prev, currentBlock: 'project', projectIndex: 0 }; @@ -164,10 +228,13 @@ export const AgentSelectionStep = ({ // Wrap to first item in user block return { ...prev, userIndex: 0 }; } - } else { + } else if (prev.currentBlock === 'builtin') { // builtin block if (prev.builtinIndex < builtinAgents.length - 1) { return { ...prev, builtinIndex: prev.builtinIndex + 1 }; + } else if (extensionAgents.length > 0) { + // Move to first item in extension block + return { ...prev, currentBlock: 'extension', extensionIndex: 0 }; } else if (projectAgents.length > 0) { // Move to first item in project block return { ...prev, currentBlock: 'project', projectIndex: 0 }; @@ -178,6 +245,23 @@ export const AgentSelectionStep = ({ // Wrap to first item in builtin block return { ...prev, builtinIndex: 0 }; } + } else { + // extension block + if (prev.extensionIndex < extensionAgents.length - 1) { + return { ...prev, extensionIndex: prev.extensionIndex + 1 }; + } else if (projectAgents.length > 0) { + // Move to first item in project block + return { ...prev, currentBlock: 'project', projectIndex: 0 }; + } else if (userAgents.length > 0) { + // Move to first item in user block + return { ...prev, currentBlock: 'user', userIndex: 0 }; + } else if (builtinAgents.length > 0) { + // Move to first item in builtin block + return { ...prev, currentBlock: 'builtin', builtinIndex: 0 }; + } else { + // Wrap to first item in extension block + return { ...prev, extensionIndex: 0 }; + } } }); } else if (name === 'return' || name === 'space') { @@ -188,11 +272,17 @@ export const AgentSelectionStep = ({ } else if (navigation.currentBlock === 'user') { // User agents come after project agents in the availableAgents array globalIndex = projectAgents.length + navigation.userIndex; - } else { - // builtin block + } else if (navigation.currentBlock === 'builtin') { // Builtin agents come after project and user agents in the availableAgents array globalIndex = projectAgents.length + userAgents.length + navigation.builtinIndex; + } else { + // Extension agents come after project, user, and builtin agents + globalIndex = + projectAgents.length + + userAgents.length + + builtinAgents.length + + navigation.extensionIndex; } if (globalIndex >= 0 && globalIndex < availableAgents.length) { @@ -258,7 +348,8 @@ export const AgentSelectionStep = ({ const enabledAgentsCount = projectAgents.length + userAgents.filter((agent) => !projectNames.has(agent.name)).length + - builtinAgents.length; + builtinAgents.length + + extensionAgents.length; return ( @@ -305,7 +396,10 @@ export const AgentSelectionStep = ({ {/* Built-in Agents */} {builtinAgents.length > 0 && ( - + 0 ? 1 : 0} + > {t('Built-in Agents')} @@ -320,10 +414,28 @@ export const AgentSelectionStep = ({ )} + {/* Extension Agents */} + {extensionAgents.length > 0 && ( + + + {t('Extension Agents')} + + + {extensionAgents.map((agent, index) => { + const isSelected = + navigation.currentBlock === 'extension' && + navigation.extensionIndex === index; + return renderAgentItem(agent, index, isSelected); + })} + + + )} + {/* Agent count summary */} {(projectAgents.length > 0 || userAgents.length > 0 || - builtinAgents.length > 0) && ( + builtinAgents.length > 0 || + extensionAgents.length > 0) && ( {t('Using: {{count}} agents', { diff --git a/packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx b/packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx index f496d6bc501..f2a5f02e2ef 100644 --- a/packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx +++ b/packages/cli/src/ui/components/subagents/manage/AgentsManagerDialog.tsx @@ -95,7 +95,11 @@ export function AgentsManagerDialog({ try { const subagentManager = config.getSubagentManager(); - await subagentManager.deleteSubagent(agent.name, agent.level); + await subagentManager.deleteSubagent( + agent.name, + agent.level, + agent.extensionName, + ); // Reload agents to get updated state await loadAgents(); diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 59f6dde76f5..ee1c560781f 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -474,8 +474,6 @@ export class Config { private readonly listExtensions: boolean; private readonly overrideExtensions?: string[]; - fallbackModelHandler?: FallbackModelHandler; - private quotaErrorOccurred: boolean = false; private readonly summarizeToolOutput: | Record | undefined; @@ -663,6 +661,11 @@ export class Config { this.chatRecordingService = this.chatRecordingEnabled ? new ChatRecordingService(this) : undefined; + this.extensionManager = new ExtensionManager({ + workspaceDir: this.targetDir, + enabledExtensionOverrides: this.overrideExtensions, + isWorkspaceTrusted: this.isTrustedFolder(), + }); } /** @@ -681,6 +684,9 @@ export class Config { await this.getGitService(); } this.promptRegistry = new PromptRegistry(); + this.extensionManager.setConfig(this); + await this.extensionManager.refreshCache(); + this.subagentManager = new SubagentManager(this); this.skillManager = new SkillManager(this); await this.skillManager.startWatching(); @@ -690,13 +696,6 @@ export class Config { this.subagentManager.loadSessionSubagents(this.sessionSubagents); } - this.extensionManager = new ExtensionManager({ - workspaceDir: this.targetDir, - enabledExtensionOverrides: this.overrideExtensions, - config: this, - isWorkspaceTrusted: this.isTrustedFolder(), - }); - await this.extensionManager.refreshCache(); const activeExtensions = await this.extensionManager .getLoadedExtensions() diff --git a/packages/core/src/extension/claude-converter.ts b/packages/core/src/extension/claude-converter.ts index c5833286c5a..1cbc726c60d 100644 --- a/packages/core/src/extension/claude-converter.ts +++ b/packages/core/src/extension/claude-converter.ts @@ -12,7 +12,17 @@ import * as path from 'node:path'; import { glob } from 'glob'; import type { ExtensionConfig } from './extensionManager.js'; import { ExtensionStorage } from './storage.js'; -import type { MCPServerConfig } from '../config/config.js'; +import type { + ExtensionInstallMetadata, + MCPServerConfig, +} from '../config/config.js'; +import { cloneFromGit, downloadFromGitHubRelease } from './github.js'; +import { createHash } from 'node:crypto'; +import { copyDirectory } from './gemini-converter.js'; +import { + parse as parseYaml, + stringify as stringifyYaml, +} from '../utils/yaml-parser.js'; export interface ClaudePluginConfig { name: string; @@ -32,6 +42,33 @@ export interface ClaudePluginConfig { lspServers?: string; } +/** + * Claude Code subagent configuration format. + * Based on https://code.claude.com/docs/en/sub-agents + */ +export interface ClaudeAgentConfig { + /** Unique identifier using lowercase letters and hyphens */ + name: string; + /** When Claude should delegate to this subagent */ + description: string; + /** Tools the subagent can use. Inherits all tools if omitted */ + tools?: string[]; + /** Tools to deny, removed from inherited or specified list */ + disallowedTools?: string[]; + /** Model to use: sonnet, opus, haiku, or inherit */ + model?: string; + /** Permission mode: default, acceptEdits, dontAsk, bypassPermissions, or plan */ + permissionMode?: string; + /** Skills to load into the subagent's context at startup */ + skills?: string[]; + /** Hooks configuration */ + hooks?: unknown; + /** System prompt content */ + systemPrompt?: string; + /** subagent color */ + color?: string; +} + export type ClaudePluginSource = | { source: 'github'; repo: string } | { source: 'url'; url: string }; @@ -50,6 +87,200 @@ export interface ClaudeMarketplaceConfig { metadata?: { description?: string; version?: string; pluginRoot?: string }; } +const CLAUDE_TOOLS_MAPPING: Record = { + AskUserQuestion: 'None', + Bash: 'Shell', + BashOutput: 'None', + Edit: 'Edit', + ExitPlanMode: 'ExitPlanMode', + Glob: 'Glob', + Grep: 'Grep', + KillShell: 'None', + NotebookEdit: 'None', + Read: ['ReadFile', 'ReadManyFiles'], + Skill: 'Skill', + Task: 'Task', + TodoWrite: 'TodoWrite', + WebFetch: 'WebFetch', + WebSearch: 'WebSearch', + Write: 'WriteFile', + LS: 'ListFiles', +}; + +const claudeBuildInToolsTransform = (tools: string[]): string[] => { + const transformedTools: string[] = []; + tools.forEach((tool) => { + if (!CLAUDE_TOOLS_MAPPING[tool]) { + transformedTools.push(tool); + } else { + if (CLAUDE_TOOLS_MAPPING[tool] === 'None') { + return; + } else if (Array.isArray(CLAUDE_TOOLS_MAPPING[tool])) { + transformedTools.push(...CLAUDE_TOOLS_MAPPING[tool]); + } else { + transformedTools.push(CLAUDE_TOOLS_MAPPING[tool]); + } + } + }); + return transformedTools; +}; + +/** + * Parses a value that can be either a comma-separated string or an array. + * Claude agent config can have tools like 'Glob, Grep, Read' or ['Glob', 'Grep', 'Read'] + * @param value The value to parse + * @returns Array of strings or undefined + */ +function parseStringOrArray(value: unknown): string[] | undefined { + if (value === undefined || value === null) { + return undefined; + } + if (Array.isArray(value)) { + return value.map(String); + } + if (typeof value === 'string') { + // Split by comma and trim whitespace + return value + .split(',') + .map((s) => s.trim()) + .filter((s) => s.length > 0); + } + return undefined; +} + +/** + * Converts a Claude agent config to Qwen Code subagent format. + * @param claudeAgent Claude agent configuration + * @returns Converted agent config compatible with Qwen Code SubagentConfig + */ +export function convertClaudeAgentConfig( + claudeAgent: ClaudeAgentConfig, +): Record { + // Base config with required fields + const qwenAgent: Record = { + name: claudeAgent.name, + description: claudeAgent.description, + }; + + if (claudeAgent.color) { + qwenAgent['color'] = claudeAgent.color; + } + + // Convert system prompt if present + if (claudeAgent.systemPrompt) { + qwenAgent['systemPrompt'] = claudeAgent.systemPrompt; + } + + // Convert tools using claudeBuildInToolsTransform + if (claudeAgent.tools && claudeAgent.tools.length > 0) { + qwenAgent['tools'] = claudeBuildInToolsTransform(claudeAgent.tools); + } + + // Convert model to modelConfig + if (claudeAgent.model) { + // Map Claude model names to Qwen model config + // Claude uses: sonnet, opus, haiku, inherit + // We preserve the model name for now, the actual mapping will be handled at runtime + qwenAgent['modelConfig'] = { + model: claudeAgent.model === 'inherit' ? undefined : claudeAgent.model, + }; + } + + // Preserve unsupported fields as-is for potential future compatibility + // These fields are not supported by Qwen Code SubagentConfig but we keep them + if (claudeAgent.permissionMode) { + qwenAgent['permissionMode'] = claudeAgent.permissionMode; + } + if (claudeAgent.hooks) { + qwenAgent['hooks'] = claudeAgent.hooks; + } + if (claudeAgent.skills && claudeAgent.skills.length > 0) { + qwenAgent['skills'] = claudeAgent.skills; + } + if (claudeAgent.disallowedTools && claudeAgent.disallowedTools.length > 0) { + qwenAgent['disallowedTools'] = claudeAgent.disallowedTools; + } + + return qwenAgent; +} + +/** + * Converts all agent files in a directory from Claude format to Qwen format. + * Parses the YAML frontmatter, converts the configuration, and writes back. + * @param agentsDir Directory containing agent markdown files + */ +async function convertAgentFiles(agentsDir: string): Promise { + if (!fs.existsSync(agentsDir)) { + return; + } + + const files = await fs.promises.readdir(agentsDir); + + for (const file of files) { + if (!file.endsWith('.md')) continue; + + const filePath = path.join(agentsDir, file); + + try { + const content = await fs.promises.readFile(filePath, 'utf-8'); + + // Parse frontmatter + const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/; + const match = content.match(frontmatterRegex); + + if (!match) { + // No frontmatter, skip this file + continue; + } + + const [, frontmatterYaml, body] = match; + const frontmatter = parseYaml(frontmatterYaml) as Record; + + // Build Claude agent config from frontmatter + // Note: Claude tools/disallowedTools/skills can be comma-separated strings like 'Glob, Grep, Read' + const claudeAgent: ClaudeAgentConfig = { + name: String(frontmatter['name'] || ''), + description: String(frontmatter['description'] || ''), + tools: parseStringOrArray(frontmatter['tools']), + disallowedTools: parseStringOrArray(frontmatter['disallowedTools']), + model: frontmatter['model'] as string | undefined, + permissionMode: frontmatter['permissionMode'] as string | undefined, + skills: parseStringOrArray(frontmatter['skills']), + hooks: frontmatter['hooks'], + color: frontmatter['color'] as string | undefined, + systemPrompt: body.trim(), + }; + + // Convert to Qwen format + const qwenAgent = convertClaudeAgentConfig(claudeAgent); + + // Build new frontmatter (excluding systemPrompt as it goes in body) + const newFrontmatter: Record = {}; + for (const [key, value] of Object.entries(qwenAgent)) { + if (key !== 'systemPrompt' && value !== undefined) { + newFrontmatter[key] = value; + } + } + + // Write converted content back + const newYaml = stringifyYaml(newFrontmatter); + const systemPrompt = (qwenAgent['systemPrompt'] as string) || body.trim(); + const newContent = `--- +${newYaml} +--- + +${systemPrompt} +`; + + await fs.promises.writeFile(filePath, newContent, 'utf-8'); + } catch (error) { + console.warn( + `[Claude Converter] Failed to convert agent file ${filePath}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } +} + /** * Converts a Claude plugin config to Qwen Code format. * @param claudeConfig Claude plugin configuration @@ -108,14 +339,10 @@ export function convertClaudeToQwenConfig( * 2. Commands, skills, and agents collected to respective folders * 3. MCP servers resolved from JSON files if needed * 4. All other files preserved - * - * @param extensionDir Path to the Claude plugin directory - * @param marketplace Marketplace information for loading marketplace.json - * @returns Object containing converted config and the temporary directory path */ export async function convertClaudePluginPackage( extensionDir: string, - marketplace: { marketplaceSource: string; pluginName: string }, + pluginName: string, ): Promise<{ config: ExtensionConfig; convertedDir: string }> { // Step 1: Load marketplace.json const marketplaceJsonPath = path.join( @@ -135,46 +362,27 @@ export async function convertClaudePluginPackage( // Find the target plugin in marketplace const marketplacePlugin = marketplaceConfig.plugins.find( - (p) => p.name === marketplace.pluginName, + (p) => p.name === pluginName, ); if (!marketplacePlugin) { - throw new Error( - `Plugin ${marketplace.pluginName} not found in marketplace.json`, - ); + throw new Error(`Plugin ${pluginName} not found in marketplace.json`); } // Step 2: Resolve plugin source directory based on source field - const source = marketplacePlugin.source; - let pluginSourceDir: string; + const pluginDir = path.join( + extensionDir, + `plugin${createHash('sha256').update(`${extensionDir}/${pluginName}`).digest('hex')}`, + ); + await fs.promises.mkdir(pluginDir, { recursive: true }); - if (typeof source === 'string') { - // Check if it's a URL (online path) - if (source.startsWith('http://') || source.startsWith('https://')) { - throw new Error( - `Online plugin sources are not supported in convertClaudePluginPackage. ` + - `Plugin ${marketplace.pluginName} has source: ${source}. ` + - `This should be downloaded and resolved before calling this function.`, - ); - } - // Relative path within marketplace directory - const marketplaceDir = marketplaceConfig.metadata?.pluginRoot - ? path.join(extensionDir, marketplaceConfig.metadata.pluginRoot) - : extensionDir; - pluginSourceDir = path.join(marketplaceDir, source); - } else if (source.source === 'github' || source.source === 'url') { - throw new Error( - `Online plugin sources (github/url) are not supported in convertClaudePluginPackage. ` + - `Plugin ${marketplace.pluginName} has source type: ${source.source}. ` + - `This should be downloaded and resolved before calling this function.`, - ); - } else { - throw new Error( - `Unsupported plugin source type for ${marketplace.pluginName}: ${JSON.stringify(source)}`, - ); - } + const pluginSource = await resolvePluginSource( + marketplacePlugin, + extensionDir, + pluginDir, + ); - if (!fs.existsSync(pluginSourceDir)) { - throw new Error(`Plugin source directory not found: ${pluginSourceDir}`); + if (!fs.existsSync(pluginSource)) { + throw new Error(`Plugin source directory not found: ${pluginSource}`); } // Step 3: Load and merge plugin.json if exists (based on strict mode) @@ -183,7 +391,7 @@ export async function convertClaudePluginPackage( if (strict) { const pluginJsonPath = path.join( - pluginSourceDir, + pluginSource, '.claude-plugin', 'plugin.json', ); @@ -201,7 +409,7 @@ export async function convertClaudePluginPackage( if (mergedConfig.mcpServers && typeof mergedConfig.mcpServers === 'string') { const mcpServersPath = path.isAbsolute(mergedConfig.mcpServers) ? mergedConfig.mcpServers - : path.join(pluginSourceDir, mergedConfig.mcpServers); + : path.join(pluginSource, mergedConfig.mcpServers); if (fs.existsSync(mcpServersPath)) { try { @@ -223,14 +431,14 @@ export async function convertClaudePluginPackage( try { // Step 6: Copy plugin files to temporary directory - await copyDirectory(pluginSourceDir, tmpDir); + await copyDirectory(pluginSource, tmpDir); // Step 7: Collect commands to commands folder if (mergedConfig.commands) { const commandsDestDir = path.join(tmpDir, 'commands'); await collectResources( mergedConfig.commands, - pluginSourceDir, + pluginSource, commandsDestDir, ); } @@ -238,22 +446,16 @@ export async function convertClaudePluginPackage( // Step 8: Collect skills to skills folder if (mergedConfig.skills) { const skillsDestDir = path.join(tmpDir, 'skills'); - await collectResources( - mergedConfig.skills, - pluginSourceDir, - skillsDestDir, - ); + await collectResources(mergedConfig.skills, pluginSource, skillsDestDir); } // Step 9: Collect agents to agents folder + const agentsDestDir = path.join(tmpDir, 'agents'); if (mergedConfig.agents) { - const agentsDestDir = path.join(tmpDir, 'agents'); - await collectResources( - mergedConfig.agents, - pluginSourceDir, - agentsDestDir, - ); + await collectResources(mergedConfig.agents, pluginSource, agentsDestDir); } + // Step 9.1: Convert collected agent files from Claude format to Qwen format + await convertAgentFiles(agentsDestDir); // Step 10: Convert to Qwen format config const qwenConfig = convertClaudeToQwenConfig(mergedConfig); @@ -281,34 +483,6 @@ export async function convertClaudePluginPackage( } } -/** - * Recursively copies a directory and its contents. - * @param source Source directory path - * @param destination Destination directory path - */ -async function copyDirectory( - source: string, - destination: string, -): Promise { - // Create destination directory if it doesn't exist - if (!fs.existsSync(destination)) { - fs.mkdirSync(destination, { recursive: true }); - } - - const entries = fs.readdirSync(source, { withFileTypes: true }); - - for (const entry of entries) { - const sourcePath = path.join(source, entry.name); - const destPath = path.join(destination, entry.name); - - if (entry.isDirectory()) { - await copyDirectory(sourcePath, destPath); - } else { - fs.copyFileSync(sourcePath, destPath); - } - } -} - /** * Collects resources (commands, skills, agents) to a destination folder. * If a resource is already in the destination folder, it will be skipped. @@ -498,3 +672,74 @@ export function isClaudePluginConfig( return true; } + +/** + * Resolve plugin source from marketplace plugin configuration. + * Returns the absolute path to the plugin source directory. + */ +async function resolvePluginSource( + pluginConfig: ClaudeMarketplacePluginConfig, + marketplaceDir: string, + pluginDir: string, +): Promise { + const source = pluginConfig.source; + + // Handle string source (relative path or URL) + if (typeof source === 'string') { + // Check if it's a URL + if (source.startsWith('http://') || source.startsWith('https://')) { + // Download from URL + const installMetadata: ExtensionInstallMetadata = { + source, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + // Relative path within marketplace + const pluginRoot = marketplaceDir; + const sourcePath = path.join(pluginRoot, source); + + if (!fs.existsSync(sourcePath)) { + throw new Error(`Plugin source not found at ${sourcePath}`); + } + + // Copy to plugin directory + await fs.promises.cp(sourcePath, pluginDir, { recursive: true }); + return pluginDir; + } + + // Handle object source (github or url) + if (source.source === 'github') { + const installMetadata: ExtensionInstallMetadata = { + source: `https://github.com/${source.repo}`, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + if (source.source === 'url') { + const installMetadata: ExtensionInstallMetadata = { + source: source.url, + type: 'git', + }; + try { + await downloadFromGitHubRelease(installMetadata, pluginDir); + } catch { + await cloneFromGit(installMetadata, pluginDir); + } + return pluginDir; + } + + throw new Error(`Unsupported plugin source type: ${JSON.stringify(source)}`); +} diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 72197cda7bb..3d33a30f869 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -764,6 +764,8 @@ describe('extensionManager utility functions', () => { config, requestConsent, [], + [], + [], previousConfig, ); @@ -786,6 +788,8 @@ describe('extensionManager utility functions', () => { config, requestConsent, [], + [], + [], previousConfig, ); diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 1fab09498e2..d33a4ec6720 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -37,10 +37,7 @@ import { import type { LoadExtensionContext } from './variableSchema.js'; import { Override, type AllExtensionsEnablementConfig } from './override.js'; import chalk from 'chalk'; -import { - installFromMarketplace, - parseMarketplaceSource, -} from './marketplace.js'; +import { parseMarketplaceSource } from './marketplace.js'; import { isGeminiExtensionConfig, convertGeminiExtensionPackage, @@ -63,6 +60,9 @@ import { ExtensionUpdateEvent, } from '../telemetry/types.js'; import { stat } from 'node:fs/promises'; +import { loadSkillsFromDir } from '../skills/skill-load.js'; +import { convertClaudePluginPackage } from './claude-converter.js'; +import { loadSubagentFromDir } from '../subagents/subagent-manager.js'; // ============================================================================ // Types and Interfaces @@ -82,13 +82,14 @@ export interface Extension { isActive: boolean; path: string; config: ExtensionConfig; - installMetadata?: ExtensionInstallMetadata; + mcpServers?: Record; contextFiles: string[]; excludeTools?: string[]; settings?: ExtensionSetting[]; resolvedSettings?: ResolvedExtensionSetting[]; + commands?: string[]; skills?: SkillConfig[]; agents?: SubagentConfig[]; } @@ -243,7 +244,10 @@ async function loadCommandsFromDir( } } -async function convertGeminiOrClaudeExtension(extensionDir: string) { +async function convertGeminiOrClaudeExtension( + extensionDir: string, + pluginName?: string, +) { let newExtensionDir = extensionDir; const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); if (fs.existsSync(configFilePath)) { @@ -251,6 +255,10 @@ async function convertGeminiOrClaudeExtension(extensionDir: string) { } else if (isGeminiExtensionConfig(extensionDir)) { newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)) .convertedDir; + } else if (pluginName) { + newExtensionDir = ( + await convertClaudePluginPackage(extensionDir, pluginName) + ).convertedDir; } // Claude plugin conversion not yet implemented return newExtensionDir; @@ -298,6 +306,10 @@ export class ExtensionManager { this.isWorkspaceTrusted = options.isWorkspaceTrusted; } + setConfig(config: Config): void { + this.config = config; + } + setRequestConsent( requestConsent: (consent: string) => Promise, ): void { @@ -622,20 +634,23 @@ export class ExtensionManager { ); } + extension.commands = await loadCommandsFromDir( + `${effectiveExtensionPath}/commands`, + extension.name, + ); + extension.contextFiles = getContextFileNames(config) .map((contextFileName) => path.join(effectiveExtensionPath, contextFileName), ) .filter((contextFilePath) => fs.existsSync(contextFilePath)); - if (this.config) { - extension.skills = await this.config - .getSkillManager() - .loadSkillsFromDir(effectiveExtensionPath, 'extension'); - extension.agents = await this.config - .getSubagentManager() - .loadSubagentFromDir(effectiveExtensionPath, 'extension'); - } + extension.skills = await loadSkillsFromDir( + `${effectiveExtensionPath}/skills`, + ); + extension.agents = await loadSubagentFromDir( + `${effectiveExtensionPath}/agents`, + ); return extension; } catch (e) { @@ -738,6 +753,7 @@ export class ExtensionManager { } let tempDir: string | undefined; + let claudePluginName: string | undefined; // Handle marketplace installation if (installMetadata.type === 'marketplace') { @@ -751,16 +767,20 @@ export class ExtensionManager { } tempDir = await ExtensionStorage.createTmpDir(); - const marketplaceResult = await installFromMarketplace({ - marketplaceUrl: marketplaceParsed.marketplaceSource, - pluginName: marketplaceParsed.pluginName, - tempDir, - requestConsent: requestConsent || this.requestConsent, - }); - - newExtensionConfig = marketplaceResult.config; - localSourcePath = marketplaceResult.sourcePath; - installMetadata = marketplaceResult.installMetadata; + try { + await downloadFromGitHubRelease( + { + source: marketplaceParsed.marketplaceSource, + type: 'git', + }, + tempDir, + ); + } catch (_error) { + await cloneFromGit(installMetadata, tempDir); + installMetadata.type = 'git'; + } + localSourcePath = tempDir; + claudePluginName = marketplaceParsed.pluginName; } else if ( installMetadata.type === 'git' || installMetadata.type === 'github-release' @@ -788,13 +808,14 @@ export class ExtensionManager { } try { - localSourcePath = await convertGeminiOrClaudeExtension(localSourcePath); - if (!newExtensionConfig) { - newExtensionConfig = this.loadExtensionConfig({ - extensionDir: localSourcePath, - workspaceDir: currentDir, - }); - } + localSourcePath = await convertGeminiOrClaudeExtension( + localSourcePath, + claudePluginName, + ); + newExtensionConfig = this.loadExtensionConfig({ + extensionDir: localSourcePath, + workspaceDir: currentDir, + }); if (isUpdate && installMetadata.autoUpdate) { const oldSettings = new Set( @@ -833,12 +854,24 @@ export class ExtensionManager { `${localSourcePath}/commands`, newExtensionConfig.name, ); + const previousCommands = previous?.commands ?? []; + + const skills = await loadSkillsFromDir(`${localSourcePath}/skills`); + const previousSkills = previous?.skills ?? []; + + const agents = await loadSubagentFromDir(`${localSourcePath}/agents`); + const previousAgents = previous?.agents ?? []; await maybeRequestConsentOrFail( newExtensionConfig, requestConsent || this.requestConsent, commands, + skills, + agents, previousExtensionConfig, + previousCommands, + previousSkills, + previousAgents, ); const extensionStorage = new ExtensionStorage(newExtensionName); @@ -873,7 +906,8 @@ export class ExtensionManager { if ( installMetadata.type === 'local' || installMetadata.type === 'git' || - installMetadata.type === 'github-release' + installMetadata.type === 'github-release' || + installMetadata.type === 'marketplace' ) { await copyExtension(localSourcePath, destinationPath); } @@ -1041,6 +1075,12 @@ export class ExtensionManager { output += `\n ${contextFile}`; }); } + if (extension.commands && extension.commands.length > 0) { + output += `\n Commands:`; + extension.commands.forEach((command) => { + output += `\n /${command}`; + }); + } if (extension.config.mcpServers) { output += `\n MCP servers:`; Object.keys(extension.config.mcpServers).forEach((key) => { @@ -1188,6 +1228,12 @@ export class ExtensionManager { ) ).filter((updateInfo) => !!updateInfo); } + + async refreshMemory(): Promise { + if (!this.config) return; + this.config.getSkillManager().refreshCache(); + this.config.getSubagentManager().refreshCache(); + } } export async function copyExtension( @@ -1234,7 +1280,9 @@ export function validateName(name: string) { */ export function extensionConsentString( extensionConfig: ExtensionConfig, - commands?: string[], + commands: string[] = [], + skills: SkillConfig[] = [], + subagents: SubagentConfig[] = [], ): string { const output: string[] = []; const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); @@ -1268,6 +1316,18 @@ export function extensionConsentString( `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, ); } + if (skills.length > 0) { + output.push('This extension will install the following skills:'); + for (const skill of skills) { + output.push(` * ${chalk.bold(skill.name)}: ${skill.description}`); + } + } + if (subagents.length > 0) { + output.push('This extension will install the following subagents:'); + for (const subagent of subagents) { + output.push(` * ${chalk.bold(subagent.name)}: ${subagent.description}`); + } + } return output.join('\n'); } @@ -1284,12 +1344,25 @@ export async function maybeRequestConsentOrFail( extensionConfig: ExtensionConfig, requestConsent: (consent: string) => Promise, commands: string[], + skills: SkillConfig[] = [], + subagents: SubagentConfig[] = [], previousExtensionConfig?: ExtensionConfig, + previousCommands: string[] = [], + previousSkills: SkillConfig[] = [], + previousSubagents: SubagentConfig[] = [], ) { - const extensionConsent = extensionConsentString(extensionConfig, commands); + const extensionConsent = extensionConsentString( + extensionConfig, + commands, + skills, + subagents, + ); if (previousExtensionConfig) { const previousExtensionConsent = extensionConsentString( previousExtensionConfig, + previousCommands, + previousSkills, + previousSubagents, ); if (previousExtensionConsent === extensionConsent) { return; diff --git a/packages/core/src/extension/gemini-converter.ts b/packages/core/src/extension/gemini-converter.ts index 7d3c4488307..c3dee4966fb 100644 --- a/packages/core/src/extension/gemini-converter.ts +++ b/packages/core/src/extension/gemini-converter.ts @@ -111,7 +111,7 @@ export async function convertGeminiExtensionPackage( * @param source Source directory path * @param destination Destination directory path */ -async function copyDirectory( +export async function copyDirectory( source: string, destination: string, ): Promise { diff --git a/packages/core/src/extension/github.ts b/packages/core/src/extension/github.ts index 7cbf796c8ec..a89c565b87d 100644 --- a/packages/core/src/extension/github.ts +++ b/packages/core/src/extension/github.ts @@ -303,7 +303,22 @@ export async function downloadFromGitHubRelease( const hasGeminiConfig = fs.existsSync( path.join(destination, lonelyDir.name, 'gemini-extension.json'), ); - if (hasQwenConfig || hasGeminiConfig) { + const hasMarketplaceConfig = fs.existsSync( + path.join( + destination, + lonelyDir.name, + '.claude-plugin/marketplace.json', + ), + ); + const hasClaudePluginConfig = fs.existsSync( + path.join(destination, lonelyDir.name, '.claude-plugin/plugin.json'), + ); + if ( + hasQwenConfig || + hasGeminiConfig || + hasMarketplaceConfig || + hasClaudePluginConfig + ) { const dirPathToExtract = path.join(destination, lonelyDir.name); const extractedDirFiles = await fs.promises.readdir(dirPathToExtract); for (const file of extractedDirFiles) { diff --git a/packages/core/src/extension/marketplace.ts b/packages/core/src/extension/marketplace.ts index ab3351546e4..35b472683ab 100644 --- a/packages/core/src/extension/marketplace.ts +++ b/packages/core/src/extension/marketplace.ts @@ -11,17 +11,7 @@ * Example: https://github.com/example/marketplace:my-plugin */ -import * as fs from 'node:fs'; -import * as path from 'node:path'; import type { ExtensionConfig } from './extensionManager.js'; -import { - convertClaudeToQwenConfig, - mergeClaudeConfigs, - type ClaudeMarketplaceConfig, - type ClaudeMarketplacePluginConfig, - type ClaudePluginConfig, -} from './claude-converter.js'; -import { cloneFromGit, downloadFromGitHubRelease } from './github.js'; import type { ExtensionInstallMetadata } from '../config/config.js'; export interface MarketplaceInstallOptions { @@ -69,191 +59,3 @@ export function parseMarketplaceSource(source: string): { return { marketplaceSource, pluginName }; } - -/** - * Install an extension from a Claude marketplace. - * - * Process: - * 1. Download marketplace repository - * 2. Parse marketplace.json - * 3. Find the specified plugin - * 4. Download/copy plugin source - * 5. Merge configurations (if strict mode) - * 6. Convert to Qwen format - */ -export async function installFromMarketplace( - options: MarketplaceInstallOptions, -): Promise { - const { - marketplaceUrl, - pluginName, - tempDir, - requestConsent: _requestConsent, - } = options; - - // Step 1: Download marketplace repository - const marketplaceDir = path.join(tempDir, 'marketplace'); - await fs.promises.mkdir(marketplaceDir, { recursive: true }); - - console.log(`Downloading marketplace from ${marketplaceUrl}...`); - const installMetadata: ExtensionInstallMetadata = { - source: marketplaceUrl, - type: 'git', - }; - - try { - await downloadFromGitHubRelease(installMetadata, marketplaceDir); - } catch { - await cloneFromGit(installMetadata, marketplaceDir); - } - - // Step 2: Parse marketplace.json - const marketplaceConfigPath = path.join(marketplaceDir, 'marketplace.json'); - if (!fs.existsSync(marketplaceConfigPath)) { - throw new Error( - `Marketplace configuration not found at ${marketplaceConfigPath}`, - ); - } - - const marketplaceConfigContent = await fs.promises.readFile( - marketplaceConfigPath, - 'utf-8', - ); - const marketplaceConfig: ClaudeMarketplaceConfig = JSON.parse( - marketplaceConfigContent, - ); - - // Step 3: Find the plugin - const pluginConfig = marketplaceConfig.plugins.find( - (p) => p.name.toLowerCase() === pluginName.toLowerCase(), - ); - - if (!pluginConfig) { - throw new Error( - `Plugin "${pluginName}" not found in marketplace. Available plugins: ${marketplaceConfig.plugins.map((p) => p.name).join(', ')}`, - ); - } - - // Step 4: Download/copy plugin source - const pluginDir = path.join(tempDir, 'plugin'); - await fs.promises.mkdir(pluginDir, { recursive: true }); - - const pluginSource = await resolvePluginSource( - pluginConfig, - marketplaceDir, - pluginDir, - ); - - // Step 5: Merge configurations (if strict mode) - let finalPluginConfig: ClaudePluginConfig; - const strict = pluginConfig.strict ?? true; - - if (strict) { - // Read plugin.json from plugin source - const pluginJsonPath = path.join( - pluginSource, - '.claude-plugin', - 'plugin.json', - ); - if (!fs.existsSync(pluginJsonPath)) { - throw new Error( - `Strict mode requires plugin.json at ${pluginJsonPath}, but file not found`, - ); - } - - const pluginJsonContent = await fs.promises.readFile( - pluginJsonPath, - 'utf-8', - ); - const basePluginConfig: ClaudePluginConfig = JSON.parse(pluginJsonContent); - - // Merge marketplace config with plugin config - finalPluginConfig = mergeClaudeConfigs(pluginConfig, basePluginConfig); - } else { - // Use marketplace config directly - finalPluginConfig = pluginConfig; - } - - // Step 6: Convert to Qwen format - const qwenConfig = convertClaudeToQwenConfig(finalPluginConfig); - - return { - config: qwenConfig, - sourcePath: pluginSource, - installMetadata: { - source: `${marketplaceUrl}:${pluginName}`, - type: 'git', // Marketplace installs are treated as git installs - }, - }; -} - -/** - * Resolve plugin source from marketplace plugin configuration. - * Returns the absolute path to the plugin source directory. - */ -async function resolvePluginSource( - pluginConfig: ClaudeMarketplacePluginConfig, - marketplaceDir: string, - pluginDir: string, -): Promise { - const source = pluginConfig.source; - - // Handle string source (relative path or URL) - if (typeof source === 'string') { - // Check if it's a URL - if (source.startsWith('http://') || source.startsWith('https://')) { - // Download from URL - const installMetadata: ExtensionInstallMetadata = { - source, - type: 'git', - }; - try { - await downloadFromGitHubRelease(installMetadata, pluginDir); - } catch { - await cloneFromGit(installMetadata, pluginDir); - } - return pluginDir; - } - - // Relative path within marketplace - const pluginRoot = marketplaceDir; - const sourcePath = path.join(pluginRoot, source); - - if (!fs.existsSync(sourcePath)) { - throw new Error(`Plugin source not found at ${sourcePath}`); - } - - // Copy to plugin directory - await fs.promises.cp(sourcePath, pluginDir, { recursive: true }); - return pluginDir; - } - - // Handle object source (github or url) - if (source.source === 'github') { - const installMetadata: ExtensionInstallMetadata = { - source: `https://github.com/${source.repo}`, - type: 'git', - }; - try { - await downloadFromGitHubRelease(installMetadata, pluginDir); - } catch { - await cloneFromGit(installMetadata, pluginDir); - } - return pluginDir; - } - - if (source.source === 'url') { - const installMetadata: ExtensionInstallMetadata = { - source: source.url, - type: 'git', - }; - try { - await downloadFromGitHubRelease(installMetadata, pluginDir); - } catch { - await cloneFromGit(installMetadata, pluginDir); - } - return pluginDir; - } - - throw new Error(`Unsupported plugin source type: ${JSON.stringify(source)}`); -} diff --git a/packages/core/src/skills/skill-load.ts b/packages/core/src/skills/skill-load.ts new file mode 100644 index 00000000000..ed88eb907cc --- /dev/null +++ b/packages/core/src/skills/skill-load.ts @@ -0,0 +1,148 @@ +import type { SkillConfig, SkillValidationResult } from './types.js'; +import * as fs from 'fs/promises'; +import * as path from 'path'; +import { parse as parseYaml } from '../utils/yaml-parser.js'; + +const SKILL_MANIFEST_FILE = 'SKILL.md'; + +export async function loadSkillsFromDir( + baseDir: string, +): Promise { + try { + const entries = await fs.readdir(baseDir, { withFileTypes: true }); + const skills: SkillConfig[] = []; + for (const entry of entries) { + // Only process directories (each skill is a directory) + if (!entry.isDirectory()) continue; + + const skillDir = path.join(baseDir, entry.name); + const skillManifest = path.join(skillDir, SKILL_MANIFEST_FILE); + + try { + // Check if SKILL.md exists + await fs.access(skillManifest); + + const content = await fs.readFile(skillManifest, 'utf8'); + const config = parseSkillContent(content, skillManifest); + skills.push(config); + } catch (error) { + console.warn( + `Failed to parse skill at ${skillDir}: ${error instanceof Error ? error.message : 'Unknown error'}`, + ); + continue; + } + } + return skills; + } catch (_error) { + // Directory doesn't exist or can't be read + return []; + } +} + +export function parseSkillContent( + content: string, + filePath: string, +): SkillConfig { + // Split frontmatter and content + const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/; + const match = content.match(frontmatterRegex); + + if (!match) { + throw new Error('Invalid format: missing YAML frontmatter'); + } + + const [, frontmatterYaml, body] = match; + + // Parse YAML frontmatter + const frontmatter = parseYaml(frontmatterYaml) as Record; + + // Extract required fields + const nameRaw = frontmatter['name']; + const descriptionRaw = frontmatter['description']; + + if (nameRaw == null || nameRaw === '') { + throw new Error('Missing "name" in frontmatter'); + } + + if (descriptionRaw == null || descriptionRaw === '') { + throw new Error('Missing "description" in frontmatter'); + } + + // Convert to strings + const name = String(nameRaw); + const description = String(descriptionRaw); + + // Extract optional fields + const allowedToolsRaw = frontmatter['allowedTools'] as unknown[] | undefined; + let allowedTools: string[] | undefined; + + if (allowedToolsRaw !== undefined) { + if (Array.isArray(allowedToolsRaw)) { + allowedTools = allowedToolsRaw.map(String); + } else { + throw new Error('"allowedTools" must be an array'); + } + } + + const config: SkillConfig = { + name, + description, + allowedTools, + filePath, + body: body.trim(), + level: 'extension', + }; + + // Validate the parsed configuration + const validation = validateConfig(config); + if (!validation.isValid) { + throw new Error(`Validation failed: ${validation.errors.join(', ')}`); + } + + return config; +} + +export function validateConfig( + config: Partial, +): SkillValidationResult { + const errors: string[] = []; + const warnings: string[] = []; + + // Check required fields + if (typeof config.name !== 'string') { + errors.push('Missing or invalid "name" field'); + } else if (config.name.trim() === '') { + errors.push('"name" cannot be empty'); + } + + if (typeof config.description !== 'string') { + errors.push('Missing or invalid "description" field'); + } else if (config.description.trim() === '') { + errors.push('"description" cannot be empty'); + } + + // Validate allowedTools if present + if (config.allowedTools !== undefined) { + if (!Array.isArray(config.allowedTools)) { + errors.push('"allowedTools" must be an array'); + } else { + for (const tool of config.allowedTools) { + if (typeof tool !== 'string') { + errors.push('"allowedTools" must contain only strings'); + break; + } + } + } + } + + // Warn if body is empty + if (!config.body || config.body.trim() === '') { + warnings.push('Skill body is empty'); + } + + return { + isValid: errors.length === 0, + errors, + warnings, + }; +} diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 471d46dfd9a..9fc5273390a 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -18,6 +18,7 @@ import type { } from './types.js'; import { SkillError, SkillErrorCode } from './types.js'; import type { Config } from '../config/config.js'; +import { validateConfig } from './skill-load.js'; const QWEN_CONFIG_DIR = '.qwen'; const SKILLS_CONFIG_DIR = 'skills'; @@ -166,46 +167,7 @@ export class SkillManager { * @returns Validation result */ validateConfig(config: Partial): SkillValidationResult { - const errors: string[] = []; - const warnings: string[] = []; - - // Check required fields - if (typeof config.name !== 'string') { - errors.push('Missing or invalid "name" field'); - } else if (config.name.trim() === '') { - errors.push('"name" cannot be empty'); - } - - if (typeof config.description !== 'string') { - errors.push('Missing or invalid "description" field'); - } else if (config.description.trim() === '') { - errors.push('"description" cannot be empty'); - } - - // Validate allowedTools if present - if (config.allowedTools !== undefined) { - if (!Array.isArray(config.allowedTools)) { - errors.push('"allowedTools" must be an array'); - } else { - for (const tool of config.allowedTools) { - if (typeof tool !== 'string') { - errors.push('"allowedTools" must contain only strings'); - break; - } - } - } - } - - // Warn if body is empty - if (!config.body || config.body.trim() === '') { - warnings.push('Skill body is empty'); - } - - return { - isValid: errors.length === 0, - errors, - warnings, - }; + return validateConfig(config); } /** @@ -411,9 +373,17 @@ export class SkillManager { return []; } - // if (level === 'extension') { - // const extensions = this.config.getExtensions(); - // } + if (level === 'extension') { + const extensions = this.config.getExtensions(); + const skills: SkillConfig[] = []; + for (const extension of extensions) { + extension.skills?.forEach((skill) => { + skills.push(skill); + }); + } + + return skills; + } const baseDir = this.getSkillsBaseDir(level); const skills = await this.loadSkillsFromDir(baseDir, level); diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 303292e8954..443ff1e7ce9 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -178,6 +178,15 @@ export class SubagentManager { return userConfig; } + // Try extension level + const extensionConfig = await this.findSubagentByNameAtLevel( + name, + 'extension', + ); + if (extensionConfig) { + return extensionConfig; + } + // Try built-in agents as fallback return BuiltinAgentRegistry.getBuiltinAgent(name); } @@ -259,7 +268,11 @@ export class SubagentManager { * @param level - Specific level to delete from, or undefined to delete from both * @throws SubagentError if deletion fails */ - async deleteSubagent(name: string, level?: SubagentLevel): Promise { + async deleteSubagent( + name: string, + level?: SubagentLevel, + extensionName?: string, + ): Promise { // Check if it's a built-in agent first if (BuiltinAgentRegistry.isBuiltinAgent(name)) { throw new SubagentError( @@ -268,6 +281,13 @@ export class SubagentManager { name, ); } + if (level === 'extension') { + throw new SubagentError( + `Cannot delete subagent "${name}" in extension "${extensionName}", If needed, you can directly uninstall extension.`, + SubagentErrorCode.INVALID_CONFIG, + name, + ); + } const levelsToCheck: SubagentLevel[] = level ? [level] @@ -440,7 +460,7 @@ export class SubagentManager { * * @private */ - private async refreshCache(): Promise { + async refreshCache(): Promise { const subagentsCache = new Map(); const levels: SubagentLevel[] = ['project', 'user', 'builtin', 'extension']; @@ -510,71 +530,7 @@ export class SubagentManager { filePath: string, level: SubagentLevel, ): SubagentConfig { - try { - // Split frontmatter and content - const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/; - const match = content.match(frontmatterRegex); - - if (!match) { - throw new Error('Invalid format: missing YAML frontmatter'); - } - - const [, frontmatterYaml, systemPrompt] = match; - - // Parse YAML frontmatter - const frontmatter = parseYaml(frontmatterYaml) as Record; - - // Extract required fields and convert to strings - const nameRaw = frontmatter['name']; - const descriptionRaw = frontmatter['description']; - - if (nameRaw == null || nameRaw === '') { - throw new Error('Missing "name" in frontmatter'); - } - - if (descriptionRaw == null || descriptionRaw === '') { - throw new Error('Missing "description" in frontmatter'); - } - - // Convert to strings (handles numbers, booleans, etc.) - const name = String(nameRaw); - const description = String(descriptionRaw); - - // Extract optional fields - const tools = frontmatter['tools'] as string[] | undefined; - const modelConfig = frontmatter['modelConfig'] as - | Record - | undefined; - const runConfig = frontmatter['runConfig'] as - | Record - | undefined; - const color = frontmatter['color'] as string | undefined; - - const config: SubagentConfig = { - name, - description, - tools, - systemPrompt: systemPrompt.trim(), - filePath, - modelConfig: modelConfig as Partial, - runConfig: runConfig as Partial, - color, - level, - }; - - // Validate the parsed configuration - const validation = this.validator.validateConfig(config); - if (!validation.isValid) { - throw new Error(`Validation failed: ${validation.errors.join(', ')}`); - } - - return config; - } catch (error) { - throw new SubagentError( - `Failed to parse subagent file: ${error instanceof Error ? error.message : 'Unknown error'}`, - SubagentErrorCode.INVALID_CONFIG, - ); - } + return parseSubagentContent(content, filePath, level, this.validator); } /** @@ -819,6 +775,11 @@ export class SubagentManager { return BuiltinAgentRegistry.getBuiltinAgents(); } + if (level === 'extension') { + const extensions = this.config.getExtensions(); + return extensions.flatMap((extension) => extension.agents || []); + } + const projectRoot = this.config.getProjectRoot(); const homeDir = os.homedir(); const isHomeDirectory = path.resolve(projectRoot) === path.resolve(homeDir); @@ -832,14 +793,6 @@ export class SubagentManager { let baseDir = level === 'project' ? projectRoot : homeDir; baseDir = path.join(baseDir, QWEN_CONFIG_DIR, AGENT_CONFIG_DIR); - const subagents = await this.loadSubagentFromDir(baseDir, level); - return subagents; - } - - async loadSubagentFromDir( - baseDir: string, - level: SubagentLevel, - ): Promise { try { const files = await fs.readdir(baseDir); const subagents: SubagentConfig[] = []; @@ -910,3 +863,110 @@ export class SubagentManager { return false; // Name is already in use } } + +export async function loadSubagentFromDir( + baseDir: string, +): Promise { + try { + const files = await fs.readdir(baseDir); + const subagents: SubagentConfig[] = []; + + for (const file of files) { + if (!file.endsWith('.md')) continue; + + const filePath = path.join(baseDir, file); + + try { + const content = await fs.readFile(filePath, 'utf8'); + const config = parseSubagentContent( + content, + filePath, + 'extension', + new SubagentValidator(), + ); + subagents.push(config); + } catch (_error) { + // Ignore invalid files + continue; + } + } + + return subagents; + } catch (_error) { + // Directory doesn't exist or can't be read + return []; + } +} + +function parseSubagentContent( + content: string, + filePath: string, + level: SubagentLevel, + validator: SubagentValidator, +): SubagentConfig { + try { + // Split frontmatter and content + const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/; + const match = content.match(frontmatterRegex); + + if (!match) { + throw new Error('Invalid format: missing YAML frontmatter'); + } + + const [, frontmatterYaml, systemPrompt] = match; + + // Parse YAML frontmatter + const frontmatter = parseYaml(frontmatterYaml) as Record; + + // Extract required fields and convert to strings + const nameRaw = frontmatter['name']; + const descriptionRaw = frontmatter['description']; + + if (nameRaw == null || nameRaw === '') { + throw new Error('Missing "name" in frontmatter'); + } + + if (descriptionRaw == null || descriptionRaw === '') { + throw new Error('Missing "description" in frontmatter'); + } + + // Convert to strings (handles numbers, booleans, etc.) + const name = String(nameRaw); + const description = String(descriptionRaw); + + // Extract optional fields + const tools = frontmatter['tools'] as string[] | undefined; + const modelConfig = frontmatter['modelConfig'] as + | Record + | undefined; + const runConfig = frontmatter['runConfig'] as + | Record + | undefined; + const color = frontmatter['color'] as string | undefined; + + const config: SubagentConfig = { + name, + description, + tools, + systemPrompt: systemPrompt.trim(), + filePath, + modelConfig: modelConfig as Partial, + runConfig: runConfig as Partial, + color, + level, + }; + + // Validate the parsed configuration + const validation = validator.validateConfig(config); + if (!validation.isValid) { + throw new Error(`Validation failed: ${validation.errors.join(', ')}`); + } + + return config; + } catch (error) { + throw new SubagentError( + `Failed to parse subagent file: ${error instanceof Error ? error.message : 'Unknown error'}`, + SubagentErrorCode.INVALID_CONFIG, + ); + } +} From f7fb624af98e932da73c12a247b932d0ade97334 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Fri, 16 Jan 2026 16:29:03 +0800 Subject: [PATCH 10/30] feat: extension slash commands --- .../fs/{grep-code.toml => grep-code.md} | 3 - .../src/ui/commands/extensionsCommand.test.ts | 521 +++++++++++++-- .../cli/src/ui/commands/extensionsCommand.ts | 315 ++++++++- .../cli/src/ui/commands/memoryCommand.test.ts | 2 +- .../src/extension/extensionManager.test.ts | 614 ++++++++++++------ .../core/src/extension/extensionManager.ts | 43 +- .../core/src/tools/mcp-client-manager.test.ts | 44 +- packages/core/src/tools/mcp-client-manager.ts | 33 +- packages/core/src/tools/tool-registry.ts | 6 +- 9 files changed, 1268 insertions(+), 313 deletions(-) rename packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/{grep-code.toml => grep-code.md} (65%) diff --git a/packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.toml b/packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.md similarity index 65% rename from packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.toml rename to packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.md index 87d957542ad..cb57c52de93 100644 --- a/packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.toml +++ b/packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.md @@ -1,6 +1,3 @@ -prompt = """ Please summarize the findings for the pattern `{{args}}`. Search Results: -!{grep -r {{args}} .} -""" diff --git a/packages/cli/src/ui/commands/extensionsCommand.test.ts b/packages/cli/src/ui/commands/extensionsCommand.test.ts index 459a825b7dc..acac19c8556 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.test.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.test.ts @@ -4,11 +4,6 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { GeminiCLIExtension } from '@qwen-code/qwen-code-core'; -import { - updateAllUpdatableExtensions, - updateExtension, -} from '../../config/extensions/update.js'; import { createMockCommandContext } from '../../test-utils/mockCommandContext.js'; import { MessageType } from '../types.js'; import { extensionsCommand } from './extensionsCommand.js'; @@ -22,34 +17,59 @@ import { type MockedFunction, } from 'vitest'; import { ExtensionUpdateState } from '../state/extensions.js'; +import { + type Extension, + ExtensionManager, + parseInstallSource, +} from '@qwen-code/qwen-code-core'; -vi.mock('../../config/extensions/update.js', () => ({ - updateExtension: vi.fn(), - updateAllUpdatableExtensions: vi.fn(), - checkForAllExtensionUpdates: vi.fn(), -})); - -const mockUpdateExtension = updateExtension as MockedFunction< - typeof updateExtension ->; - -const mockUpdateAllUpdatableExtensions = - updateAllUpdatableExtensions as MockedFunction< - typeof updateAllUpdatableExtensions - >; +vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + parseInstallSource: vi.fn(), + }; +}); const mockGetExtensions = vi.fn(); +const mockUpdateExtension = vi.fn(); +const mockUpdateAllUpdatableExtensions = vi.fn(); +const mockCheckForAllExtensionUpdates = vi.fn(); +const mockInstallExtension = vi.fn(); +const mockUninstallExtension = vi.fn(); +const mockGetLoadedExtensions = vi.fn(); +const mockEnableExtension = vi.fn(); +const mockDisableExtension = vi.fn(); + +const createMockExtensionManager = () => ({ + updateExtension: mockUpdateExtension, + updateAllUpdatableExtensions: mockUpdateAllUpdatableExtensions, + checkForAllExtensionUpdates: mockCheckForAllExtensionUpdates, + installExtension: mockInstallExtension, + uninstallExtension: mockUninstallExtension, + getLoadedExtensions: mockGetLoadedExtensions, + enableExtension: mockEnableExtension, + disableExtension: mockDisableExtension, +}); describe('extensionsCommand', () => { let mockContext: CommandContext; + let mockExtensionManager: ReturnType; beforeEach(() => { vi.resetAllMocks(); + mockExtensionManager = createMockExtensionManager(); + mockGetExtensions.mockReturnValue([]); + mockGetLoadedExtensions.mockReturnValue([]); + mockCheckForAllExtensionUpdates.mockResolvedValue(undefined); mockContext = createMockCommandContext({ services: { config: { getExtensions: mockGetExtensions, getWorkingDir: () => '/test/dir', + getExtensionManager: () => + mockExtensionManager as unknown as ExtensionManager, }, }, ui: { @@ -59,8 +79,9 @@ describe('extensionsCommand', () => { }); describe('list', () => { - it('should add an EXTENSIONS_LIST item to the UI', async () => { + it('should add an EXTENSIONS_LIST item to the UI when extensions exist', async () => { if (!extensionsCommand.action) throw new Error('Action not defined'); + mockGetExtensions.mockReturnValue([{ name: 'test-ext', isActive: true }]); await extensionsCommand.action(mockContext, ''); expect(mockContext.ui.addItem).toHaveBeenCalledWith( @@ -70,6 +91,20 @@ describe('extensionsCommand', () => { expect.any(Number), ); }); + + it('should show info message when no extensions installed', async () => { + if (!extensionsCommand.action) throw new Error('Action not defined'); + mockGetExtensions.mockReturnValue([]); + await extensionsCommand.action(mockContext, ''); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'No extensions installed. Run `/extensions explore` to check out the gallery.', + }, + expect.any(Number), + ); + }); }); describe('update', () => { @@ -93,6 +128,7 @@ describe('extensionsCommand', () => { }); it('should inform user if there are no extensions to update with --all', async () => { + mockGetExtensions.mockReturnValue([{ name: 'ext-one', isActive: true }]); mockUpdateAllUpdatableExtensions.mockResolvedValue([]); await updateAction(mockContext, '--all'); expect(mockContext.ui.addItem).toHaveBeenCalledWith( @@ -105,6 +141,7 @@ describe('extensionsCommand', () => { }); it('should call setPendingItem and addItem in a finally block on success', async () => { + mockGetExtensions.mockReturnValue([{ name: 'ext-one', isActive: true }]); mockUpdateAllUpdatableExtensions.mockResolvedValue([ { name: 'ext-one', @@ -131,6 +168,7 @@ describe('extensionsCommand', () => { }); it('should call setPendingItem and addItem in a finally block on failure', async () => { + mockGetExtensions.mockReturnValue([{ name: 'ext-one', isActive: true }]); mockUpdateAllUpdatableExtensions.mockRejectedValue( new Error('Something went wrong'), ); @@ -155,11 +193,14 @@ describe('extensionsCommand', () => { }); it('should update a single extension by name', async () => { - const extension: GeminiCLIExtension = { + const extension: Extension = { + id: 'ext-one', name: 'ext-one', version: '1.0.0', isActive: true, path: '/test/dir/ext-one', + contextFiles: [], + config: { name: 'ext-one', version: '1.0.0' }, installMetadata: { type: 'git', autoUpdate: false, @@ -179,16 +220,23 @@ describe('extensionsCommand', () => { await updateAction(mockContext, 'ext-one'); expect(mockUpdateExtension).toHaveBeenCalledWith( extension, - '/test/dir', - expect.any(Function), ExtensionUpdateState.UPDATE_AVAILABLE, expect.any(Function), ); }); it('should handle errors when updating a single extension', async () => { - mockUpdateExtension.mockRejectedValue(new Error('Extension not found')); - mockGetExtensions.mockReturnValue([]); + // Provide at least one extension so we don't get "No extensions installed" message + const otherExtension: Extension = { + id: 'other-ext', + name: 'other-ext', + version: '1.0.0', + isActive: true, + path: '/test/dir/other-ext', + contextFiles: [], + config: { name: 'other-ext', version: '1.0.0' }, + }; + mockGetExtensions.mockReturnValue([otherExtension]); await updateAction(mockContext, 'ext-one'); expect(mockContext.ui.addItem).toHaveBeenCalledWith( { @@ -200,22 +248,28 @@ describe('extensionsCommand', () => { }); it('should update multiple extensions by name', async () => { - const extensionOne: GeminiCLIExtension = { + const extensionOne: Extension = { + id: 'ext-one', name: 'ext-one', version: '1.0.0', isActive: true, path: '/test/dir/ext-one', + contextFiles: [], + config: { name: 'ext-one', version: '1.0.0' }, installMetadata: { type: 'git', autoUpdate: false, source: 'https://github.com/some/extension.git', }, }; - const extensionTwo: GeminiCLIExtension = { + const extensionTwo: Extension = { + id: 'ext-two', name: 'ext-two', version: '1.0.0', isActive: true, path: '/test/dir/ext-two', + contextFiles: [], + config: { name: 'ext-two', version: '1.0.0' }, installMetadata: { type: 'git', autoUpdate: false, @@ -223,14 +277,14 @@ describe('extensionsCommand', () => { }, }; mockGetExtensions.mockReturnValue([extensionOne, extensionTwo]); - mockContext.ui.extensionsUpdateState.set( - extensionOne.name, - ExtensionUpdateState.UPDATE_AVAILABLE, - ); - mockContext.ui.extensionsUpdateState.set( - extensionTwo.name, - ExtensionUpdateState.UPDATE_AVAILABLE, - ); + mockContext.ui.extensionsUpdateState.set(extensionOne.name, { + status: ExtensionUpdateState.UPDATE_AVAILABLE, + processed: false, + }); + mockContext.ui.extensionsUpdateState.set(extensionTwo.name, { + status: ExtensionUpdateState.UPDATE_AVAILABLE, + processed: false, + }); mockUpdateExtension .mockResolvedValueOnce({ name: 'ext-one', @@ -265,18 +319,24 @@ describe('extensionsCommand', () => { throw new Error('Update completion not found'); } - const extensionOne: GeminiCLIExtension = { + const extensionOne: Extension = { + id: 'ext-one', name: 'ext-one', version: '1.0.0', isActive: true, path: '/test/dir/ext-one', + contextFiles: [], + config: { name: 'ext-one', version: '1.0.0' }, installMetadata: { type: 'git', autoUpdate: false, source: 'https://github.com/some/extension.git', }, }; - const extensionTwo: GeminiCLIExtension = { + const extensionTwo: Extension = { + id: 'another-ext', + contextFiles: [], + config: { name: 'another-ext', version: '1.0.0' }, name: 'another-ext', version: '1.0.0', isActive: true, @@ -287,8 +347,11 @@ describe('extensionsCommand', () => { source: 'https://github.com/some/extension.git', }, }; - const allExt: GeminiCLIExtension = { + const allExt: Extension = { + id: 'all-ext', name: 'all-ext', + contextFiles: [], + config: { name: 'all-ext', version: '1.0.0' }, version: '1.0.0', isActive: true, path: '/test/dir/all-ext', @@ -331,5 +394,387 @@ describe('extensionsCommand', () => { expect(suggestions).toEqual(expected); }); }); + + it('should call reloadCommands in finally block', async () => { + mockGetExtensions.mockReturnValue([{ name: 'ext-one', isActive: true }]); + mockUpdateAllUpdatableExtensions.mockResolvedValue([ + { + name: 'ext-one', + originalVersion: '1.0.0', + updatedVersion: '1.0.1', + }, + ]); + await updateAction(mockContext, '--all'); + expect(mockContext.ui.reloadCommands).toHaveBeenCalled(); + }); + }); + + describe('install', () => { + const installAction = extensionsCommand.subCommands?.find( + (cmd) => cmd.name === 'install', + )?.action; + + if (!installAction) { + throw new Error('Install action not found'); + } + + const mockParseInstallSource = parseInstallSource as MockedFunction< + typeof parseInstallSource + >; + + // Create a real ExtensionManager mock that passes instanceof check + let realMockExtensionManager: ExtensionManager; + + beforeEach(() => { + vi.resetAllMocks(); + // Create a mock that inherits from ExtensionManager prototype + realMockExtensionManager = Object.create(ExtensionManager.prototype); + realMockExtensionManager.installExtension = mockInstallExtension; + + mockContext = createMockCommandContext({ + services: { + config: { + getExtensions: mockGetExtensions, + getWorkingDir: () => '/test/dir', + getExtensionManager: () => realMockExtensionManager, + }, + }, + ui: { + dispatchExtensionStateUpdate: vi.fn(), + }, + }); + }); + + it('should show usage if no source is provided', async () => { + await installAction(mockContext, ''); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Usage: /extensions install ', + }, + expect.any(Number), + ); + }); + + it('should install extension successfully', async () => { + mockParseInstallSource.mockResolvedValue({ + type: 'git', + source: 'https://github.com/test/extension', + }); + mockInstallExtension.mockResolvedValue({ + name: 'test-extension', + version: '1.0.0', + }); + + await installAction(mockContext, 'https://github.com/test/extension'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Installing extension from "https://github.com/test/extension"...', + }, + expect.any(Number), + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" installed successfully.', + }, + expect.any(Number), + ); + expect(mockContext.ui.reloadCommands).toHaveBeenCalled(); + }); + + it('should handle install errors', async () => { + mockParseInstallSource.mockRejectedValue( + new Error('Install source not found.'), + ); + + await installAction(mockContext, '/invalid/path'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Failed to install extension from "/invalid/path": Install source not found.', + }, + expect.any(Number), + ); + }); + }); + + describe('uninstall', () => { + const uninstallAction = extensionsCommand.subCommands?.find( + (cmd) => cmd.name === 'uninstall', + )?.action; + + if (!uninstallAction) { + throw new Error('Uninstall action not found'); + } + + let realMockExtensionManager: ExtensionManager; + + beforeEach(() => { + vi.resetAllMocks(); + realMockExtensionManager = Object.create(ExtensionManager.prototype); + realMockExtensionManager.uninstallExtension = mockUninstallExtension; + + mockContext = createMockCommandContext({ + services: { + config: { + getExtensions: mockGetExtensions, + getWorkingDir: () => '/test/dir', + getExtensionManager: () => realMockExtensionManager, + }, + }, + ui: { + dispatchExtensionStateUpdate: vi.fn(), + }, + }); + }); + + it('should show usage if no name is provided', async () => { + await uninstallAction(mockContext, ''); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Usage: /extensions uninstall ', + }, + expect.any(Number), + ); + }); + + it('should uninstall extension successfully', async () => { + mockUninstallExtension.mockResolvedValue(undefined); + + await uninstallAction(mockContext, 'test-extension'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Uninstalling extension "test-extension"...', + }, + expect.any(Number), + ); + expect(mockUninstallExtension).toHaveBeenCalledWith( + 'test-extension', + false, + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" uninstalled successfully.', + }, + expect.any(Number), + ); + expect(mockContext.ui.reloadCommands).toHaveBeenCalled(); + }); + + it('should handle uninstall errors', async () => { + mockUninstallExtension.mockRejectedValue( + new Error('Extension not found.'), + ); + + await uninstallAction(mockContext, 'nonexistent-extension'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Failed to uninstall extension "nonexistent-extension": Extension not found.', + }, + expect.any(Number), + ); + }); + }); + + describe('disable', () => { + const disableAction = extensionsCommand.subCommands?.find( + (cmd) => cmd.name === 'disable', + )?.action; + + if (!disableAction) { + throw new Error('Disable action not found'); + } + + let realMockExtensionManager: ExtensionManager; + + beforeEach(() => { + vi.resetAllMocks(); + realMockExtensionManager = Object.create(ExtensionManager.prototype); + realMockExtensionManager.disableExtension = mockDisableExtension; + realMockExtensionManager.getLoadedExtensions = mockGetLoadedExtensions; + + mockContext = createMockCommandContext({ + invocation: { + raw: '/extensions disable', + name: 'disable', + args: '', + }, + services: { + config: { + getExtensions: mockGetExtensions, + getWorkingDir: () => '/test/dir', + getExtensionManager: () => realMockExtensionManager, + }, + }, + ui: { + dispatchExtensionStateUpdate: vi.fn(), + }, + }); + }); + + it('should show usage if invalid args are provided', async () => { + await disableAction(mockContext, ''); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Usage: /extensions disable [--scope=]', + }, + expect.any(Number), + ); + }); + + it('should disable extension at user scope', async () => { + mockDisableExtension.mockResolvedValue(undefined); + + await disableAction(mockContext, 'test-extension --scope=user'); + + expect(mockDisableExtension).toHaveBeenCalledWith( + 'test-extension', + 'User', + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" disabled for the scope "User"', + }, + expect.any(Number), + ); + }); + + it('should disable extension at workspace scope', async () => { + mockDisableExtension.mockResolvedValue(undefined); + + await disableAction(mockContext, 'test-extension --scope workspace'); + + expect(mockDisableExtension).toHaveBeenCalledWith( + 'test-extension', + 'Workspace', + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" disabled for the scope "Workspace"', + }, + expect.any(Number), + ); + }); + + it('should show error for invalid scope', async () => { + await disableAction(mockContext, 'test-extension --scope=invalid'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Unsupported scope invalid, should be one of "user" or "workspace"', + }, + expect.any(Number), + ); + }); + }); + + describe('enable', () => { + const enableAction = extensionsCommand.subCommands?.find( + (cmd) => cmd.name === 'enable', + )?.action; + + if (!enableAction) { + throw new Error('Enable action not found'); + } + + let realMockExtensionManager: ExtensionManager; + + beforeEach(() => { + vi.resetAllMocks(); + realMockExtensionManager = Object.create(ExtensionManager.prototype); + realMockExtensionManager.enableExtension = mockEnableExtension; + realMockExtensionManager.getLoadedExtensions = mockGetLoadedExtensions; + + mockContext = createMockCommandContext({ + invocation: { + raw: '/extensions enable', + name: 'enable', + args: '', + }, + services: { + config: { + getExtensions: mockGetExtensions, + getWorkingDir: () => '/test/dir', + getExtensionManager: () => realMockExtensionManager, + }, + }, + ui: { + dispatchExtensionStateUpdate: vi.fn(), + }, + }); + }); + + it('should show usage if invalid args are provided', async () => { + await enableAction(mockContext, ''); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Usage: /extensions enable [--scope=]', + }, + expect.any(Number), + ); + }); + + it('should enable extension at user scope', async () => { + mockEnableExtension.mockResolvedValue(undefined); + + await enableAction(mockContext, 'test-extension --scope=user'); + + expect(mockEnableExtension).toHaveBeenCalledWith( + 'test-extension', + 'User', + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" enabled for the scope "User"', + }, + expect.any(Number), + ); + }); + + it('should enable extension at workspace scope', async () => { + mockEnableExtension.mockResolvedValue(undefined); + + await enableAction(mockContext, 'test-extension --scope workspace'); + + expect(mockEnableExtension).toHaveBeenCalledWith( + 'test-extension', + 'Workspace', + ); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: 'Extension "test-extension" enabled for the scope "Workspace"', + }, + expect.any(Number), + ); + }); + + it('should show error for invalid scope', async () => { + await enableAction(mockContext, 'test-extension --scope=invalid'); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Unsupported scope invalid, should be one of "user" or "workspace"', + }, + expect.any(Number), + ); + }); }); }); diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index b15c6d82dd3..859936914d8 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -13,7 +13,12 @@ import { CommandKind, } from './types.js'; import { t } from '../../i18n/index.js'; -import type { ExtensionUpdateInfo } from '@qwen-code/qwen-code-core'; +import { + ExtensionManager, + parseInstallSource, + type ExtensionUpdateInfo, +} from '@qwen-code/qwen-code-core'; +import { SettingScope } from '../../config/settings.js'; function showMessageIfNoExtensions( context: CommandContext, @@ -153,10 +158,268 @@ async function updateAction(context: CommandContext, args: string) { }, Date.now(), ); + context.ui.reloadCommands(); context.ui.setPendingItem(null); } } +async function installAction(context: CommandContext, args: string) { + const extensionManager = context.services.config?.getExtensionManager(); + if (!(extensionManager instanceof ExtensionManager)) { + console.error( + `Cannot ${context.invocation?.name} extensions in this environment`, + ); + return; + } + + const source = args.trim(); + if (!source) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Usage: /extensions install `, + }, + Date.now(), + ); + return; + } + + try { + const installMetadata = await parseInstallSource(source); + context.ui.addItem( + { + type: MessageType.INFO, + text: `Installing extension from "${source}"...`, + }, + Date.now(), + ); + const extension = await extensionManager.installExtension(installMetadata); + context.ui.addItem( + { + type: MessageType.INFO, + text: `Extension "${extension.name}" installed successfully.`, + }, + Date.now(), + ); + // FIXME: refresh command controlled by ui for now, cannot be auto refreshed by extensionManager + context.ui.reloadCommands(); + } catch (error) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Failed to install extension from "${source}": ${getErrorMessage( + error, + )}`, + }, + Date.now(), + ); + return; + } +} + +async function uninstallAction(context: CommandContext, args: string) { + const extensionManager = context.services.config?.getExtensionManager(); + if (!(extensionManager instanceof ExtensionManager)) { + console.error( + `Cannot ${context.invocation?.name} extensions in this environment`, + ); + return; + } + + const name = args.trim(); + if (!name) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Usage: /extensions uninstall `, + }, + Date.now(), + ); + return; + } + + context.ui.addItem( + { + type: MessageType.INFO, + text: `Uninstalling extension "${name}"...`, + }, + Date.now(), + ); + + try { + await extensionManager.uninstallExtension(name, false); + context.ui.addItem( + { + type: MessageType.INFO, + text: `Extension "${name}" uninstalled successfully.`, + }, + Date.now(), + ); + context.ui.reloadCommands(); + } catch (error) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Failed to uninstall extension "${name}": ${getErrorMessage( + error, + )}`, + }, + Date.now(), + ); + } +} + +function getEnableDisableContext( + context: CommandContext, + argumentsString: string, +): { + extensionManager: ExtensionManager; + names: string[]; + scope: SettingScope; +} | null { + const extensionManager = context.services.config?.getExtensionManager(); + if (!(extensionManager instanceof ExtensionManager)) { + console.error( + `Cannot ${context.invocation?.name} extensions in this environment`, + ); + return null; + } + const parts = argumentsString.split(' '); + const name = parts[0]; + if ( + name === '' || + !( + (parts.length === 2 && parts[1].startsWith('--scope=')) || // --scope= + (parts.length === 3 && parts[1] === '--scope') // --scope + ) + ) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Usage: /extensions ${context.invocation?.name} [--scope=]`, + }, + Date.now(), + ); + return null; + } + let scope: SettingScope; + // Transform `--scope=` to `--scope `. + if (parts.length === 2) { + parts.push(...parts[1].split('=')); + parts.splice(1, 1); + } + switch (parts[2].toLowerCase()) { + case 'workspace': + scope = SettingScope.Workspace; + break; + case 'user': + scope = SettingScope.User; + break; + default: + context.ui.addItem( + { + type: MessageType.ERROR, + text: `Unsupported scope ${parts[2]}, should be one of "user" or "workspace"`, + }, + Date.now(), + ); + return null; + } + let names: string[] = []; + if (name === '--all') { + let extensions = extensionManager.getLoadedExtensions(); + if (context.invocation?.name === 'enable') { + extensions = extensions.filter((ext) => !ext.isActive); + } + if (context.invocation?.name === 'disable') { + extensions = extensions.filter((ext) => ext.isActive); + } + names = extensions.map((ext) => ext.name); + } else { + names = [name]; + } + + return { + extensionManager, + names, + scope, + }; +} + +async function disableAction(context: CommandContext, args: string) { + const enableContext = getEnableDisableContext(context, args); + if (!enableContext) return; + + const { names, scope, extensionManager } = enableContext; + for (const name of names) { + await extensionManager.disableExtension(name, scope); + context.ui.addItem( + { + type: MessageType.INFO, + text: `Extension "${name}" disabled for the scope "${scope}"`, + }, + Date.now(), + ); + context.ui.reloadCommands(); + } +} + +async function enableAction(context: CommandContext, args: string) { + const enableContext = getEnableDisableContext(context, args); + if (!enableContext) return; + + const { names, scope, extensionManager } = enableContext; + for (const name of names) { + await extensionManager.enableExtension(name, scope); + context.ui.addItem( + { + type: MessageType.INFO, + text: `Extension "${name}" enabled for the scope "${scope}"`, + }, + Date.now(), + ); + context.ui.reloadCommands(); + } +} + +export async function completeExtensions( + context: CommandContext, + partialArg: string, +) { + let extensions = context.services.config?.getExtensions() ?? []; + + if (context.invocation?.name === 'enable') { + extensions = extensions.filter((ext) => !ext.isActive); + } + if ( + context.invocation?.name === 'disable' || + context.invocation?.name === 'restart' + ) { + extensions = extensions.filter((ext) => ext.isActive); + } + const extensionNames = extensions.map((ext) => ext.name); + const suggestions = extensionNames.filter((name) => + name.startsWith(partialArg), + ); + + if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) { + suggestions.unshift('--all'); + } + + return suggestions; +} + +export async function completeExtensionsAndScopes( + context: CommandContext, + partialArg: string, +) { + const completions = await completeExtensions(context, partialArg); + return completions.flatMap((s) => [ + `${s} --scope user`, + `${s} --scope workspace`, + ]); +} + const listExtensionsCommand: SlashCommand = { name: 'list', get description() { @@ -173,19 +436,38 @@ const updateExtensionsCommand: SlashCommand = { }, kind: CommandKind.BUILT_IN, action: updateAction, - completion: async (context, partialArg) => { - const extensions = context.services.config?.getExtensions() ?? []; - const extensionNames = extensions.map((ext) => ext.name); - const suggestions = extensionNames.filter((name) => - name.startsWith(partialArg), - ); + completion: completeExtensions, +}; - if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) { - suggestions.unshift('--all'); - } +const disableCommand: SlashCommand = { + name: 'disable', + description: 'Disable an extension', + kind: CommandKind.BUILT_IN, + action: disableAction, + completion: completeExtensionsAndScopes, +}; - return suggestions; - }, +const enableCommand: SlashCommand = { + name: 'enable', + description: 'Enable an extension', + kind: CommandKind.BUILT_IN, + action: enableAction, + completion: completeExtensionsAndScopes, +}; + +const installCommand: SlashCommand = { + name: 'install', + description: 'Install an extension from a git repo or local path', + kind: CommandKind.BUILT_IN, + action: installAction, +}; + +const uninstallCommand: SlashCommand = { + name: 'uninstall', + description: 'Uninstall an extension', + kind: CommandKind.BUILT_IN, + action: uninstallAction, + completion: completeExtensions, }; export const extensionsCommand: SlashCommand = { @@ -194,7 +476,14 @@ export const extensionsCommand: SlashCommand = { return t('Manage extensions'); }, kind: CommandKind.BUILT_IN, - subCommands: [listExtensionsCommand, updateExtensionsCommand], + subCommands: [ + listExtensionsCommand, + updateExtensionsCommand, + disableCommand, + enableCommand, + installCommand, + uninstallCommand, + ], action: (context, args) => // Default to list if no subcommand is provided listExtensionsCommand.action!(context, args), diff --git a/packages/cli/src/ui/commands/memoryCommand.test.ts b/packages/cli/src/ui/commands/memoryCommand.test.ts index 7e20bf11ce3..e37ff6474b5 100644 --- a/packages/cli/src/ui/commands/memoryCommand.test.ts +++ b/packages/cli/src/ui/commands/memoryCommand.test.ts @@ -7,7 +7,7 @@ import type { Mock } from 'vitest'; import { vi, describe, it, expect, beforeEach } from 'vitest'; import { memoryCommand } from './memoryCommand.js'; -import type { SlashCommand, type CommandContext } from './types.js'; +import type { SlashCommand, CommandContext } from './types.js'; import { createMockCommandContext } from '../../test-utils/mockCommandContext.js'; import { MessageType } from '../types.js'; import type { LoadedSettings } from '../../config/settings.js'; diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 3d33a30f869..550c76c20cc 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -321,7 +321,7 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - manager.disableExtension('my-extension', SettingScope.User); + await manager.disableExtension('my-extension', SettingScope.User); expect(manager.isEnabled('my-extension', tempWorkspaceDir)).toBe(false); }); @@ -335,7 +335,7 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - manager.disableExtension( + await manager.disableExtension( 'my-extension', SettingScope.Workspace, tempWorkspaceDir, @@ -355,8 +355,8 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - manager.disableExtension('my-extension', SettingScope.User); - manager.disableExtension('my-extension', SettingScope.User); + await manager.disableExtension('my-extension', SettingScope.User); + await manager.disableExtension('my-extension', SettingScope.User); expect(manager.isEnabled('my-extension', tempWorkspaceDir)).toBe(false); }); @@ -370,9 +370,9 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - expect(() => + await expect( manager.disableExtension('my-extension', SettingScope.System), - ).toThrow('System and SystemDefaults scopes are not supported.'); + ).rejects.toThrow('System and SystemDefaults scopes are not supported.'); }); it('should enable an extension at the user scope', async () => { @@ -385,10 +385,10 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - manager.disableExtension('ext1', SettingScope.User); + await manager.disableExtension('ext1', SettingScope.User); expect(manager.isEnabled('ext1')).toBe(false); - manager.enableExtension('ext1', SettingScope.User); + await manager.enableExtension('ext1', SettingScope.User); expect(manager.isEnabled('ext1')).toBe(true); }); @@ -402,10 +402,10 @@ describe('extension tests', () => { const manager = createExtensionManager(); await manager.refreshCache(); - manager.disableExtension('ext1', SettingScope.Workspace); + await manager.disableExtension('ext1', SettingScope.Workspace); expect(manager.isEnabled('ext1', tempWorkspaceDir)).toBe(false); - manager.enableExtension('ext1', SettingScope.Workspace); + await manager.enableExtension('ext1', SettingScope.Workspace); expect(manager.isEnabled('ext1', tempWorkspaceDir)).toBe(true); }); }); @@ -606,231 +606,447 @@ describe('extension tests', () => { expect(serverConfig.env!['MISSING_VAR']).toBe('$UNDEFINED_ENV_VAR'); expect(serverConfig.env!['MISSING_VAR_BRACES']).toBe('${ALSO_UNDEFINED}'); }); - }); -}); + describe('refreshTools and refreshMemory', () => { + it('refreshTools should return early if config is not set', async () => { + const manager = createExtensionManager(); + const extension = { + name: 'test-ext', + config: { name: 'test-ext', version: '1.0.0' }, + excludeTools: ['tool1'], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + + // Should not throw when config is undefined + await expect(manager.refreshTools(extension)).resolves.not.toThrow(); + }); -describe('extensionManager utility functions', () => { - describe('validateName', () => { - it('should accept valid extension names', () => { - expect(() => validateName('my-extension')).not.toThrow(); - expect(() => validateName('Extension123')).not.toThrow(); - expect(() => validateName('test-ext-1')).not.toThrow(); - expect(() => validateName('UPPERCASE')).not.toThrow(); - }); + it('refreshTools should call setTools when extension has excludeTools', async () => { + const mockSetTools = vi.fn().mockResolvedValue(undefined); + const mockRefreshCache = vi.fn(); + const mockRestartMcpServers = vi.fn(); + const mockRefreshHierarchicalMemory = vi.fn(); + + const mockConfig = { + getGeminiClient: () => ({ + isInitialized: () => true, + setTools: mockSetTools, + }), + getToolRegistry: () => ({ + restartMcpServers: mockRestartMcpServers, + }), + getSkillManager: () => ({ + refreshCache: mockRefreshCache, + }), + getSubagentManager: () => ({ + refreshCache: mockRefreshCache, + }), + refreshHierarchicalMemory: mockRefreshHierarchicalMemory, + }; - it('should reject names with invalid characters', () => { - expect(() => validateName('my_extension')).toThrow( - 'Invalid extension name', - ); - expect(() => validateName('my.extension')).toThrow( - 'Invalid extension name', - ); - expect(() => validateName('my extension')).toThrow( - 'Invalid extension name', - ); - expect(() => validateName('my@ext')).toThrow('Invalid extension name'); - }); + const manager = createExtensionManager(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (manager as any).config = mockConfig; - it('should reject empty names', () => { - expect(() => validateName('')).toThrow('Invalid extension name'); - }); - }); + const extension = { + name: 'test-ext', + config: { name: 'test-ext', version: '1.0.0' }, + excludeTools: ['tool1', 'tool2'], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; - describe('hashValue', () => { - it('should generate consistent hash for same input', () => { - const hash1 = hashValue('test-input'); - const hash2 = hashValue('test-input'); - expect(hash1).toBe(hash2); - }); + await manager.refreshTools(extension); - it('should generate different hashes for different inputs', () => { - const hash1 = hashValue('input-1'); - const hash2 = hashValue('input-2'); - expect(hash1).not.toBe(hash2); - }); + expect(mockSetTools).toHaveBeenCalledOnce(); + }); - it('should generate a valid SHA256 hash', () => { - const hash = hashValue('test'); - expect(hash).toMatch(/^[a-f0-9]{64}$/); - }); - }); + it('refreshTools should not call setTools when extension has no excludeTools', async () => { + const mockSetTools = vi.fn().mockResolvedValue(undefined); + const mockRefreshCache = vi.fn(); + const mockRestartMcpServers = vi.fn(); + const mockRefreshHierarchicalMemory = vi.fn(); + + const mockConfig = { + getGeminiClient: () => ({ + isInitialized: () => true, + setTools: mockSetTools, + }), + getToolRegistry: () => ({ + restartMcpServers: mockRestartMcpServers, + }), + getSkillManager: () => ({ + refreshCache: mockRefreshCache, + }), + getSubagentManager: () => ({ + refreshCache: mockRefreshCache, + }), + refreshHierarchicalMemory: mockRefreshHierarchicalMemory, + }; - describe('getExtensionId', () => { - it('should use hashed name when no install metadata', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const id = getExtensionId(config); - expect(id).toBe(hashValue('test-ext')); - }); + const manager = createExtensionManager(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (manager as any).config = mockConfig; - it('should use hashed source for local install', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const metadata = { type: 'local' as const, source: '/path/to/ext' }; - const id = getExtensionId(config, metadata); - expect(id).toBe(hashValue('/path/to/ext')); - }); + const extension = { + name: 'test-ext', + config: { name: 'test-ext', version: '1.0.0' }, + excludeTools: [], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; - it('should use GitHub URL for git install', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const metadata = { - type: 'git' as const, - source: 'https://github.com/owner/repo', - }; - const id = getExtensionId(config, metadata); - expect(id).toBe(hashValue('https://github.com/owner/repo')); - }); - }); + await manager.refreshTools(extension); - describe('extensionConsentString', () => { - it('should generate basic consent string', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const consent = extensionConsentString(config); - expect(consent).toContain('Installing extension "test-ext"'); - expect(consent).toContain('Extensions may introduce unexpected behavior'); - }); + expect(mockSetTools).not.toHaveBeenCalled(); + }); - it('should include MCP servers in consent string', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - mcpServers: { - 'my-server': { command: 'node', args: ['server.js'] }, - }, - }; - const consent = extensionConsentString(config); - expect(consent).toContain( - 'This extension will run the following MCP servers', - ); - expect(consent).toContain('my-server'); - }); + it('refreshTools should not call setTools when geminiClient is not initialized', async () => { + const mockSetTools = vi.fn().mockResolvedValue(undefined); + const mockRefreshCache = vi.fn(); + const mockRestartMcpServers = vi.fn(); + const mockRefreshHierarchicalMemory = vi.fn(); + + const mockConfig = { + getGeminiClient: () => ({ + isInitialized: () => false, + setTools: mockSetTools, + }), + getToolRegistry: () => ({ + restartMcpServers: mockRestartMcpServers, + }), + getSkillManager: () => ({ + refreshCache: mockRefreshCache, + }), + getSubagentManager: () => ({ + refreshCache: mockRefreshCache, + }), + refreshHierarchicalMemory: mockRefreshHierarchicalMemory, + }; - it('should include commands in consent string', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const consent = extensionConsentString(config, ['cmd1', 'cmd2']); - expect(consent).toContain( - 'This extension will add the following commands', - ); - expect(consent).toContain('cmd1, cmd2'); - }); + const manager = createExtensionManager(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (manager as any).config = mockConfig; - it('should include context file info', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - contextFileName: 'CONTEXT.md', - }; - const consent = extensionConsentString(config); - expect(consent).toContain('CONTEXT.md'); - }); + const extension = { + name: 'test-ext', + config: { name: 'test-ext', version: '1.0.0' }, + excludeTools: ['tool1'], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; - it('should include excluded tools', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - excludeTools: ['tool1', 'tool2'], - }; - const consent = extensionConsentString(config); - expect(consent).toContain('exclude the following core tools'); - }); - }); + await manager.refreshTools(extension); - describe('maybeRequestConsentOrFail', () => { - it('should request consent for new installation', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const requestConsent = vi.fn().mockResolvedValue(true); + expect(mockSetTools).not.toHaveBeenCalled(); + }); - await maybeRequestConsentOrFail(config, requestConsent, []); + it('refreshTools should always call refreshMemory', async () => { + const mockRefreshCache = vi.fn(); + const mockRestartMcpServers = vi.fn(); + const mockRefreshHierarchicalMemory = vi.fn(); + + const mockConfig = { + getGeminiClient: () => ({ + isInitialized: () => false, + setTools: vi.fn(), + }), + getToolRegistry: () => ({ + restartMcpServers: mockRestartMcpServers, + }), + getSkillManager: () => ({ + refreshCache: mockRefreshCache, + }), + getSubagentManager: () => ({ + refreshCache: mockRefreshCache, + }), + refreshHierarchicalMemory: mockRefreshHierarchicalMemory, + }; - expect(requestConsent).toHaveBeenCalledTimes(1); - }); + const manager = createExtensionManager(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (manager as any).config = mockConfig; + + const extension = { + name: 'test-ext', + config: { name: 'test-ext', version: '1.0.0' }, + excludeTools: [], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + + await manager.refreshTools(extension); + + // refreshMemory should be called which includes these + expect(mockRestartMcpServers).toHaveBeenCalledOnce(); + expect(mockRefreshCache).toHaveBeenCalledTimes(2); // skillManager and subagentManager + expect(mockRefreshHierarchicalMemory).toHaveBeenCalledOnce(); + }); - it('should throw if user declines consent', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const requestConsent = vi.fn().mockResolvedValue(false); + it('refreshMemory should return early if config is not set', async () => { + const manager = createExtensionManager(); - await expect( - maybeRequestConsentOrFail(config, requestConsent, []), - ).rejects.toThrow('Installation cancelled'); - }); + // Should not throw when config is undefined + await expect(manager.refreshMemory()).resolves.not.toThrow(); + }); - it('should skip consent if config unchanged during update', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const previousConfig: ExtensionConfig = { - name: 'test-ext', - version: '0.9.0', - }; - const requestConsent = vi.fn().mockResolvedValue(true); - - await maybeRequestConsentOrFail( - config, - requestConsent, - [], - [], - [], - previousConfig, - ); + it('refreshMemory should call all refresh methods', async () => { + const mockSkillRefreshCache = vi.fn(); + const mockSubagentRefreshCache = vi.fn(); + const mockRestartMcpServers = vi.fn(); + const mockRefreshHierarchicalMemory = vi.fn(); + + const mockConfig = { + getToolRegistry: () => ({ + restartMcpServers: mockRestartMcpServers, + }), + getSkillManager: () => ({ + refreshCache: mockSkillRefreshCache, + }), + getSubagentManager: () => ({ + refreshCache: mockSubagentRefreshCache, + }), + refreshHierarchicalMemory: mockRefreshHierarchicalMemory, + }; - expect(requestConsent).not.toHaveBeenCalled(); - }); + const manager = createExtensionManager(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (manager as any).config = mockConfig; - it('should request consent if config changed during update', async () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - mcpServers: { server: { command: 'node' } }, - }; - const previousConfig: ExtensionConfig = { - name: 'test-ext', - version: '0.9.0', - }; - const requestConsent = vi.fn().mockResolvedValue(true); - - await maybeRequestConsentOrFail( - config, - requestConsent, - [], - [], - [], - previousConfig, - ); + await manager.refreshMemory(); - expect(requestConsent).toHaveBeenCalledTimes(1); + expect(mockRestartMcpServers).toHaveBeenCalledOnce(); + expect(mockSkillRefreshCache).toHaveBeenCalledOnce(); + expect(mockSubagentRefreshCache).toHaveBeenCalledOnce(); + expect(mockRefreshHierarchicalMemory).toHaveBeenCalledOnce(); + }); }); }); - describe('parseInstallSource', () => { - it('should parse HTTPS URL as git type', async () => { - const result = await parseInstallSource('https://github.com/owner/repo'); - expect(result.type).toBe('git'); - expect(result.source).toBe('https://github.com/owner/repo'); + describe('extensionManager utility functions', () => { + describe('validateName', () => { + it('should accept valid extension names', () => { + expect(() => validateName('my-extension')).not.toThrow(); + expect(() => validateName('Extension123')).not.toThrow(); + expect(() => validateName('test-ext-1')).not.toThrow(); + expect(() => validateName('UPPERCASE')).not.toThrow(); + }); + + it('should reject names with invalid characters', () => { + expect(() => validateName('my_extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my.extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my extension')).toThrow( + 'Invalid extension name', + ); + expect(() => validateName('my@ext')).toThrow('Invalid extension name'); + }); + + it('should reject empty names', () => { + expect(() => validateName('')).toThrow('Invalid extension name'); + }); }); - it('should parse HTTP URL as git type', async () => { - const result = await parseInstallSource('http://example.com/repo'); - expect(result.type).toBe('git'); + describe('hashValue', () => { + it('should generate consistent hash for same input', () => { + const hash1 = hashValue('test-input'); + const hash2 = hashValue('test-input'); + expect(hash1).toBe(hash2); + }); + + it('should generate different hashes for different inputs', () => { + const hash1 = hashValue('input-1'); + const hash2 = hashValue('input-2'); + expect(hash1).not.toBe(hash2); + }); + + it('should generate a valid SHA256 hash', () => { + const hash = hashValue('test'); + expect(hash).toMatch(/^[a-f0-9]{64}$/); + }); }); - it('should parse git@ URL as git type', async () => { - const result = await parseInstallSource('git@github.com:owner/repo.git'); - expect(result.type).toBe('git'); + describe('getExtensionId', () => { + it('should use hashed name when no install metadata', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const id = getExtensionId(config); + expect(id).toBe(hashValue('test-ext')); + }); + + it('should use hashed source for local install', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const metadata = { type: 'local' as const, source: '/path/to/ext' }; + const id = getExtensionId(config, metadata); + expect(id).toBe(hashValue('/path/to/ext')); + }); + + it('should use GitHub URL for git install', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const metadata = { + type: 'git' as const, + source: 'https://github.com/owner/repo', + }; + const id = getExtensionId(config, metadata); + expect(id).toBe(hashValue('https://github.com/owner/repo')); + }); }); - it('should parse sso:// URL as git type', async () => { - const result = await parseInstallSource('sso://some/path'); - expect(result.type).toBe('git'); + describe('extensionConsentString', () => { + it('should generate basic consent string', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const consent = extensionConsentString(config); + expect(consent).toContain('Installing extension "test-ext"'); + expect(consent).toContain( + 'Extensions may introduce unexpected behavior', + ); + }); + + it('should include MCP servers in consent string', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + mcpServers: { + 'my-server': { command: 'node', args: ['server.js'] }, + }, + }; + const consent = extensionConsentString(config); + expect(consent).toContain( + 'This extension will run the following MCP servers', + ); + expect(consent).toContain('my-server'); + }); + + it('should include commands in consent string', () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const consent = extensionConsentString(config, ['cmd1', 'cmd2']); + expect(consent).toContain( + 'This extension will add the following commands', + ); + expect(consent).toContain('cmd1, cmd2'); + }); + + it('should include context file info', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + contextFileName: 'CONTEXT.md', + }; + const consent = extensionConsentString(config); + expect(consent).toContain('CONTEXT.md'); + }); + + it('should include excluded tools', () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + excludeTools: ['tool1', 'tool2'], + }; + const consent = extensionConsentString(config); + expect(consent).toContain('exclude the following core tools'); + }); }); - it('should parse marketplace URL correctly', async () => { - const result = await parseInstallSource( - 'https://example.com/marketplace:plugin-name', - ); - expect(result.type).toBe('marketplace'); - expect(result.marketplace?.pluginName).toBe('plugin-name'); + describe('maybeRequestConsentOrFail', () => { + it('should request consent for new installation', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail(config, requestConsent, []); + + expect(requestConsent).toHaveBeenCalledTimes(1); + }); + + it('should throw if user declines consent', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const requestConsent = vi.fn().mockResolvedValue(false); + + await expect( + maybeRequestConsentOrFail(config, requestConsent, []), + ).rejects.toThrow('Installation cancelled'); + }); + + it('should skip consent if config unchanged during update', async () => { + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '0.9.0', + }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail( + config, + requestConsent, + [], + [], + [], + previousConfig, + ); + + expect(requestConsent).not.toHaveBeenCalled(); + }); + + it('should request consent if config changed during update', async () => { + const config: ExtensionConfig = { + name: 'test-ext', + version: '1.0.0', + mcpServers: { server: { command: 'node' } }, + }; + const previousConfig: ExtensionConfig = { + name: 'test-ext', + version: '0.9.0', + }; + const requestConsent = vi.fn().mockResolvedValue(true); + + await maybeRequestConsentOrFail( + config, + requestConsent, + [], + [], + [], + previousConfig, + ); + + expect(requestConsent).toHaveBeenCalledTimes(1); + }); }); - it('should throw for non-existent local path', async () => { - await expect( - parseInstallSource('/nonexistent/path/to/extension'), - ).rejects.toThrow('Install source not found'); + describe('parseInstallSource', () => { + it('should parse HTTPS URL as git type', async () => { + const result = await parseInstallSource( + 'https://github.com/owner/repo', + ); + expect(result.type).toBe('git'); + expect(result.source).toBe('https://github.com/owner/repo'); + }); + + it('should parse HTTP URL as git type', async () => { + const result = await parseInstallSource('http://example.com/repo'); + expect(result.type).toBe('git'); + }); + + it('should parse git@ URL as git type', async () => { + const result = await parseInstallSource( + 'git@github.com:owner/repo.git', + ); + expect(result.type).toBe('git'); + }); + + it('should parse sso:// URL as git type', async () => { + const result = await parseInstallSource('sso://some/path'); + expect(result.type).toBe('git'); + }); + + it('should parse marketplace URL correctly', async () => { + const result = await parseInstallSource( + 'https://example.com/marketplace:plugin-name', + ); + expect(result.type).toBe('marketplace'); + expect(result.marketplace?.pluginName).toBe('plugin-name'); + }); + + it('should throw for non-existent local path', async () => { + await expect( + parseInstallSource('/nonexistent/path/to/extension'), + ).rejects.toThrow('Install source not found'); + }); }); }); }); diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index d33a4ec6720..7a14554d459 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -374,7 +374,11 @@ export class ExtensionManager { /** * Enables an extension at the specified scope. */ - enableExtension(name: string, scope: SettingScope, cwd?: string): void { + async enableExtension( + name: string, + scope: SettingScope, + cwd?: string, + ): Promise { const currentDir = cwd ?? this.workspaceDir; if ( scope === SettingScope.System || @@ -382,7 +386,7 @@ export class ExtensionManager { ) { throw new Error('System and SystemDefaults scopes are not supported.'); } - const extension = this.loadExtensionByName(name, currentDir); + const extension = await this.loadExtensionByName(name, currentDir); if (!extension) { throw new Error(`Extension with name ${name} does not exist.`); } @@ -391,12 +395,17 @@ export class ExtensionManager { this.enableByPath(name, true, scopePath); const config = getTelemetryConfig(currentDir, this.telemetrySettings); logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); + await this.refreshTools(extension); } /** * Disables an extension at the specified scope. */ - disableExtension(name: string, scope: SettingScope, cwd?: string): void { + async disableExtension( + name: string, + scope: SettingScope, + cwd?: string, + ): Promise { const currentDir = cwd ?? this.workspaceDir; const config = getTelemetryConfig(currentDir, this.telemetrySettings); if ( @@ -405,7 +414,7 @@ export class ExtensionManager { ) { throw new Error('System and SystemDefaults scopes are not supported.'); } - const extension = this.loadExtensionByName(name, currentDir); + const extension = await this.loadExtensionByName(name, currentDir); if (!extension) { throw new Error(`Extension with name ${name} does not exist.`); } @@ -413,6 +422,7 @@ export class ExtensionManager { scope === SettingScope.Workspace ? currentDir : os.homedir(); this.disableByPath(name, true, scopePath); logExtensionDisable(config, new ExtensionDisableEvent(name, scope)); + await this.refreshTools(extension); } /** @@ -936,6 +946,7 @@ export class ExtensionManager { 'success', ), ); + this.refreshTools(extension); } else { logExtensionInstallEvent( telemetryConfig, @@ -952,7 +963,11 @@ export class ExtensionManager { if (tempDir) { await fs.promises.rm(tempDir, { recursive: true, force: true }); } - if (localSourcePath !== tempDir) { + if ( + localSourcePath !== tempDir && + installMetadata.type !== 'link' && + installMetadata.type !== 'local' + ) { await fs.promises.rm(localSourcePath, { recursive: true, force: true, @@ -1231,8 +1246,26 @@ export class ExtensionManager { async refreshMemory(): Promise { if (!this.config) return; + // refresh mcp servers + // FIXME: restart all mcp servers, can be optimized by only restarting changed ones and move to 'refreshTools' + this.config.getToolRegistry().restartMcpServers(); + // refresh skills this.config.getSkillManager().refreshCache(); + // refresh subagents this.config.getSubagentManager().refreshCache(); + // refresh context files + this.config.refreshHierarchicalMemory(); + } + + async refreshTools(extension: Extension): Promise { + if (!this.config) return; + if (extension.excludeTools && extension.excludeTools.length > 0) { + const geminiClient = this.config?.getGeminiClient(); + if (geminiClient?.isInitialized()) { + await geminiClient.setTools(); + } + } + this.refreshMemory(); } } diff --git a/packages/core/src/tools/mcp-client-manager.test.ts b/packages/core/src/tools/mcp-client-manager.test.ts index 9611f823be9..ff2cb60fcb0 100644 --- a/packages/core/src/tools/mcp-client-manager.test.ts +++ b/packages/core/src/tools/mcp-client-manager.test.ts @@ -8,8 +8,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { McpClientManager } from './mcp-client-manager.js'; import { McpClient } from './mcp-client.js'; import type { ToolRegistry } from './tool-registry.js'; -import type { PromptRegistry } from '../prompts/prompt-registry.js'; -import type { WorkspaceContext } from '../utils/workspaceContext.js'; import type { Config } from '../config/config.js'; vi.mock('./mcp-client.js', async () => { @@ -38,19 +36,16 @@ describe('McpClientManager', () => { vi.mocked(McpClient).mockReturnValue( mockedMcpClient as unknown as McpClient, ); - const manager = new McpClientManager( - { - 'test-server': {}, - }, - '', - {} as ToolRegistry, - {} as PromptRegistry, - false, - {} as WorkspaceContext, - ); - await manager.discoverAllMcpTools({ + const mockConfig = { isTrustedFolder: () => true, - } as unknown as Config); + getMcpServers: () => ({ 'test-server': {} }), + getMcpServerCommand: () => undefined, + getPromptRegistry: () => ({}), + getWorkspaceContext: () => ({}), + getDebugMode: () => false, + } as unknown as Config; + const manager = new McpClientManager(mockConfig, {} as ToolRegistry); + await manager.discoverAllMcpTools(mockConfig); expect(mockedMcpClient.connect).toHaveBeenCalledOnce(); expect(mockedMcpClient.discover).toHaveBeenCalledOnce(); }); @@ -65,19 +60,16 @@ describe('McpClientManager', () => { vi.mocked(McpClient).mockReturnValue( mockedMcpClient as unknown as McpClient, ); - const manager = new McpClientManager( - { - 'test-server': {}, - }, - '', - {} as ToolRegistry, - {} as PromptRegistry, - false, - {} as WorkspaceContext, - ); - await manager.discoverAllMcpTools({ + const mockConfig = { isTrustedFolder: () => false, - } as unknown as Config); + getMcpServers: () => ({ 'test-server': {} }), + getMcpServerCommand: () => undefined, + getPromptRegistry: () => ({}), + getWorkspaceContext: () => ({}), + getDebugMode: () => false, + } as unknown as Config; + const manager = new McpClientManager(mockConfig, {} as ToolRegistry); + await manager.discoverAllMcpTools(mockConfig); expect(mockedMcpClient.connect).not.toHaveBeenCalled(); expect(mockedMcpClient.discover).not.toHaveBeenCalled(); }); diff --git a/packages/core/src/tools/mcp-client-manager.ts b/packages/core/src/tools/mcp-client-manager.ts index a8b482363ec..354776c8d0c 100644 --- a/packages/core/src/tools/mcp-client-manager.ts +++ b/packages/core/src/tools/mcp-client-manager.ts @@ -4,10 +4,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { Config, MCPServerConfig } from '../config/config.js'; +import type { Config } from '../config/config.js'; import { isSdkMcpServerConfig } from '../config/config.js'; import type { ToolRegistry } from './tool-registry.js'; -import type { PromptRegistry } from '../prompts/prompt-registry.js'; import { McpClient, MCPDiscoveryState, @@ -16,7 +15,6 @@ import { import type { SendSdkMcpMessage } from './mcp-client.js'; import { getErrorMessage } from '../utils/errors.js'; import type { EventEmitter } from 'node:events'; -import type { WorkspaceContext } from '../utils/workspaceContext.js'; /** * Manages the lifecycle of multiple MCP clients, including local child processes. @@ -25,32 +23,21 @@ import type { WorkspaceContext } from '../utils/workspaceContext.js'; */ export class McpClientManager { private clients: Map = new Map(); - private readonly mcpServers: Record; - private readonly mcpServerCommand: string | undefined; private readonly toolRegistry: ToolRegistry; - private readonly promptRegistry: PromptRegistry; - private readonly debugMode: boolean; - private readonly workspaceContext: WorkspaceContext; + private readonly cliConfig: Config; private discoveryState: MCPDiscoveryState = MCPDiscoveryState.NOT_STARTED; private readonly eventEmitter?: EventEmitter; private readonly sendSdkMcpMessage?: SendSdkMcpMessage; constructor( - mcpServers: Record, - mcpServerCommand: string | undefined, + config: Config, toolRegistry: ToolRegistry, - promptRegistry: PromptRegistry, - debugMode: boolean, - workspaceContext: WorkspaceContext, eventEmitter?: EventEmitter, sendSdkMcpMessage?: SendSdkMcpMessage, ) { - this.mcpServers = mcpServers; - this.mcpServerCommand = mcpServerCommand; + this.cliConfig = config; this.toolRegistry = toolRegistry; - this.promptRegistry = promptRegistry; - this.debugMode = debugMode; - this.workspaceContext = workspaceContext; + this.eventEmitter = eventEmitter; this.sendSdkMcpMessage = sendSdkMcpMessage; } @@ -67,8 +54,8 @@ export class McpClientManager { await this.stop(); const servers = populateMcpServerCommand( - this.mcpServers, - this.mcpServerCommand, + this.cliConfig.getMcpServers() || {}, + this.cliConfig.getMcpServerCommand(), ); this.discoveryState = MCPDiscoveryState.IN_PROGRESS; @@ -85,9 +72,9 @@ export class McpClientManager { name, config, this.toolRegistry, - this.promptRegistry, - this.workspaceContext, - this.debugMode, + this.cliConfig.getPromptRegistry(), + this.cliConfig.getWorkspaceContext(), + this.cliConfig.getDebugMode(), sdkCallback, ); this.clients.set(name, client); diff --git a/packages/core/src/tools/tool-registry.ts b/packages/core/src/tools/tool-registry.ts index 9b641647a8d..4db7bd78978 100644 --- a/packages/core/src/tools/tool-registry.ts +++ b/packages/core/src/tools/tool-registry.ts @@ -181,12 +181,8 @@ export class ToolRegistry { ) { this.config = config; this.mcpClientManager = new McpClientManager( - this.config.getMcpServers() ?? {}, - this.config.getMcpServerCommand(), + this.config, this, - this.config.getPromptRegistry(), - this.config.getDebugMode(), - this.config.getWorkspaceContext(), eventEmitter, sendSdkMcpMessage, ); From f10fcc8dc920bfa65997749951a907d451965bcd Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Fri, 16 Jan 2026 19:02:22 +0800 Subject: [PATCH 11/30] fix: hot refresh agents --- packages/core/src/config/config.ts | 12 ++-- .../core/src/extension/extensionManager.ts | 66 +++++++------------ packages/core/src/skills/skill-manager.ts | 12 +++- .../core/src/subagents/subagent-manager.ts | 2 +- 4 files changed, 39 insertions(+), 53 deletions(-) diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index ee1c560781f..c74449fb948 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -458,7 +458,6 @@ export class Config { private gitService: GitService | undefined = undefined; private sessionService: SessionService | undefined = undefined; private chatRecordingService: ChatRecordingService | undefined = undefined; - private extensionContextFilePaths: string[] = []; private readonly checkpointing: boolean; private readonly proxy: string | undefined; private readonly cwd: string; @@ -697,12 +696,6 @@ export class Config { } await this.extensionManager.refreshCache(); - const activeExtensions = await this.extensionManager - .getLoadedExtensions() - .filter((e) => e.isActive); - this.extensionContextFilePaths = activeExtensions.flatMap( - (e) => e.contextFiles, - ); await this.refreshHierarchicalMemory(); @@ -1287,8 +1280,11 @@ export class Config { } getExtensionContextFilePaths(): string[] { + const extensionContextFilePaths = this.getActiveExtensions().flatMap( + (e) => e.contextFiles, + ); return [ - ...this.extensionContextFilePaths, + ...extensionContextFilePaths, ...(this.outputLanguageFilePath ? [this.outputLanguageFilePath] : []), ]; } diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 7a14554d459..350ed693329 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -143,9 +143,6 @@ export enum ExtensionUpdateState { UNKNOWN = 'unknown', } -/** Extension storage level - user level or project/workspace level */ -export type ExtensionLevel = 'user' | 'project'; - export interface ExtensionManagerOptions { /** Working directory for project-level extensions */ workspaceDir?: string; @@ -275,8 +272,7 @@ async function convertGeminiOrClaudeExtension( * Reference: SkillManager pattern for level-based management */ export class ExtensionManager { - // Level-based cache (reference: SkillManager) - private extensionCache: Map | null = null; + private extensionCache: Map | null = null; // Enablement configuration (directly implemented) private readonly configDir: string; @@ -386,7 +382,9 @@ export class ExtensionManager { ) { throw new Error('System and SystemDefaults scopes are not supported.'); } - const extension = await this.loadExtensionByName(name, currentDir); + const extension = this.getLoadedExtensions().find( + (ext) => ext.name === name, + ); if (!extension) { throw new Error(`Extension with name ${name} does not exist.`); } @@ -395,6 +393,7 @@ export class ExtensionManager { this.enableByPath(name, true, scopePath); const config = getTelemetryConfig(currentDir, this.telemetrySettings); logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); + extension.isActive = true; await this.refreshTools(extension); } @@ -414,7 +413,9 @@ export class ExtensionManager { ) { throw new Error('System and SystemDefaults scopes are not supported.'); } - const extension = await this.loadExtensionByName(name, currentDir); + const extension = this.getLoadedExtensions().find( + (ext) => ext.name === name, + ); if (!extension) { throw new Error(`Extension with name ${name} does not exist.`); } @@ -422,6 +423,7 @@ export class ExtensionManager { scope === SettingScope.Workspace ? currentDir : os.homedir(); this.disableByPath(name, true, scopePath); logExtensionDisable(config, new ExtensionDisableEvent(name, scope)); + extension.isActive = false; await this.refreshTools(extension); } @@ -499,46 +501,18 @@ export class ExtensionManager { * Refreshes the extension cache from disk. */ async refreshCache(): Promise { - this.extensionCache = new Map(); - this.extensionCache.set('user', await this.loadExtensionsAtLevel('user')); - this.extensionCache.set( - 'project', - await this.loadExtensionsAtLevel('project'), - ); + this.extensionCache = new Map(); + const extensions = await this.loadExtensionsFromDir(os.homedir()); + extensions.forEach((extension) => { + this.extensionCache!.set(extension.name, extension); + }); } getLoadedExtensions(): Extension[] { if (!this.extensionCache) { return []; } - return [ - ...(this.extensionCache?.get('user') ?? []), - ...(this.extensionCache?.get('project') ?? []), - ]; - } - - /** - * Lists extensions at a specific level. - */ - listExtensionsAtLevel(level: ExtensionLevel): Extension[] { - if (!this.extensionCache) { - return []; - } - return this.extensionCache?.get(level) ?? []; - } - - private async loadExtensionsAtLevel( - level: ExtensionLevel, - ): Promise { - if (level === 'user') { - return await this.loadExtensionsFromDir(os.homedir()); - } else { - // project level - if (path.resolve(this.workspaceDir) === path.resolve(os.homedir())) { - return []; - } - return await this.loadExtensionsFromDir(this.workspaceDir); - } + return [...this.extensionCache!.values()]; } // ========================================================================== @@ -632,6 +606,7 @@ export class ExtensionManager { isActive: this.isEnabled(config.name, this.workspaceDir), config, settings: config.settings, + excludeTools: config.excludeTools, contextFiles: [], }; @@ -934,6 +909,10 @@ export class ExtensionManager { throw new Error(`Extension not found`); } + if (this.extensionCache) { + this.extensionCache.set(extension.name, extension); + } + if (isUpdate) { logExtensionUpdateEvent( telemetryConfig, @@ -1052,9 +1031,14 @@ export class ExtensionManager { force: true, }); + if (this.extensionCache) { + this.extensionCache.delete(extension.name); + } + if (isUpdate) return; this.removeEnablementConfig(extension.name); + this.refreshTools(extension); logExtensionUninstall( telemetryConfig, diff --git a/packages/core/src/skills/skill-manager.ts b/packages/core/src/skills/skill-manager.ts index 9fc5273390a..3919e8cea08 100644 --- a/packages/core/src/skills/skill-manager.ts +++ b/packages/core/src/skills/skill-manager.ts @@ -136,8 +136,14 @@ export class SkillManager { return projectSkill; } - // Try user level - return this.findSkillByNameAtLevel(name, 'user'); + // Try user level first + const userSkill = await this.findSkillByNameAtLevel(name, 'user'); + if (userSkill) { + return userSkill; + } + + // Try extension level + return this.findSkillByNameAtLevel(name, 'extension'); } /** @@ -374,7 +380,7 @@ export class SkillManager { } if (level === 'extension') { - const extensions = this.config.getExtensions(); + const extensions = this.config.getActiveExtensions(); const skills: SkillConfig[] = []; for (const extension of extensions) { extension.skills?.forEach((skill) => { diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 443ff1e7ce9..2e1aa472fd0 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -776,7 +776,7 @@ export class SubagentManager { } if (level === 'extension') { - const extensions = this.config.getExtensions(); + const extensions = this.config.getActiveExtensions(); return extensions.flatMap((extension) => extension.agents || []); } From 592bf2bad11340eb178c560cafebeccb601bb152 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Fri, 16 Jan 2026 19:58:08 +0800 Subject: [PATCH 12/30] fix: auto update error --- packages/core/src/extension/extensionManager.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 350ed693329..4a923f6dedc 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -1139,7 +1139,7 @@ export class ExtensionManager { extension: Extension, currentState: ExtensionUpdateState, callback: (extensionName: string, state: ExtensionUpdateState) => void, - enableExtensionReloading?: boolean, + enableExtensionReloading: boolean = true, ): Promise { if (currentState === ExtensionUpdateState.UPDATING) { return undefined; @@ -1205,7 +1205,7 @@ export class ExtensionManager { async updateAllUpdatableExtensions( extensionsState: Map, callback: (extensionName: string, state: ExtensionUpdateState) => void, - enableExtensionReloading?: boolean, + enableExtensionReloading: boolean = true, ): Promise { const extensions = this.getLoadedExtensions(); return ( From c8b0efa4d931c47d401b7c715aae8560952a4b9e Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 10:08:21 +0800 Subject: [PATCH 13/30] feat: add i18n --- packages/cli/src/i18n/locales/de.js | 48 ++++++++++++ packages/cli/src/i18n/locales/en.js | 46 +++++++++++ packages/cli/src/i18n/locales/ru.js | 47 ++++++++++++ packages/cli/src/i18n/locales/zh.js | 44 +++++++++++ .../src/ui/CommandFormatMigrationNudge.tsx | 20 +++-- .../cli/src/ui/commands/extensionsCommand.ts | 76 +++++++++++++------ 6 files changed, 249 insertions(+), 32 deletions(-) diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index fa42218549e..b8a188528b8 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -151,6 +151,7 @@ export default { 'Project Level ({{path}})': 'Projektebene ({{path}})', 'User Level ({{path}})': 'Benutzerebene ({{path}})', 'Built-in Agents': 'Integrierte Agenten', + 'Extension Agents': 'Erweiterungs-Agenten', 'Using: {{count}} agents': 'Verwendet: {{count}} Agenten', 'View Agent': 'Agent anzeigen', 'Edit Agent': 'Agent bearbeiten', @@ -348,6 +349,40 @@ export default { 'List active extensions': 'Aktive Erweiterungen auflisten', 'Update extensions. Usage: update |--all': 'Erweiterungen aktualisieren. Verwendung: update |--all', + 'Disable an extension': 'Erweiterung deaktivieren', + 'Enable an extension': 'Erweiterung aktivieren', + 'Install an extension from a git repo or local path': + 'Erweiterung aus Git-Repository oder lokalem Pfad installieren', + 'Uninstall an extension': 'Erweiterung deinstallieren', + 'No extensions installed.': 'Keine Erweiterungen installiert.', + 'Usage: /extensions update |--all': + 'Verwendung: /extensions update |--all', + 'Extension "{{name}}" not found.': 'Erweiterung "{{name}}" nicht gefunden.', + 'No extensions to update.': 'Keine Erweiterungen zum Aktualisieren.', + 'Usage: /extensions install ': + 'Verwendung: /extensions install ', + 'Installing extension from "{{source}}"...': + 'Installiere Erweiterung von "{{source}}"...', + 'Extension "{{name}}" installed successfully.': + 'Erweiterung "{{name}}" erfolgreich installiert.', + 'Failed to install extension from "{{source}}": {{error}}': + 'Fehler beim Installieren der Erweiterung von "{{source}}": {{error}}', + 'Usage: /extensions uninstall ': + 'Verwendung: /extensions uninstall ', + 'Uninstalling extension "{{name}}"...': + 'Deinstalliere Erweiterung "{{name}}"...', + 'Extension "{{name}}" uninstalled successfully.': + 'Erweiterung "{{name}}" erfolgreich deinstalliert.', + 'Failed to uninstall extension "{{name}}": {{error}}': + 'Fehler beim Deinstallieren der Erweiterung "{{name}}": {{error}}', + 'Usage: /extensions {{command}} [--scope=]': + 'Verwendung: /extensions {{command}} [--scope=]', + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': + 'Nicht unterstützter Bereich "{{scope}}", sollte "user" oder "workspace" sein', + 'Extension "{{name}}" disabled for scope "{{scope}}"': + 'Erweiterung "{{name}}" für Bereich "{{scope}}" deaktiviert', + 'Extension "{{name}}" enabled for scope "{{scope}}"': + 'Erweiterung "{{name}}" für Bereich "{{scope}}" aktiviert', 'manage IDE integration': 'IDE-Integration verwalten', 'check status of IDE integration': 'Status der IDE-Integration prüfen', 'install required IDE companion for {{ideName}}': @@ -985,6 +1020,19 @@ export default { 'Session start time is unavailable, cannot calculate stats.': 'Sitzungsstartzeit nicht verfügbar, Statistiken können nicht berechnet werden.', + // ============================================================================ + // Command Format Migration + // ============================================================================ + 'Command Format Migration': 'Befehlsformat-Migration', + 'Found {{count}} TOML command file:': '{{count}} TOML-Befehlsdatei gefunden:', + 'Found {{count}} TOML command files:': + '{{count}} TOML-Befehlsdateien gefunden:', + '... and {{count}} more': '... und {{count}} weitere', + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?': + 'Das TOML-Format ist veraltet. Möchten Sie sie ins Markdown-Format migrieren?', + '(Backups will be created and original files will be preserved)': + '(Backups werden erstellt und Originaldateien werden beibehalten)', + // ============================================================================ // Loading Phrases // ============================================================================ diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 51461f4cb4b..756903e43ed 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -152,6 +152,7 @@ export default { 'Project Level ({{path}})': 'Project Level ({{path}})', 'User Level ({{path}})': 'User Level ({{path}})', 'Built-in Agents': 'Built-in Agents', + 'Extension Agents': 'Extension Agents', 'Using: {{count}} agents': 'Using: {{count}} agents', 'View Agent': 'View Agent', 'Edit Agent': 'Edit Agent', @@ -344,6 +345,39 @@ export default { 'List active extensions': 'List active extensions', 'Update extensions. Usage: update |--all': 'Update extensions. Usage: update |--all', + 'Disable an extension': 'Disable an extension', + 'Enable an extension': 'Enable an extension', + 'Install an extension from a git repo or local path': + 'Install an extension from a git repo or local path', + 'Uninstall an extension': 'Uninstall an extension', + 'No extensions installed.': 'No extensions installed.', + 'Usage: /extensions update |--all': + 'Usage: /extensions update |--all', + 'Extension "{{name}}" not found.': 'Extension "{{name}}" not found.', + 'No extensions to update.': 'No extensions to update.', + 'Usage: /extensions install ': 'Usage: /extensions install ', + 'Installing extension from "{{source}}"...': + 'Installing extension from "{{source}}"...', + 'Extension "{{name}}" installed successfully.': + 'Extension "{{name}}" installed successfully.', + 'Failed to install extension from "{{source}}": {{error}}': + 'Failed to install extension from "{{source}}": {{error}}', + 'Usage: /extensions uninstall ': + 'Usage: /extensions uninstall ', + 'Uninstalling extension "{{name}}"...': + 'Uninstalling extension "{{name}}"...', + 'Extension "{{name}}" uninstalled successfully.': + 'Extension "{{name}}" uninstalled successfully.', + 'Failed to uninstall extension "{{name}}": {{error}}': + 'Failed to uninstall extension "{{name}}": {{error}}', + 'Usage: /extensions {{command}} [--scope=]': + 'Usage: /extensions {{command}} [--scope=]', + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"', + 'Extension "{{name}}" disabled for scope "{{scope}}"': + 'Extension "{{name}}" disabled for scope "{{scope}}"', + 'Extension "{{name}}" enabled for scope "{{scope}}"': + 'Extension "{{name}}" enabled for scope "{{scope}}"', 'manage IDE integration': 'manage IDE integration', 'check status of IDE integration': 'check status of IDE integration', 'install required IDE companion for {{ideName}}': @@ -958,6 +992,18 @@ export default { 'Session start time is unavailable, cannot calculate stats.': 'Session start time is unavailable, cannot calculate stats.', + // ============================================================================ + // Command Format Migration + // ============================================================================ + 'Command Format Migration': 'Command Format Migration', + 'Found {{count}} TOML command file:': 'Found {{count}} TOML command file:', + 'Found {{count}} TOML command files:': 'Found {{count}} TOML command files:', + '... and {{count}} more': '... and {{count}} more', + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?': + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?', + '(Backups will be created and original files will be preserved)': + '(Backups will be created and original files will be preserved)', + // ============================================================================ // Loading Phrases // ============================================================================ diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index 82f2436efb4..9f9bfb89681 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -155,6 +155,7 @@ export default { 'Project Level ({{path}})': 'Уровень проекта ({{path}})', 'User Level ({{path}})': 'Уровень пользователя ({{path}})', 'Built-in Agents': 'Встроенные агенты', + 'Extension Agents': 'Агенты расширений', 'Using: {{count}} agents': 'Используется: {{count}} агент(ов)', 'View Agent': 'Просмотреть агента', 'Edit Agent': 'Редактировать агента', @@ -349,6 +350,39 @@ export default { 'List active extensions': 'Показать активные расширения', 'Update extensions. Usage: update |--all': 'Обновить расширения. Использование: update |--all', + 'Disable an extension': 'Отключить расширение', + 'Enable an extension': 'Включить расширение', + 'Install an extension from a git repo or local path': + 'Установить расширение из Git-репозитория или локального пути', + 'Uninstall an extension': 'Удалить расширение', + 'No extensions installed.': 'Расширения не установлены.', + 'Usage: /extensions update |--all': + 'Использование: /extensions update <имена-расширений>|--all', + 'Extension "{{name}}" not found.': 'Расширение "{{name}}" не найдено.', + 'No extensions to update.': 'Нет расширений для обновления.', + 'Usage: /extensions install ': + 'Использование: /extensions install <источник>', + 'Installing extension from "{{source}}"...': + 'Установка расширения из "{{source}}"...', + 'Extension "{{name}}" installed successfully.': + 'Расширение "{{name}}" успешно установлено.', + 'Failed to install extension from "{{source}}": {{error}}': + 'Не удалось установить расширение из "{{source}}": {{error}}', + 'Usage: /extensions uninstall ': + 'Использование: /extensions uninstall <имя-расширения>', + 'Uninstalling extension "{{name}}"...': 'Удаление расширения "{{name}}"...', + 'Extension "{{name}}" uninstalled successfully.': + 'Расширение "{{name}}" успешно удалено.', + 'Failed to uninstall extension "{{name}}": {{error}}': + 'Не удалось удалить расширение "{{name}}": {{error}}', + 'Usage: /extensions {{command}} [--scope=]': + 'Использование: /extensions {{command}} <расширение> [--scope=]', + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': + 'Неподдерживаемая область "{{scope}}", должна быть "user" или "workspace"', + 'Extension "{{name}}" disabled for scope "{{scope}}"': + 'Расширение "{{name}}" отключено для области "{{scope}}"', + 'Extension "{{name}}" enabled for scope "{{scope}}"': + 'Расширение "{{name}}" включено для области "{{scope}}"', 'manage IDE integration': 'Управление интеграцией с IDE', 'check status of IDE integration': 'Проверить статус интеграции с IDE', 'install required IDE companion for {{ideName}}': @@ -975,6 +1009,19 @@ export default { 'Session start time is unavailable, cannot calculate stats.': 'Время начала сессии недоступно, невозможно рассчитать статистику.', + // ============================================================================ + // Command Format Migration + // ============================================================================ + 'Command Format Migration': 'Миграция формата команд', + 'Found {{count}} TOML command file:': 'Найден {{count}} файл команд TOML:', + 'Found {{count}} TOML command files:': + 'Найдено {{count}} файлов команд TOML:', + '... and {{count}} more': '... и ещё {{count}}', + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?': + 'Формат TOML устарел. Хотите перенести их в формат Markdown?', + '(Backups will be created and original files will be preserved)': + '(Будут созданы резервные копии, исходные файлы будут сохранены)', + // ============================================================================ // Loading Phrases // ============================================================================ diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index a1b9c203352..883ebb994f0 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -149,6 +149,7 @@ export default { 'Project Level ({{path}})': '项目级 ({{path}})', 'User Level ({{path}})': '用户级 ({{path}})', 'Built-in Agents': '内置代理', + 'Extension Agents': '扩展代理', 'Using: {{count}} agents': '使用中: {{count}} 个代理', 'View Agent': '查看代理', 'Edit Agent': '编辑代理', @@ -331,6 +332,37 @@ export default { 'List active extensions': '列出活动扩展', 'Update extensions. Usage: update |--all': '更新扩展。用法:update |--all', + 'Disable an extension': '禁用扩展', + 'Enable an extension': '启用扩展', + 'Install an extension from a git repo or local path': + '从 Git 仓库或本地路径安装扩展', + 'Uninstall an extension': '卸载扩展', + 'No extensions installed.': '未安装扩展。', + 'Usage: /extensions update |--all': + '用法:/extensions update <扩展名>|--all', + 'Extension "{{name}}" not found.': '未找到扩展 "{{name}}"。', + 'No extensions to update.': '没有可更新的扩展。', + 'Usage: /extensions install ': '用法:/extensions install <来源>', + 'Installing extension from "{{source}}"...': + '正在从 "{{source}}" 安装扩展...', + 'Extension "{{name}}" installed successfully.': '扩展 "{{name}}" 安装成功。', + 'Failed to install extension from "{{source}}": {{error}}': + '从 "{{source}}" 安装扩展失败:{{error}}', + 'Usage: /extensions uninstall ': + '用法:/extensions uninstall <扩展名>', + 'Uninstalling extension "{{name}}"...': '正在卸载扩展 "{{name}}"...', + 'Extension "{{name}}" uninstalled successfully.': + '扩展 "{{name}}" 卸载成功。', + 'Failed to uninstall extension "{{name}}": {{error}}': + '卸载扩展 "{{name}}" 失败:{{error}}', + 'Usage: /extensions {{command}} [--scope=]': + '用法:/extensions {{command}} <扩展> [--scope=]', + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': + '不支持的作用域 "{{scope}}",应为 "user" 或 "workspace"', + 'Extension "{{name}}" disabled for scope "{{scope}}"': + '扩展 "{{name}}" 已在作用域 "{{scope}}" 中禁用', + 'Extension "{{name}}" enabled for scope "{{scope}}"': + '扩展 "{{name}}" 已在作用域 "{{scope}}" 中启用', 'manage IDE integration': '管理 IDE 集成', 'check status of IDE integration': '检查 IDE 集成状态', 'install required IDE companion for {{ideName}}': @@ -911,6 +943,18 @@ export default { 'Session start time is unavailable, cannot calculate stats.': '会话开始时间不可用,无法计算统计信息', + // ============================================================================ + // Command Format Migration + // ============================================================================ + 'Command Format Migration': '命令格式迁移', + 'Found {{count}} TOML command file:': '发现 {{count}} 个 TOML 命令文件:', + 'Found {{count}} TOML command files:': '发现 {{count}} 个 TOML 命令文件:', + '... and {{count}} more': '... 以及其他 {{count}} 个', + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?': + 'TOML 格式已弃用。是否将它们迁移到 Markdown 格式?', + '(Backups will be created and original files will be preserved)': + '(将创建备份,原始文件将保留)', + // ============================================================================ // Loading Phrases // ============================================================================ diff --git a/packages/cli/src/ui/CommandFormatMigrationNudge.tsx b/packages/cli/src/ui/CommandFormatMigrationNudge.tsx index 214193b54db..5e1070e86ef 100644 --- a/packages/cli/src/ui/CommandFormatMigrationNudge.tsx +++ b/packages/cli/src/ui/CommandFormatMigrationNudge.tsx @@ -9,6 +9,7 @@ import type { RadioSelectItem } from './components/shared/RadioButtonSelect.js'; import { RadioButtonSelect } from './components/shared/RadioButtonSelect.js'; import { useKeypress } from './hooks/useKeypress.js'; import { theme } from './semantic-colors.js'; +import { t } from '../i18n/index.js'; export type CommandMigrationNudgeResult = { userSelection: 'yes' | 'no'; @@ -36,14 +37,14 @@ export function CommandFormatMigrationNudge({ const OPTIONS: Array> = [ { - label: 'Yes', + label: t('Yes'), value: { userSelection: 'yes', }, key: 'Yes', }, { - label: 'No (esc)', + label: t('No (esc)'), value: { userSelection: 'no', }, @@ -55,7 +56,7 @@ export function CommandFormatMigrationNudge({ const fileList = count <= 3 ? tomlFiles.map((f) => ` • ${f}`).join('\n') - : ` • ${tomlFiles.slice(0, 2).join('\n • ')}\n • ... and ${count - 2} more`; + : ` • ${tomlFiles.slice(0, 2).join('\n • ')}\n • ${t('... and {{count}} more', { count: String(count - 2) })}`; return ( {'⚠️ '} - Command Format Migration + {t('Command Format Migration')} - {`Found ${count} TOML command file${count > 1 ? 's' : ''}:`} + {count > 1 + ? t('Found {{count}} TOML command files:', { count: String(count) }) + : t('Found {{count}} TOML command file:', { count: String(count) })} {fileList} {''} - The TOML format is deprecated. Would you like to migrate them to - Markdown format? + {t( + 'The TOML format is deprecated. Would you like to migrate them to Markdown format?', + )} - (Backups will be created and original files will be preserved) + {t('(Backups will be created and original files will be preserved)')} diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index 859936914d8..c50db9dbfaa 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -28,7 +28,7 @@ function showMessageIfNoExtensions( context.ui.addItem( { type: MessageType.INFO, - text: 'No extensions installed. Run `/extensions explore` to check out the gallery.', + text: t('No extensions installed.'), }, Date.now(), ); @@ -63,7 +63,7 @@ async function updateAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: 'Usage: /extensions update |--all', + text: t('Usage: /extensions update |--all'), }, Date.now(), ); @@ -113,7 +113,7 @@ async function updateAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: `Extension ${name} not found.`, + text: t('Extension "{{name}}" not found.', { name }), }, Date.now(), ); @@ -137,7 +137,7 @@ async function updateAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: 'No extensions to update.', + text: t('No extensions to update.'), }, Date.now(), ); @@ -177,7 +177,7 @@ async function installAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: `Usage: /extensions install `, + text: t('Usage: /extensions install '), }, Date.now(), ); @@ -189,7 +189,7 @@ async function installAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Installing extension from "${source}"...`, + text: t('Installing extension from "{{source}}"...', { source }), }, Date.now(), ); @@ -197,7 +197,9 @@ async function installAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Extension "${extension.name}" installed successfully.`, + text: t('Extension "{{name}}" installed successfully.', { + name: extension.name, + }), }, Date.now(), ); @@ -207,9 +209,10 @@ async function installAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: `Failed to install extension from "${source}": ${getErrorMessage( - error, - )}`, + text: t('Failed to install extension from "{{source}}": {{error}}', { + source, + error: getErrorMessage(error), + }), }, Date.now(), ); @@ -231,7 +234,7 @@ async function uninstallAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: `Usage: /extensions uninstall `, + text: t('Usage: /extensions uninstall '), }, Date.now(), ); @@ -241,7 +244,7 @@ async function uninstallAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Uninstalling extension "${name}"...`, + text: t('Uninstalling extension "{{name}}"...', { name }), }, Date.now(), ); @@ -251,7 +254,7 @@ async function uninstallAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Extension "${name}" uninstalled successfully.`, + text: t('Extension "{{name}}" uninstalled successfully.', { name }), }, Date.now(), ); @@ -260,9 +263,10 @@ async function uninstallAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.ERROR, - text: `Failed to uninstall extension "${name}": ${getErrorMessage( - error, - )}`, + text: t('Failed to uninstall extension "{{name}}": {{error}}', { + name, + error: getErrorMessage(error), + }), }, Date.now(), ); @@ -296,7 +300,12 @@ function getEnableDisableContext( context.ui.addItem( { type: MessageType.ERROR, - text: `Usage: /extensions ${context.invocation?.name} [--scope=]`, + text: t( + 'Usage: /extensions {{command}} [--scope=]', + { + command: context.invocation?.name ?? '', + }, + ), }, Date.now(), ); @@ -319,7 +328,12 @@ function getEnableDisableContext( context.ui.addItem( { type: MessageType.ERROR, - text: `Unsupported scope ${parts[2]}, should be one of "user" or "workspace"`, + text: t( + 'Unsupported scope "{{scope}}", should be one of "user" or "workspace"', + { + scope: parts[2], + }, + ), }, Date.now(), ); @@ -356,7 +370,10 @@ async function disableAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Extension "${name}" disabled for the scope "${scope}"`, + text: t('Extension "{{name}}" disabled for scope "{{scope}}"', { + name, + scope, + }), }, Date.now(), ); @@ -374,7 +391,10 @@ async function enableAction(context: CommandContext, args: string) { context.ui.addItem( { type: MessageType.INFO, - text: `Extension "${name}" enabled for the scope "${scope}"`, + text: t('Extension "{{name}}" enabled for scope "{{scope}}"', { + name, + scope, + }), }, Date.now(), ); @@ -441,7 +461,9 @@ const updateExtensionsCommand: SlashCommand = { const disableCommand: SlashCommand = { name: 'disable', - description: 'Disable an extension', + get description() { + return t('Disable an extension'); + }, kind: CommandKind.BUILT_IN, action: disableAction, completion: completeExtensionsAndScopes, @@ -449,7 +471,9 @@ const disableCommand: SlashCommand = { const enableCommand: SlashCommand = { name: 'enable', - description: 'Enable an extension', + get description() { + return t('Enable an extension'); + }, kind: CommandKind.BUILT_IN, action: enableAction, completion: completeExtensionsAndScopes, @@ -457,14 +481,18 @@ const enableCommand: SlashCommand = { const installCommand: SlashCommand = { name: 'install', - description: 'Install an extension from a git repo or local path', + get description() { + return t('Install an extension from a git repo or local path'); + }, kind: CommandKind.BUILT_IN, action: installAction, }; const uninstallCommand: SlashCommand = { name: 'uninstall', - description: 'Uninstall an extension', + get description() { + return t('Uninstall an extension'); + }, kind: CommandKind.BUILT_IN, action: uninstallAction, completion: completeExtensions, From 706cdb2ac1c346e1494111cb63bf887b263bc923 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 10:12:47 +0800 Subject: [PATCH 14/30] fix: merge skillManager change --- packages/core/src/extension/extensionManager.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 4a923f6dedc..31c36c509c7 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -265,12 +265,6 @@ async function convertGeminiOrClaudeExtension( // ExtensionManager Class // ============================================================================ -/** - * ExtensionManager manages extensions at different levels (user/project) - * and directly implements enablement functionality. - * - * Reference: SkillManager pattern for level-based management - */ export class ExtensionManager { private extensionCache: Map | null = null; @@ -493,10 +487,6 @@ export class ExtensionManager { fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2)); } - // ========================================================================== - // Cache management (reference: SkillManager) - // ========================================================================== - /** * Refreshes the extension cache from disk. */ @@ -1234,7 +1224,7 @@ export class ExtensionManager { // FIXME: restart all mcp servers, can be optimized by only restarting changed ones and move to 'refreshTools' this.config.getToolRegistry().restartMcpServers(); // refresh skills - this.config.getSkillManager().refreshCache(); + this.config.getSkillManager()?.refreshCache(); // refresh subagents this.config.getSubagentManager().refreshCache(); // refresh context files From a546e848879858b21d7d55e22eb55ccfc7281c84 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 11:18:01 +0800 Subject: [PATCH 15/30] fix: settings in arg --- packages/cli/src/config/config.ts | 2 +- packages/cli/src/gemini.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index dd3b5a993d4..66f9f7f2580 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -164,7 +164,7 @@ function normalizeOutputFormat( return OutputFormat.TEXT; } -export async function parseArguments(): Promise { +export async function parseArguments(settings: Settings): Promise { let rawArgv = hideBin(process.argv); // hack: if the first argument is the CLI entry point, remove it diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index d908583b7ea..ea2dee43b4d 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -202,7 +202,7 @@ export async function main() { const settings = loadSettings(); await cleanupCheckpoints(); - let argv = await parseArguments(); + let argv = await parseArguments(settings.merged); // Check for invalid input combinations early to prevent crashes if (argv.promptInteractive && !process.stdin.isTTY) { From 6e641b8defdae7183434e2bc4946dc34ee0bebc9 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 14:51:49 +0800 Subject: [PATCH 16/30] feat: add docs --- docs/developers/extensions/extension.md | 80 +++++++- .../extensions/getting-started-extensions.md | 110 ++++++++++- docs/users/features/commands.md | 94 ++++++---- docs/users/features/skills.md | 12 ++ docs/users/features/sub-agents.md | 40 ++-- .../cli/src/commands/extensions/consent.ts | 110 +++++++++++ .../cli/src/commands/extensions/install.ts | 9 +- packages/cli/src/commands/extensions/link.ts | 7 +- .../cli/src/commands/extensions/uninstall.ts | 10 +- packages/cli/src/commands/extensions/utils.ts | 10 +- packages/cli/src/services/command-factory.ts | 9 +- packages/cli/src/ui/AppContainer.tsx | 11 +- .../src/extension/extensionManager.test.ts | 121 ------------ .../core/src/extension/extensionManager.ts | 173 +++++------------- 14 files changed, 468 insertions(+), 328 deletions(-) diff --git a/docs/developers/extensions/extension.md b/docs/developers/extensions/extension.md index 0d2e93eb0c7..2ad06d06d9d 100644 --- a/docs/developers/extensions/extension.md +++ b/docs/developers/extensions/extension.md @@ -4,11 +4,25 @@ Qwen Code extensions package prompts, MCP servers, and custom commands into a fa ## Extension management -We offer a suite of extension management tools using `qwen extensions` commands. +We offer a suite of extension management tools using both `qwen extensions` CLI commands and `/extensions` slash commands within the interactive CLI. -Note that these commands are not supported from within the CLI, although you can list installed extensions using the `/extensions list` subcommand. +### Runtime Extension Management (Slash Commands) -Note that all of these commands will only be reflected in active CLI sessions on restart. +You can manage extensions at runtime within the interactive CLI using `/extensions` slash commands. These commands support hot-reloading, meaning changes take effect immediately without restarting the application. + +| Command | Description | +| ------------------------------------------------------ | --------------------------------------------------------------- | +| `/extensions` or `/extensions list` | List all installed extensions with their status | +| `/extensions install ` | Install an extension from a git URL, local path, or marketplace | +| `/extensions uninstall ` | Uninstall an extension | +| `/extensions enable --scope ` | Enable an extension | +| `/extensions disable --scope ` | Disable an extension | +| `/extensions update ` | Update a specific extension | +| `/extensions update --all` | Update all extensions with available updates | + +### CLI Extension Management + +You can also manage extensions using `qwen extensions` CLI commands. Note that changes made via CLI commands will be reflected in active CLI sessions on restart. ### Installing an extension @@ -98,7 +112,18 @@ The `qwen-extension.json` file contains the configuration for the extension. The } }, "contextFileName": "QWEN.md", - "excludeTools": ["run_shell_command"] + "excludeTools": ["run_shell_command"], + "commands": "commands", + "skills": "skills", + "agents": "agents", + "settings": [ + { + "name": "API Key", + "description": "Your API key for the service", + "envVar": "MY_API_KEY", + "sensitive": true + } + ] } ``` @@ -108,12 +133,18 @@ The `qwen-extension.json` file contains the configuration for the extension. The - Note that all MCP server configuration options are supported except for `trust`. - `contextFileName`: The name of the file that contains the context for the extension. This will be used to load the context from the extension directory. If this property is not used but a `QWEN.md` file is present in your extension directory, then that file will be loaded. - `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. Note that this differs from the MCP server `excludeTools` functionality, which can be listed in the MCP server config. **Important:** Tools specified in `excludeTools` will be disabled for the entire conversation context and will affect all subsequent queries in the current session. +- `commands`: The directory containing custom commands (default: `commands`). Commands are `.md` files that define prompts. +- `skills`: The directory containing custom skills (default: `skills`). Skills are discovered automatically and become available via the `/skills` command. +- `agents`: The directory containing custom subagents (default: `agents`). Subagents are `.yaml` or `.md` files that define specialized AI assistants. +- `settings`: An array of settings that the extension requires. When installing, users will be prompted to provide values for these settings. The values are stored securely and passed to MCP servers as environment variables. When Qwen Code starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence. ### Custom commands -Extensions can provide [custom commands](./cli/commands.md#custom-commands) by placing TOML files in a `commands/` subdirectory within the extension directory. These commands follow the same format as user and project custom commands and use standard naming conventions. +Extensions can provide [custom commands](./cli/commands.md#custom-commands) by placing Markdown files in a `commands/` subdirectory within the extension directory. These commands follow the same format as user and project custom commands and use standard naming conventions. + +> **Note:** The command format has been updated from TOML to Markdown. TOML files are deprecated but still supported. You can migrate existing TOML commands using the automatic migration prompt that appears when TOML files are detected. **Example** @@ -123,15 +154,46 @@ An extension named `gcp` with the following structure: .qwen/extensions/gcp/ ├── qwen-extension.json └── commands/ - ├── deploy.toml + ├── deploy.md └── gcs/ - └── sync.toml + └── sync.md ``` Would provide these commands: -- `/deploy` - Shows as `[gcp] Custom command from deploy.toml` in help -- `/gcs:sync` - Shows as `[gcp] Custom command from sync.toml` in help +- `/deploy` - Shows as `[gcp] Custom command from deploy.md` in help +- `/gcs:sync` - Shows as `[gcp] Custom command from sync.md` in help + +### Custom skills + +Extensions can provide custom skills by placing skill files in a `skills/` subdirectory within the extension directory. Each skill should have a `SKILL.md` file with YAML frontmatter defining the skill's name and description. + +**Example** + +``` +.qwen/extensions/my-extension/ +├── qwen-extension.json +└── skills/ + └── pdf-processor/ + └── SKILL.md +``` + +The skill will be available via the `/skills` command when the extension is active. + +### Custom subagents + +Extensions can provide custom subagents by placing agent configuration files in an `agents/` subdirectory within the extension directory. Agents are defined using YAML or Markdown files. + +**Example** + +``` +.qwen/extensions/my-extension/ +├── qwen-extension.json +└── agents/ + └── testing-expert.yaml +``` + +Extension subagents appear in the subagent manager dialog under "Extension Agents" section. ### Conflict resolution diff --git a/docs/developers/extensions/getting-started-extensions.md b/docs/developers/extensions/getting-started-extensions.md index db4ed35fb0d..3ac0e74ecbe 100644 --- a/docs/developers/extensions/getting-started-extensions.md +++ b/docs/developers/extensions/getting-started-extensions.md @@ -148,22 +148,119 @@ Custom commands provide a way to create shortcuts for complex prompts. Let's add mkdir -p commands/fs ``` -2. Create a file named `commands/fs/grep-code.toml`: +2. Create a file named `commands/fs/grep-code.md`: + + ```markdown + --- + description: Search for a pattern in code and summarize findings + --- - ```toml - prompt = """ Please summarize the findings for the pattern `{{args}}`. Search Results: !{grep -r {{args}} .} - """ ``` This command, `/fs:grep-code`, will take an argument, run the `grep` shell command with it, and pipe the results into a prompt for summarization. +> **Note:** Commands use Markdown format with optional YAML frontmatter. TOML format is deprecated but still supported for backwards compatibility. + After saving the file, restart the Qwen Code. You can now run `/fs:grep-code "some pattern"` to use your new command. -## Step 5: Add a Custom `QWEN.md` +## Step 5: Add Custom Skills and Subagents (Optional) + +Extensions can also provide custom skills and subagents to extend Qwen Code's capabilities. + +### Adding a Custom Skill + +Skills are model-invoked capabilities that the AI can automatically use when relevant. + +1. Create a `skills` directory with a skill subdirectory: + + ```bash + mkdir -p skills/code-analyzer + ``` + +2. Create a `skills/code-analyzer/SKILL.md` file: + + ```markdown + --- + name: code-analyzer + description: Analyzes code structure and provides insights about complexity, dependencies, and potential improvements + --- + + # Code Analyzer + + ## Instructions + + When analyzing code, focus on: + + - Code complexity and maintainability + - Dependencies and coupling + - Potential performance issues + - Suggestions for improvements + + ## Examples + + - "Analyze the complexity of this function" + - "What are the dependencies of this module?" + ``` + +### Adding a Custom Subagent + +Subagents are specialized AI assistants for specific tasks. + +1. Create an `agents` directory: + + ```bash + mkdir -p agents + ``` + +2. Create an `agents/refactoring-expert.md` file: + + ```markdown + --- + name: refactoring-expert + description: Specialized in code refactoring, improving code structure and maintainability + tools: + - read_file + - write_file + - read_many_files + --- + + You are a refactoring specialist focused on improving code quality. + + Your expertise includes: + + - Identifying code smells and anti-patterns + - Applying SOLID principles + - Improving code readability and maintainability + - Safe refactoring with minimal risk + + For each refactoring task: + + 1. Analyze the current code structure + 2. Identify areas for improvement + 3. Propose refactoring steps + 4. Implement changes incrementally + 5. Verify functionality is preserved + ``` + +3. Update your `qwen-extension.json` to include the new directories: + + ```json + { + "name": "my-first-extension", + "version": "1.0.0", + "skills": "skills", + "agents": "agents", + "mcpServers": { ... } + } + ``` + +After restarting Qwen Code, your custom skills will be available via `/skills` and subagents via `/agents manage`. + +## Step 6: Add a Custom `QWEN.md` You can provide persistent context to the model by adding a `QWEN.md` file to your extension. This is useful for giving the model instructions on how to behave or information about your extension's tools. Note that you may not always need this for extensions built to expose commands and prompts. @@ -194,7 +291,7 @@ You can provide persistent context to the model by adding a `QWEN.md` file to yo Restart the CLI again. The model will now have the context from your `QWEN.md` file in every session where the extension is active. -## Step 6: Releasing Your Extension +## Step 7: Releasing Your Extension Once you are happy with your extension, you can share it with others. The two primary ways of releasing extensions are via a Git repository or through GitHub Releases. Using a public Git repository is the simplest method. @@ -207,6 +304,7 @@ You've successfully created a Qwen Code extension! You learned how to: - Bootstrap a new extension from a template. - Add custom tools with an MCP server. - Create convenient custom commands. +- Add custom skills and subagents. - Provide persistent context to the model. - Link your extension for local development. diff --git a/docs/users/features/commands.md b/docs/users/features/commands.md index 5583f349439..1ad7ea1d78e 100644 --- a/docs/users/features/commands.md +++ b/docs/users/features/commands.md @@ -121,6 +121,8 @@ Environment Variables: Commands executed via `!` will set the `QWEN_CODE=1` envi Save frequently used prompts as shortcut commands to improve work efficiency and ensure consistency. +> **Note:** Custom commands now use Markdown format with optional YAML frontmatter. TOML format is deprecated but still supported for backwards compatibility. When TOML files are detected, an automatic migration prompt will be displayed. + ### Quick Overview | Function | Description | Advantages | Priority | Applicable Scenarios | @@ -135,14 +137,34 @@ Priority Rules: Project commands > User commands (project command used when name #### File Path to Command Name Mapping Table -| File Location | Generated Command | Example Call | -| ---------------------------- | ----------------- | --------------------- | -| `~/.qwen/commands/test.toml` | `/test` | `/test Parameter` | -| `/git/commit.toml` | `/git:commit` | `/git:commit Message` | +| File Location | Generated Command | Example Call | +| -------------------------- | ----------------- | --------------------- | +| `~/.qwen/commands/test.md` | `/test` | `/test Parameter` | +| `/git/commit.md` | `/git:commit` | `/git:commit Message` | Naming Rules: Path separator (`/` or `\`) converted to colon (`:`) -### TOML File Format Specification +### Markdown File Format Specification (Recommended) + +Custom commands use Markdown files with optional YAML frontmatter: + +```markdown +--- +description: Optional description (displayed in /help) +--- + +Your prompt content here. +Use {{args}} for parameter injection. +``` + +| Field | Required | Description | Example | +| ------------- | -------- | ---------------------------------------- | ------------------------------------------ | +| `description` | Optional | Command description (displayed in /help) | `description: Code analysis tool` | +| Prompt body | Required | Prompt content sent to model | Any Markdown content after the frontmatter | + +### TOML File Format (Deprecated) + +> **Deprecated:** TOML format is still supported but will be removed in a future version. Please migrate to Markdown format. | Field | Required | Description | Example | | ------------- | -------- | ---------------------------------------- | ------------------------------------------ | @@ -191,15 +213,19 @@ Naming Rules: Path separator (`/` or `\`) converted to colon (`:`) Example: Git Commit Message Generation -``` -# git/commit.toml -description = "Generate Commit message based on staged changes" -prompt = """ +````markdown +--- +description: Generate Commit message based on staged changes +--- + Please generate a Commit message based on the following diff: -diff + +```diff !{git diff --staged} -""" ``` +```` + +```` #### 4. File Content Injection (`@{...}`) @@ -212,36 +238,38 @@ diff Example: Code Review Command -``` -# review.toml -description = "Code review based on best practices" -prompt = """ +```markdown +--- +description: Code review based on best practices +--- + Review {{args}}, reference standards: @{docs/code-standards.md} -""" -``` +```` ### Practical Creation Example #### "Pure Function Refactoring" Command Creation Steps Table -| Operation | Command/Code | -| ----------------------------- | ------------------------------------------- | -| 1. Create directory structure | `mkdir -p ~/.qwen/commands/refactor` | -| 2. Create command file | `touch ~/.qwen/commands/refactor/pure.toml` | -| 3. Edit command content | Refer to the complete code below. | -| 4. Test command | `@file.js` → `/refactor:pure` | - -```# ~/.qwen/commands/refactor/pure.toml -description = "Refactor code to pure function" -prompt = """ - Please analyze code in current context, refactor to pure function. - Requirements: - 1. Provide refactored code - 2. Explain key changes and pure function characteristic implementation - 3. Maintain function unchanged - """ +| Operation | Command/Code | +| ----------------------------- | ----------------------------------------- | +| 1. Create directory structure | `mkdir -p ~/.qwen/commands/refactor` | +| 2. Create command file | `touch ~/.qwen/commands/refactor/pure.md` | +| 3. Edit command content | Refer to the complete code below. | +| 4. Test command | `@file.js` → `/refactor:pure` | + +```markdown +--- +description: Refactor code to pure function +--- + +Please analyze code in current context, refactor to pure function. +Requirements: + +1. Provide refactored code +2. Explain key changes and pure function characteristic implementation +3. Maintain function unchanged ``` ### Custom Command Best Practices Summary diff --git a/docs/users/features/skills.md b/docs/users/features/skills.md index 0e55644ab08..d5b1be9e6e8 100644 --- a/docs/users/features/skills.md +++ b/docs/users/features/skills.md @@ -157,6 +157,18 @@ When `--experimental-skills` is enabled, Qwen Code discovers Skills from: - Personal Skills: `~/.qwen/skills/` - Project Skills: `.qwen/skills/` +- Extension Skills: Skills provided by installed extensions + +### Extension Skills + +Extensions can provide custom skills that become available when the extension is enabled. These skills are stored in the extension's `skills/` directory and follow the same format as personal and project skills. + +Extension skills are automatically discovered and loaded when: + +- The extension is installed and enabled +- The `--experimental-skills` flag is enabled + +To see which extensions provide skills, check the extension's `qwen-extension.json` file for a `skills` field. To view available Skills, ask Qwen Code directly: diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index 3497df09f5e..85ca4aff96a 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -6,11 +6,11 @@ Subagents are specialized AI assistants that handle specific types of tasks with Subagents are independent AI assistants that: -- **Specialize in specific tasks** - Each Subagent is configured with a focused system prompt for particular types of work -- **Have separate context** - They maintain their own conversation history, separate from your main chat -- **Use controlled tools** - You can configure which tools each Subagent has access to -- **Work autonomously** - Once given a task, they work independently until completion or failure -- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time +- **Specialize in specific tasks** - Each Subagent is configured with a focused system prompt for particular types of work +- **Have separate context** - They maintain their own conversation history, separate from your main chat +- **Use controlled tools** - You can configure which tools each Subagent has access to +- **Work autonomously** - Once given a task, they work independently until completion or failure +- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time ## Key Benefits @@ -59,7 +59,7 @@ AI: I'll delegate this to your testing specialist Subagents. ### CLI Commands -Subagents are managed through the `/agents` slash command and its subcommands: +Subagents are managed through the `/agents` slash command and its subcommands: **Usage:**:`/agents create`。Creates a new Subagent through a guided step wizard. @@ -67,12 +67,26 @@ Subagents are managed through the `/agents` slash command and its subcommands: ### Storage Locations -Subagents are stored as Markdown files in two locations: +Subagents are stored as Markdown files in multiple locations: -- **Project-level**: `.qwen/agents/` (takes precedence) -- **User-level**: `~/.qwen/agents/` (fallback) +- **Project-level**: `.qwen/agents/` (highest precedence) +- **User-level**: `~/.qwen/agents/` (fallback) +- **Extension-level**: Provided by installed extensions -This allows you to have both project-specific agents and personal agents that work across all projects. +This allows you to have project-specific agents, personal agents that work across all projects, and extension-provided agents that add specialized capabilities. + +### Extension Subagents + +Extensions can provide custom subagents that become available when the extension is enabled. These agents are stored in the extension's `agents/` directory and follow the same format as personal and project agents. + +Extension subagents: + +- Are automatically discovered when the extension is enabled +- Appear in the `/agents manage` dialog under "Extension Agents" section +- Cannot be edited directly (edit the extension source instead) +- Follow the same configuration format as user-defined agents + +To see which extensions provide subagents, check the extension's `qwen-extension.json` file for an `agents` field. ### File Format @@ -398,7 +412,7 @@ description: Helps with testing, documentation, code review, and deployment --- ``` -**Why:** Focused agents produce better results and are easier to maintain. +**Why:** Focused agents produce better results and are easier to maintain. #### Clear Specialization @@ -422,7 +436,7 @@ description: Works on frontend development tasks --- ``` -**Why:** Specific expertise leads to more targeted and effective assistance. +**Why:** Specific expertise leads to more targeted and effective assistance. #### Actionable Descriptions @@ -440,7 +454,7 @@ description: Reviews code for security vulnerabilities, performance issues, and description: A helpful code reviewer ``` -**Why:** Clear descriptions help the main AI choose the right agent for each task. +**Why:** Clear descriptions help the main AI choose the right agent for each task. ### Configuration Best Practices diff --git a/packages/cli/src/commands/extensions/consent.ts b/packages/cli/src/commands/extensions/consent.ts index 8f0d3123f90..b5c4ddd4f01 100644 --- a/packages/cli/src/commands/extensions/consent.ts +++ b/packages/cli/src/commands/extensions/consent.ts @@ -1,4 +1,11 @@ +import type { + ExtensionConfig, + ExtensionRequestOptions, + SkillConfig, + SubagentConfig, +} from '@qwen-code/qwen-code-core'; import type { ConfirmationRequest } from '../../ui/types.js'; +import chalk from 'chalk'; /** * Requests consent from the user to perform an action, by reading a Y/n @@ -85,3 +92,106 @@ async function promptForConsentInteractive( }); }); } + +/** + * Builds a consent string for installing an extension based on it's + * extensionConfig. + */ +export function extensionConsentString( + extensionConfig: ExtensionConfig, + commands: string[] = [], + skills: SkillConfig[] = [], + subagents: SubagentConfig[] = [], +): string { + const output: string[] = []; + const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); + output.push(`Installing extension "${extensionConfig.name}".`); + output.push( + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + ); + + if (mcpServerEntries.length) { + output.push('This extension will run the following MCP servers:'); + for (const [key, mcpServer] of mcpServerEntries) { + const isLocal = !!mcpServer.command; + const source = + mcpServer.httpUrl ?? + `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; + output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); + } + } + if (commands && commands.length > 0) { + output.push( + `This extension will add the following commands: ${commands.join(', ')}.`, + ); + } + if (extensionConfig.contextFileName) { + output.push( + `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, + ); + } + if (extensionConfig.excludeTools) { + output.push( + `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, + ); + } + if (skills.length > 0) { + output.push('This extension will install the following skills:'); + for (const skill of skills) { + output.push(` * ${chalk.bold(skill.name)}: ${skill.description}`); + } + } + if (subagents.length > 0) { + output.push('This extension will install the following subagents:'); + for (const subagent of subagents) { + output.push(` * ${chalk.bold(subagent.name)}: ${subagent.description}`); + } + } + return output.join('\n'); +} + +/** + * Requests consent from the user to install an extension (extensionConfig), if + * there is any difference between the consent string for `extensionConfig` and + * `previousExtensionConfig`. + * + * Always requests consent if previousExtensionConfig is null. + * + * Throws if the user does not consent. + */ +export const requestConsentOrFail = async ( + requestConsent: (consent: string) => Promise, + options?: ExtensionRequestOptions, +) => { + if (!options) return; + const { + extensionConfig, + commands = [], + skills = [], + subagents = [], + previousExtensionConfig, + previousCommands = [], + previousSkills = [], + previousSubagents = [], + } = options; + const extensionConsent = extensionConsentString( + extensionConfig, + commands, + skills, + subagents, + ); + if (previousExtensionConfig) { + const previousExtensionConsent = extensionConsentString( + previousExtensionConfig, + previousCommands, + previousSkills, + previousSubagents, + ); + if (previousExtensionConsent === extensionConsent) { + return; + } + } + if (!(await requestConsent(extensionConsent))) { + throw new Error(`Installation cancelled for "${extensionConfig.name}".`); + } +}; diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index 2654ac98cb2..64b89003c7a 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -13,7 +13,10 @@ import { import { getErrorMessage } from '../../utils/errors.js'; import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; import { loadSettings } from '../../config/settings.js'; -import { requestConsentNonInteractive } from './consent.js'; +import { + requestConsentOrFail, + requestConsentNonInteractive, +} from './consent.js'; interface InstallArgs { source: string; @@ -39,8 +42,8 @@ export async function handleInstall(args: InstallArgs) { } const requestConsent = args.consent - ? () => Promise.resolve(true) - : requestConsentNonInteractive; + ? () => Promise.resolve() + : requestConsentOrFail.bind(null, requestConsentNonInteractive); const workspaceDir = process.cwd(); const extensionManager = new ExtensionManager({ workspaceDir, diff --git a/packages/cli/src/commands/extensions/link.ts b/packages/cli/src/commands/extensions/link.ts index ab2f946f9bf..d3eff0a6ee2 100644 --- a/packages/cli/src/commands/extensions/link.ts +++ b/packages/cli/src/commands/extensions/link.ts @@ -7,7 +7,10 @@ import type { CommandModule } from 'yargs'; import { type ExtensionInstallMetadata } from '@qwen-code/qwen-code-core'; import { getErrorMessage } from '../../utils/errors.js'; -import { requestConsentNonInteractive } from './consent.js'; +import { + requestConsentNonInteractive, + requestConsentOrFail, +} from './consent.js'; import { getExtensionManager } from './utils.js'; interface InstallArgs { @@ -24,7 +27,7 @@ export async function handleLink(args: InstallArgs) { const extension = await extensionManager.installExtension( installMetadata, - requestConsentNonInteractive, + requestConsentOrFail.bind(null, requestConsentNonInteractive), ); console.log( `Extension "${extension.name}" linked successfully and enabled.`, diff --git a/packages/cli/src/commands/extensions/uninstall.ts b/packages/cli/src/commands/extensions/uninstall.ts index 02ce1cd68fa..9d40f9d55de 100644 --- a/packages/cli/src/commands/extensions/uninstall.ts +++ b/packages/cli/src/commands/extensions/uninstall.ts @@ -7,7 +7,10 @@ import type { CommandModule } from 'yargs'; import { getErrorMessage } from '../../utils/errors.js'; import { ExtensionManager } from '@qwen-code/qwen-code-core'; -import { requestConsentNonInteractive } from './consent.js'; +import { + requestConsentNonInteractive, + requestConsentOrFail, +} from './consent.js'; import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; import { loadSettings } from '../../config/settings.js'; @@ -20,7 +23,10 @@ export async function handleUninstall(args: UninstallArgs) { const workspaceDir = process.cwd(); const extensionManager = new ExtensionManager({ workspaceDir, - requestConsent: requestConsentNonInteractive, + requestConsent: requestConsentOrFail.bind( + null, + requestConsentNonInteractive, + ), isWorkspaceTrusted: !!isWorkspaceTrusted( loadSettings(workspaceDir).merged, ), diff --git a/packages/cli/src/commands/extensions/utils.ts b/packages/cli/src/commands/extensions/utils.ts index 5c30ea39718..49e5f15e51f 100644 --- a/packages/cli/src/commands/extensions/utils.ts +++ b/packages/cli/src/commands/extensions/utils.ts @@ -6,14 +6,20 @@ import { ExtensionManager } from '@qwen-code/qwen-code-core'; import { loadSettings } from '../../config/settings.js'; -import { requestConsentNonInteractive } from './consent.js'; +import { + requestConsentOrFail, + requestConsentNonInteractive, +} from './consent.js'; import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; export async function getExtensionManager(): Promise { const workspaceDir = process.cwd(); const extensionManager = new ExtensionManager({ workspaceDir, - requestConsent: requestConsentNonInteractive, + requestConsent: requestConsentOrFail.bind( + null, + requestConsentNonInteractive, + ), isWorkspaceTrusted: !!isWorkspaceTrusted(loadSettings(workspaceDir).merged), }); await extensionManager.refreshCache(); diff --git a/packages/cli/src/services/command-factory.ts b/packages/cli/src/services/command-factory.ts index fbe2da5c50f..95eec70c3a5 100644 --- a/packages/cli/src/services/command-factory.ts +++ b/packages/cli/src/services/command-factory.ts @@ -68,11 +68,6 @@ export function createSlashCommandFromDefinition( .map((segment) => segment.replaceAll(':', '_')) .join(':'); - // Prefix command name with extension name if provided - const commandName = extensionName - ? `${extensionName}:${baseCommandName}` - : baseCommandName; - // Add extension name tag for extension commands const defaultDescription = `Custom command from ${path.basename(filePath)}`; let description = definition.description || defaultDescription; @@ -109,7 +104,7 @@ export function createSlashCommandFromDefinition( } return { - name: commandName, + name: baseCommandName, description, kind: CommandKind.FILE, extensionName, @@ -119,7 +114,7 @@ export function createSlashCommandFromDefinition( ): Promise => { if (!context.invocation) { console.error( - `[FileCommandLoader] Critical error: Command '${commandName}' was executed without invocation context.`, + `[FileCommandLoader] Critical error: Command '${baseCommandName}' was executed without invocation context.`, ); return { type: 'submit_prompt', diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 1bd40baa4e7..d0d708cb2e9 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -102,7 +102,10 @@ import { processVisionSwitchOutcome } from './hooks/useVisionAutoSwitch.js'; import { useSubagentCreateDialog } from './hooks/useSubagentCreateDialog.js'; import { useAgentsManagerDialog } from './hooks/useAgentsManagerDialog.js'; import { useAttentionNotifications } from './hooks/useAttentionNotifications.js'; -import { requestConsentInteractive } from '../commands/extensions/consent.js'; +import { + requestConsentInteractive, + requestConsentOrFail, +} from '../commands/extensions/consent.js'; const CTRL_EXIT_PROMPT_DURATION_MS = 1000; @@ -165,8 +168,10 @@ export const AppContainer = (props: AppContainerProps) => { const extensionManager = config.getExtensionManager(); - extensionManager.setRequestConsent(async (description) => - requestConsentInteractive(description, addConfirmUpdateExtensionRequest), + extensionManager.setRequestConsent( + requestConsentOrFail.bind(null, (description) => + requestConsentInteractive(description, addConfirmUpdateExtensionRequest), + ), ); const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 550c76c20cc..cfa6feb9732 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -20,8 +20,6 @@ import { validateName, getExtensionId, hashValue, - extensionConsentString, - maybeRequestConsentOrFail, parseInstallSource, type ExtensionConfig, } from './extensionManager.js'; @@ -889,125 +887,6 @@ describe('extension tests', () => { }); }); - describe('extensionConsentString', () => { - it('should generate basic consent string', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const consent = extensionConsentString(config); - expect(consent).toContain('Installing extension "test-ext"'); - expect(consent).toContain( - 'Extensions may introduce unexpected behavior', - ); - }); - - it('should include MCP servers in consent string', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - mcpServers: { - 'my-server': { command: 'node', args: ['server.js'] }, - }, - }; - const consent = extensionConsentString(config); - expect(consent).toContain( - 'This extension will run the following MCP servers', - ); - expect(consent).toContain('my-server'); - }); - - it('should include commands in consent string', () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const consent = extensionConsentString(config, ['cmd1', 'cmd2']); - expect(consent).toContain( - 'This extension will add the following commands', - ); - expect(consent).toContain('cmd1, cmd2'); - }); - - it('should include context file info', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - contextFileName: 'CONTEXT.md', - }; - const consent = extensionConsentString(config); - expect(consent).toContain('CONTEXT.md'); - }); - - it('should include excluded tools', () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - excludeTools: ['tool1', 'tool2'], - }; - const consent = extensionConsentString(config); - expect(consent).toContain('exclude the following core tools'); - }); - }); - - describe('maybeRequestConsentOrFail', () => { - it('should request consent for new installation', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const requestConsent = vi.fn().mockResolvedValue(true); - - await maybeRequestConsentOrFail(config, requestConsent, []); - - expect(requestConsent).toHaveBeenCalledTimes(1); - }); - - it('should throw if user declines consent', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const requestConsent = vi.fn().mockResolvedValue(false); - - await expect( - maybeRequestConsentOrFail(config, requestConsent, []), - ).rejects.toThrow('Installation cancelled'); - }); - - it('should skip consent if config unchanged during update', async () => { - const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; - const previousConfig: ExtensionConfig = { - name: 'test-ext', - version: '0.9.0', - }; - const requestConsent = vi.fn().mockResolvedValue(true); - - await maybeRequestConsentOrFail( - config, - requestConsent, - [], - [], - [], - previousConfig, - ); - - expect(requestConsent).not.toHaveBeenCalled(); - }); - - it('should request consent if config changed during update', async () => { - const config: ExtensionConfig = { - name: 'test-ext', - version: '1.0.0', - mcpServers: { server: { command: 'node' } }, - }; - const previousConfig: ExtensionConfig = { - name: 'test-ext', - version: '0.9.0', - }; - const requestConsent = vi.fn().mockResolvedValue(true); - - await maybeRequestConsentOrFail( - config, - requestConsent, - [], - [], - [], - previousConfig, - ); - - expect(requestConsent).toHaveBeenCalledTimes(1); - }); - }); - describe('parseInstallSource', () => { it('should parse HTTPS URL as git type', async () => { const result = await parseInstallSource( diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 31c36c509c7..0d146af9a43 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -143,6 +143,17 @@ export enum ExtensionUpdateState { UNKNOWN = 'unknown', } +export type ExtensionRequestOptions = { + extensionConfig: ExtensionConfig; + commands?: string[]; + skills?: SkillConfig[]; + subagents?: SubagentConfig[]; + previousExtensionConfig?: ExtensionConfig; + previousCommands?: string[]; + previousSkills?: SkillConfig[]; + previousSubagents?: SubagentConfig[]; +}; + export interface ExtensionManagerOptions { /** Working directory for project-level extensions */ workspaceDir?: string; @@ -151,7 +162,7 @@ export interface ExtensionManagerOptions { isWorkspaceTrusted: boolean; telemetrySettings?: TelemetrySettings; config?: Config; - requestConsent?: (consent: string) => Promise; + requestConsent?: (options?: ExtensionRequestOptions) => Promise; } // ============================================================================ @@ -199,10 +210,7 @@ function getContextFileNames(config: ExtensionConfig): string[] { return config.contextFileName; } -async function loadCommandsFromDir( - dir: string, - extensionName: string, -): Promise { +async function loadCommandsFromDir(dir: string): Promise { const globOptions = { nodir: true, dot: true, @@ -221,12 +229,11 @@ async function loadCommandsFromDir( 0, relativePathWithExt.length - 3, ); - const baseCommandName = relativePath + const commandName = relativePath .split(path.sep) .map((segment) => segment.replaceAll(':', '_')) .join(':'); - const commandName = `${extensionName}:${baseCommandName}`; return commandName; }); @@ -277,7 +284,7 @@ export class ExtensionManager { private config?: Config; private telemetrySettings?: TelemetrySettings; private isWorkspaceTrusted: boolean; - private requestConsent: (consent: string) => Promise; + private requestConsent: (options?: ExtensionRequestOptions) => Promise; constructor(options: ExtensionManagerOptions) { this.workspaceDir = options.workspaceDir ?? process.cwd(); @@ -289,8 +296,7 @@ export class ExtensionManager { this.configDir, 'extension-enablement.json', ); - this.requestConsent = - options.requestConsent || (() => Promise.resolve(true)); + this.requestConsent = options.requestConsent || (() => Promise.resolve()); this.config = options.config; this.telemetrySettings = options.telemetrySettings; this.isWorkspaceTrusted = options.isWorkspaceTrusted; @@ -301,7 +307,7 @@ export class ExtensionManager { } setRequestConsent( - requestConsent: (consent: string) => Promise, + requestConsent: (options?: ExtensionRequestOptions) => Promise, ): void { this.requestConsent = requestConsent; } @@ -611,7 +617,6 @@ export class ExtensionManager { extension.commands = await loadCommandsFromDir( `${effectiveExtensionPath}/commands`, - extension.name, ); extension.contextFiles = getContextFileNames(config) @@ -692,7 +697,7 @@ export class ExtensionManager { */ async installExtension( installMetadata: ExtensionInstallMetadata, - requestConsent?: (consent: string) => Promise, + requestConsent?: (options?: ExtensionRequestOptions) => Promise, cwd?: string, previousExtensionConfig?: ExtensionConfig, ): Promise { @@ -827,27 +832,40 @@ export class ExtensionManager { const commands = await loadCommandsFromDir( `${localSourcePath}/commands`, - newExtensionConfig.name, ); const previousCommands = previous?.commands ?? []; const skills = await loadSkillsFromDir(`${localSourcePath}/skills`); const previousSkills = previous?.skills ?? []; - const agents = await loadSubagentFromDir(`${localSourcePath}/agents`); - const previousAgents = previous?.agents ?? []; - - await maybeRequestConsentOrFail( - newExtensionConfig, - requestConsent || this.requestConsent, - commands, - skills, - agents, - previousExtensionConfig, - previousCommands, - previousSkills, - previousAgents, + const subagents = await loadSubagentFromDir( + `${localSourcePath}/agents`, ); + const previousSubagents = previous?.agents ?? []; + + if (requestConsent) { + await requestConsent({ + extensionConfig: newExtensionConfig, + commands, + skills, + subagents, + previousExtensionConfig, + previousCommands, + previousSkills, + previousSubagents, + }); + } else { + this.requestConsent({ + extensionConfig: newExtensionConfig, + commands, + skills, + subagents, + previousExtensionConfig, + previousCommands, + previousSkills, + previousSubagents, + }); + } const extensionStorage = new ExtensionStorage(newExtensionName); const destinationPath = extensionStorage.getExtensionDir(); @@ -1087,7 +1105,7 @@ export class ExtensionManager { async performWorkspaceExtensionMigration( extensions: Extension[], - requestConsent: (consent: string) => Promise, + requestConsent: (options?: ExtensionRequestOptions) => Promise, ): Promise { const failedInstallNames: string[] = []; @@ -1281,105 +1299,6 @@ export function validateName(name: string) { } } -/** - * Builds a consent string for installing an extension based on it's - * extensionConfig. - */ -export function extensionConsentString( - extensionConfig: ExtensionConfig, - commands: string[] = [], - skills: SkillConfig[] = [], - subagents: SubagentConfig[] = [], -): string { - const output: string[] = []; - const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); - output.push(`Installing extension "${extensionConfig.name}".`); - output.push( - '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', - ); - - if (mcpServerEntries.length) { - output.push('This extension will run the following MCP servers:'); - for (const [key, mcpServer] of mcpServerEntries) { - const isLocal = !!mcpServer.command; - const source = - mcpServer.httpUrl ?? - `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; - output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); - } - } - if (commands && commands.length > 0) { - output.push( - `This extension will add the following commands: ${commands.join(', ')}.`, - ); - } - if (extensionConfig.contextFileName) { - output.push( - `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, - ); - } - if (extensionConfig.excludeTools) { - output.push( - `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, - ); - } - if (skills.length > 0) { - output.push('This extension will install the following skills:'); - for (const skill of skills) { - output.push(` * ${chalk.bold(skill.name)}: ${skill.description}`); - } - } - if (subagents.length > 0) { - output.push('This extension will install the following subagents:'); - for (const subagent of subagents) { - output.push(` * ${chalk.bold(subagent.name)}: ${subagent.description}`); - } - } - return output.join('\n'); -} - -/** - * Requests consent from the user to install an extension (extensionConfig), if - * there is any difference between the consent string for `extensionConfig` and - * `previousExtensionConfig`. - * - * Always requests consent if previousExtensionConfig is null. - * - * Throws if the user does not consent. - */ -export async function maybeRequestConsentOrFail( - extensionConfig: ExtensionConfig, - requestConsent: (consent: string) => Promise, - commands: string[], - skills: SkillConfig[] = [], - subagents: SubagentConfig[] = [], - previousExtensionConfig?: ExtensionConfig, - previousCommands: string[] = [], - previousSkills: SkillConfig[] = [], - previousSubagents: SubagentConfig[] = [], -) { - const extensionConsent = extensionConsentString( - extensionConfig, - commands, - skills, - subagents, - ); - if (previousExtensionConfig) { - const previousExtensionConsent = extensionConsentString( - previousExtensionConfig, - previousCommands, - previousSkills, - previousSubagents, - ); - if (previousExtensionConsent === extensionConsent) { - return; - } - } - if (!(await requestConsent(extensionConsent))) { - throw new Error(`Installation cancelled for "${extensionConfig.name}".`); - } -} - export async function parseInstallSource( source: string, ): Promise { From f8e41fb7fa9946272f9774b21f57041045ab364f Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 15:09:24 +0800 Subject: [PATCH 17/30] fix i18n --- .../cli/src/commands/extensions/consent.ts | 45 ++++++++++++++----- packages/cli/src/i18n/locales/de.js | 22 +++++++++ packages/cli/src/i18n/locales/en.js | 21 +++++++++ packages/cli/src/i18n/locales/ru.js | 20 +++++++++ packages/cli/src/i18n/locales/zh.js | 19 ++++++++ 5 files changed, 115 insertions(+), 12 deletions(-) diff --git a/packages/cli/src/commands/extensions/consent.ts b/packages/cli/src/commands/extensions/consent.ts index b5c4ddd4f01..65886e64644 100644 --- a/packages/cli/src/commands/extensions/consent.ts +++ b/packages/cli/src/commands/extensions/consent.ts @@ -6,6 +6,7 @@ import type { } from '@qwen-code/qwen-code-core'; import type { ConfirmationRequest } from '../../ui/types.js'; import chalk from 'chalk'; +import { t } from '../../i18n/index.js'; /** * Requests consent from the user to perform an action, by reading a Y/n @@ -21,7 +22,7 @@ export async function requestConsentNonInteractive( ): Promise { console.info(consentDescription); const result = await promptForConsentNonInteractive( - 'Do you want to continue? [Y/n]: ', + t('Do you want to continue? [Y/n]: '), ); return result; } @@ -40,7 +41,7 @@ export async function requestConsentInteractive( addExtensionUpdateConfirmationRequest: (value: ConfirmationRequest) => void, ): Promise { return promptForConsentInteractive( - consentDescription + '\n\nDo you want to continue?', + consentDescription + '\n\n' + t('Do you want to continue?'), addExtensionUpdateConfirmationRequest, ); } @@ -105,44 +106,60 @@ export function extensionConsentString( ): string { const output: string[] = []; const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); - output.push(`Installing extension "${extensionConfig.name}".`); output.push( - '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + t('Installing extension "{{name}}".', { name: extensionConfig.name }), + ); + output.push( + t( + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + ), ); if (mcpServerEntries.length) { - output.push('This extension will run the following MCP servers:'); + output.push(t('This extension will run the following MCP servers:')); for (const [key, mcpServer] of mcpServerEntries) { const isLocal = !!mcpServer.command; const source = mcpServer.httpUrl ?? `${mcpServer.command || ''}${mcpServer.args ? ' ' + mcpServer.args.join(' ') : ''}`; - output.push(` * ${key} (${isLocal ? 'local' : 'remote'}): ${source}`); + output.push( + ` * ${key} (${isLocal ? t('local') : t('remote')}): ${source}`, + ); } } if (commands && commands.length > 0) { output.push( - `This extension will add the following commands: ${commands.join(', ')}.`, + t('This extension will add the following commands: {{commands}}.', { + commands: commands.join(', '), + }), ); } if (extensionConfig.contextFileName) { + const fileName = Array.isArray(extensionConfig.contextFileName) + ? extensionConfig.contextFileName.join(', ') + : extensionConfig.contextFileName; output.push( - `This extension will append info to your QWEN.md context using ${extensionConfig.contextFileName}`, + t( + 'This extension will append info to your QWEN.md context using {{fileName}}', + { fileName }, + ), ); } if (extensionConfig.excludeTools) { output.push( - `This extension will exclude the following core tools: ${extensionConfig.excludeTools}`, + t('This extension will exclude the following core tools: {{tools}}', { + tools: extensionConfig.excludeTools.join(', '), + }), ); } if (skills.length > 0) { - output.push('This extension will install the following skills:'); + output.push(t('This extension will install the following skills:')); for (const skill of skills) { output.push(` * ${chalk.bold(skill.name)}: ${skill.description}`); } } if (subagents.length > 0) { - output.push('This extension will install the following subagents:'); + output.push(t('This extension will install the following subagents:')); for (const subagent of subagents) { output.push(` * ${chalk.bold(subagent.name)}: ${subagent.description}`); } @@ -192,6 +209,10 @@ export const requestConsentOrFail = async ( } } if (!(await requestConsent(extensionConsent))) { - throw new Error(`Installation cancelled for "${extensionConfig.name}".`); + throw new Error( + t('Installation cancelled for "{{name}}".', { + name: extensionConfig.name, + }), + ); } }; diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index b8a188528b8..d3376443a88 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -383,6 +383,28 @@ export default { 'Erweiterung "{{name}}" für Bereich "{{scope}}" deaktiviert', 'Extension "{{name}}" enabled for scope "{{scope}}"': 'Erweiterung "{{name}}" für Bereich "{{scope}}" aktiviert', + 'Do you want to continue? [Y/n]: ': 'Möchten Sie fortfahren? [Y/n]: ', + 'Do you want to continue?': 'Möchten Sie fortfahren?', + 'Installing extension "{{name}}".': + 'Erweiterung "{{name}}" wird installiert.', + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**': + '**Erweiterungen können unerwartetes Verhalten verursachen. Stellen Sie sicher, dass Sie die Erweiterungsquelle untersucht haben und dem Autor vertrauen.**', + 'This extension will run the following MCP servers:': + 'Diese Erweiterung wird folgende MCP-Server ausführen:', + local: 'lokal', + remote: 'remote', + 'This extension will add the following commands: {{commands}}.': + 'Diese Erweiterung wird folgende Befehle hinzufügen: {{commands}}.', + 'This extension will append info to your QWEN.md context using {{fileName}}': + 'Diese Erweiterung wird Informationen zu Ihrem QWEN.md-Kontext mit {{fileName}} hinzufügen', + 'This extension will exclude the following core tools: {{tools}}': + 'Diese Erweiterung wird folgende Kernwerkzeuge ausschließen: {{tools}}', + 'This extension will install the following skills:': + 'Diese Erweiterung wird folgende Fähigkeiten installieren:', + 'This extension will install the following subagents:': + 'Diese Erweiterung wird folgende Unteragenten installieren:', + 'Installation cancelled for "{{name}}".': + 'Installation von "{{name}}" abgebrochen.', 'manage IDE integration': 'IDE-Integration verwalten', 'check status of IDE integration': 'Status der IDE-Integration prüfen', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 756903e43ed..b1f933ca8b8 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -378,6 +378,27 @@ export default { 'Extension "{{name}}" disabled for scope "{{scope}}"', 'Extension "{{name}}" enabled for scope "{{scope}}"': 'Extension "{{name}}" enabled for scope "{{scope}}"', + 'Do you want to continue? [Y/n]: ': 'Do you want to continue? [Y/n]: ', + 'Do you want to continue?': 'Do you want to continue?', + 'Installing extension "{{name}}".': 'Installing extension "{{name}}".', + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**': + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**', + 'This extension will run the following MCP servers:': + 'This extension will run the following MCP servers:', + local: 'local', + remote: 'remote', + 'This extension will add the following commands: {{commands}}.': + 'This extension will add the following commands: {{commands}}.', + 'This extension will append info to your QWEN.md context using {{fileName}}': + 'This extension will append info to your QWEN.md context using {{fileName}}', + 'This extension will exclude the following core tools: {{tools}}': + 'This extension will exclude the following core tools: {{tools}}', + 'This extension will install the following skills:': + 'This extension will install the following skills:', + 'This extension will install the following subagents:': + 'This extension will install the following subagents:', + 'Installation cancelled for "{{name}}".': + 'Installation cancelled for "{{name}}".', 'manage IDE integration': 'manage IDE integration', 'check status of IDE integration': 'check status of IDE integration', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index 9f9bfb89681..977d4354ba3 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -383,6 +383,26 @@ export default { 'Расширение "{{name}}" отключено для области "{{scope}}"', 'Extension "{{name}}" enabled for scope "{{scope}}"': 'Расширение "{{name}}" включено для области "{{scope}}"', + 'Do you want to continue? [Y/n]: ': 'Хотите продолжить? [Y/n]: ', + 'Do you want to continue?': 'Хотите продолжить?', + 'Installing extension "{{name}}".': 'Установка расширения "{{name}}".', + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**': + '**Расширения могут вызывать неожиданное поведение. Убедитесь, что вы изучили источник расширения и доверяете автору.**', + 'This extension will run the following MCP servers:': + 'Это расширение запустит следующие MCP-серверы:', + local: 'локальный', + remote: 'удалённый', + 'This extension will add the following commands: {{commands}}.': + 'Это расширение добавит следующие команды: {{commands}}.', + 'This extension will append info to your QWEN.md context using {{fileName}}': + 'Это расширение добавит информацию в ваш контекст QWEN.md с помощью {{fileName}}', + 'This extension will exclude the following core tools: {{tools}}': + 'Это расширение исключит следующие основные инструменты: {{tools}}', + 'This extension will install the following skills:': + 'Это расширение установит следующие навыки:', + 'This extension will install the following subagents:': + 'Это расширение установит следующие подагенты:', + 'Installation cancelled for "{{name}}".': 'Установка "{{name}}" отменена.', 'manage IDE integration': 'Управление интеграцией с IDE', 'check status of IDE integration': 'Проверить статус интеграции с IDE', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index b1381cf8365..dea6001918d 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -363,6 +363,25 @@ export default { '扩展 "{{name}}" 已在作用域 "{{scope}}" 中禁用', 'Extension "{{name}}" enabled for scope "{{scope}}"': '扩展 "{{name}}" 已在作用域 "{{scope}}" 中启用', + 'Do you want to continue? [Y/n]: ': '是否继续?[Y/n]:', + 'Do you want to continue?': '是否继续?', + 'Installing extension "{{name}}".': '正在安装扩展 "{{name}}"。', + '**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**': + '**扩展可能会引入意外行为。请确保您已调查过扩展源并信任作者。**', + 'This extension will run the following MCP servers:': + '此扩展将运行以下 MCP 服务器:', + local: '本地', + remote: '远程', + 'This extension will add the following commands: {{commands}}.': + '此扩展将添加以下命令:{{commands}}。', + 'This extension will append info to your QWEN.md context using {{fileName}}': + '此扩展将使用 {{fileName}} 向您的 QWEN.md 上下文追加信息', + 'This extension will exclude the following core tools: {{tools}}': + '此扩展将排除以下核心工具:{{tools}}', + 'This extension will install the following skills:': '此扩展将安装以下技能:', + 'This extension will install the following subagents:': + '此扩展将安装以下子代理:', + 'Installation cancelled for "{{name}}".': '已取消安装 "{{name}}"。', 'manage IDE integration': '管理 IDE 集成', 'check status of IDE integration': '检查 IDE 集成状态', 'install required IDE companion for {{ideName}}': From 8b4626a2beed6a2a39291e1282792d0b2bdc64e5 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 19:40:16 +0800 Subject: [PATCH 18/30] fix test --- packages/cli/src/commands/extensions.test.tsx | 106 ++ .../src/commands/extensions/consent.test.ts | 273 +++ .../src/commands/extensions/disable.test.ts | 129 ++ .../src/commands/extensions/enable.test.ts | 136 ++ .../cli/src/commands/extensions/link.test.ts | 95 + .../cli/src/commands/extensions/list.test.ts | 90 + .../src/commands/extensions/update.test.ts | 262 +++ .../cli/src/commands/extensions/utils.test.ts | 66 + .../cli/src/config/config.integration.test.ts | 11 +- packages/cli/src/config/config.test.ts | 1633 ++--------------- packages/cli/src/config/config.ts | 17 +- .../src/ui/commands/extensionsCommand.test.ts | 16 +- 12 files changed, 1340 insertions(+), 1494 deletions(-) create mode 100644 packages/cli/src/commands/extensions.test.tsx create mode 100644 packages/cli/src/commands/extensions/consent.test.ts create mode 100644 packages/cli/src/commands/extensions/disable.test.ts create mode 100644 packages/cli/src/commands/extensions/enable.test.ts create mode 100644 packages/cli/src/commands/extensions/link.test.ts create mode 100644 packages/cli/src/commands/extensions/list.test.ts create mode 100644 packages/cli/src/commands/extensions/update.test.ts create mode 100644 packages/cli/src/commands/extensions/utils.test.ts diff --git a/packages/cli/src/commands/extensions.test.tsx b/packages/cli/src/commands/extensions.test.tsx new file mode 100644 index 00000000000..4499fa1eedd --- /dev/null +++ b/packages/cli/src/commands/extensions.test.tsx @@ -0,0 +1,106 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { extensionsCommand } from './extensions.js'; +import { updateCommand } from './extensions/update.js'; +import { disableCommand } from './extensions/disable.js'; +import { enableCommand } from './extensions/enable.js'; +import { linkCommand } from './extensions/link.js'; +import { newCommand } from './extensions/new.js'; +import yargs from 'yargs'; + +describe('extensions command', () => { + it('should have correct command name', () => { + expect(extensionsCommand.command).toBe('extensions '); + }); + + it('should have a description', () => { + expect(extensionsCommand.describe).toBe('Manage Qwen Code extensions.'); + }); + + it('should require a subcommand', () => { + const parser = yargs([]) + .command(extensionsCommand) + .fail(false) + .locale('en'); + + expect(() => parser.parse('extensions')).toThrow(); + }); + + it('should register install subcommand', () => { + const parser = yargs([]) + .command(extensionsCommand) + .fail(false) + .locale('en'); + + // This should throw as 'install' requires a source argument + expect(() => parser.parse('extensions install')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register uninstall subcommand', () => { + const parser = yargs([]) + .command(extensionsCommand) + .fail(false) + .locale('en'); + + expect(() => parser.parse('extensions uninstall')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register list subcommand', () => { + const parser = yargs([]) + .command(extensionsCommand) + .fail(false) + .locale('en'); + + // list doesn't require arguments, so it should not throw + expect(() => parser.parse('extensions list')).not.toThrow(); + }); + + it('should register update subcommand', () => { + const parser = yargs([]).command(updateCommand).fail(false).locale('en'); + + expect(() => parser.parse('update')).toThrow( + 'Either an extension name or --all must be provided', + ); + }); + + it('should register disable subcommand', () => { + const parser = yargs([]).command(disableCommand).fail(false).locale('en'); + + expect(() => parser.parse('disable')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register enable subcommand', () => { + const parser = yargs([]).command(enableCommand).fail(false).locale('en'); + + expect(() => parser.parse('enable')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register link subcommand', () => { + const parser = yargs([]).command(linkCommand).fail(false).locale('en'); + + expect(() => parser.parse('link')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register new subcommand', async () => { + const parser = yargs([]).command(newCommand).fail(false).locale('en'); + + await expect(parser.parseAsync('new')).rejects.toThrow( + 'Not enough non-option arguments', + ); + }); +}); diff --git a/packages/cli/src/commands/extensions/consent.test.ts b/packages/cli/src/commands/extensions/consent.test.ts new file mode 100644 index 00000000000..1b3b2801387 --- /dev/null +++ b/packages/cli/src/commands/extensions/consent.test.ts @@ -0,0 +1,273 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { extensionConsentString, requestConsentOrFail } from './consent.js'; +import type { ExtensionConfig } from '@qwen-code/qwen-code-core'; + +vi.mock('../../i18n/index.js', () => ({ + t: vi.fn((str: string, params?: Record) => { + if (params) { + return Object.entries(params).reduce( + (acc, [key, value]) => acc.replace(`{{${key}}}`, value), + str, + ); + } + return str; + }), +})); + +describe('extensionConsentString', () => { + it('should include extension name', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = extensionConsentString(config); + + expect(result).toContain('Installing extension "test-extension".'); + }); + + it('should include warning message', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = extensionConsentString(config); + + expect(result).toContain('Extensions may introduce unexpected behavior'); + }); + + it('should include MCP servers when present', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + mcpServers: { + 'test-server': { + command: 'node', + args: ['server.js'], + }, + }, + }; + + const result = extensionConsentString(config); + + expect(result).toContain( + 'This extension will run the following MCP servers', + ); + expect(result).toContain('test-server'); + expect(result).toContain('local'); + expect(result).toContain('node server.js'); + }); + + it('should include remote MCP servers', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + mcpServers: { + 'remote-server': { + httpUrl: 'https://example.com/mcp', + }, + }, + }; + + const result = extensionConsentString(config); + + expect(result).toContain('remote'); + expect(result).toContain('https://example.com/mcp'); + }); + + it('should include commands when present', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = extensionConsentString(config, ['command1', 'command2']); + + expect(result).toContain('This extension will add the following commands'); + expect(result).toContain('command1, command2'); + }); + + it('should include context file name when present (string)', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + contextFileName: 'CUSTOM.md', + }; + + const result = extensionConsentString(config); + + expect(result).toContain('CUSTOM.md'); + }); + + it('should include context file name when present (array)', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + contextFileName: ['FILE1.md', 'FILE2.md'], + }; + + const result = extensionConsentString(config); + + expect(result).toContain('FILE1.md, FILE2.md'); + }); + + it('should include excluded tools when present', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + excludeTools: ['tool1', 'tool2'], + }; + + const result = extensionConsentString(config); + + expect(result).toContain( + 'This extension will exclude the following core tools', + ); + expect(result).toContain('tool1, tool2'); + }); + + it('should include skills when present', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = extensionConsentString( + config, + [], + [ + { + name: 'skill1', + description: 'Skill 1 description', + level: 'extension', + filePath: '/test/skill1', + body: 'skill body', + }, + { + name: 'skill2', + description: 'Skill 2 description', + level: 'extension', + filePath: '/test/skill2', + body: 'skill body', + }, + ], + ); + + expect(result).toContain( + 'This extension will install the following skills', + ); + expect(result).toContain('skill1'); + expect(result).toContain('Skill 1 description'); + }); + + it('should include subagents when present', () => { + const config: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + const result = extensionConsentString( + config, + [], + [], + [ + { + name: 'agent1', + description: 'Agent 1 description', + systemPrompt: 'You are agent1', + level: 'extension', + }, + ], + ); + + expect(result).toContain( + 'This extension will install the following subagents', + ); + expect(result).toContain('agent1'); + expect(result).toContain('Agent 1 description'); + }); +}); + +describe('requestConsentOrFail', () => { + let mockRequestConsent: ReturnType; + + beforeEach(() => { + mockRequestConsent = vi.fn(); + vi.clearAllMocks(); + }); + + it('should do nothing when options is undefined', async () => { + await requestConsentOrFail(mockRequestConsent, undefined); + + expect(mockRequestConsent).not.toHaveBeenCalled(); + }); + + it('should request consent for new extension', async () => { + mockRequestConsent.mockResolvedValueOnce(true); + + await requestConsentOrFail(mockRequestConsent, { + extensionConfig: { name: 'test-extension', version: '1.0.0' }, + }); + + expect(mockRequestConsent).toHaveBeenCalled(); + }); + + it('should throw error when user declines consent', async () => { + mockRequestConsent.mockResolvedValueOnce(false); + + await expect( + requestConsentOrFail(mockRequestConsent, { + extensionConfig: { name: 'test-extension', version: '1.0.0' }, + }), + ).rejects.toThrow('Installation cancelled for "test-extension".'); + }); + + it('should skip consent when consent string is unchanged', async () => { + const extensionConfig: ExtensionConfig = { + name: 'test-extension', + version: '1.0.0', + }; + + await requestConsentOrFail(mockRequestConsent, { + extensionConfig, + previousExtensionConfig: extensionConfig, + }); + + expect(mockRequestConsent).not.toHaveBeenCalled(); + }); + + it('should request consent when consent string changes', async () => { + mockRequestConsent.mockResolvedValueOnce(true); + + await requestConsentOrFail(mockRequestConsent, { + extensionConfig: { + name: 'test-extension', + version: '1.0.0', + excludeTools: ['tool1'], + }, + previousExtensionConfig: { name: 'test-extension', version: '1.0.0' }, + }); + + expect(mockRequestConsent).toHaveBeenCalled(); + }); + + it('should request consent when commands change', async () => { + mockRequestConsent.mockResolvedValueOnce(true); + + await requestConsentOrFail(mockRequestConsent, { + extensionConfig: { name: 'test-extension', version: '1.0.0' }, + commands: ['command1'], + previousExtensionConfig: { name: 'test-extension', version: '1.0.0' }, + previousCommands: [], + }); + + expect(mockRequestConsent).toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/src/commands/extensions/disable.test.ts b/packages/cli/src/commands/extensions/disable.test.ts new file mode 100644 index 00000000000..7bde3ee0a0a --- /dev/null +++ b/packages/cli/src/commands/extensions/disable.test.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { disableCommand, handleDisable } from './disable.js'; +import yargs from 'yargs'; +import { SettingScope } from '../../config/settings.js'; + +const mockDisableExtension = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + disableExtension: mockDisableExtension, + }), +})); + +vi.mock('../../utils/errors.js', () => ({ + getErrorMessage: vi.fn((error: Error) => error.message), +})); + +describe('extensions disable command', () => { + it('should fail if no name is provided', () => { + const validationParser = yargs([]) + .command(disableCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('disable')).toThrow( + 'Not enough non-option arguments: got 0, need at least 1', + ); + }); + + it('should fail if invalid scope is provided', () => { + const validationParser = yargs([]) + .command(disableCommand) + .fail(false) + .locale('en'); + expect(() => + validationParser.parse('disable test-extension --scope=invalid'), + ).toThrow(/Invalid scope: invalid/); + }); + + it('should accept valid scope values', () => { + const parser = yargs([]).command(disableCommand).fail(false).locale('en'); + // Just check that the scope option is recognized, actual execution needs name first + expect(() => + parser.parse('disable my-extension --scope=user'), + ).not.toThrow(); + }); +}); + +describe('handleDisable', () => { + let consoleLogSpy: MockInstance; + let consoleErrorSpy: MockInstance; + let processExitSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + processExitSpy = vi + .spyOn(process, 'exit') + .mockImplementation(() => undefined as never); + vi.clearAllMocks(); + }); + + it('should disable an extension with user scope', async () => { + await handleDisable({ + name: 'test-extension', + scope: 'user', + }); + + expect(mockDisableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.User, + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully disabled for scope "user".', + ); + }); + + it('should disable an extension with workspace scope', async () => { + await handleDisable({ + name: 'test-extension', + scope: 'workspace', + }); + + expect(mockDisableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.Workspace, + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully disabled for scope "workspace".', + ); + }); + + it('should default to user scope when no scope is provided', async () => { + await handleDisable({ + name: 'test-extension', + }); + + expect(mockDisableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.User, + ); + }); + + it('should handle errors and exit with code 1', async () => { + mockDisableExtension.mockImplementationOnce(() => { + throw new Error('Disable failed'); + }); + + await handleDisable({ + name: 'test-extension', + scope: 'user', + }); + + expect(consoleErrorSpy).toHaveBeenCalledWith('Disable failed'); + expect(processExitSpy).toHaveBeenCalledWith(1); + }); +}); diff --git a/packages/cli/src/commands/extensions/enable.test.ts b/packages/cli/src/commands/extensions/enable.test.ts new file mode 100644 index 00000000000..374918e0a48 --- /dev/null +++ b/packages/cli/src/commands/extensions/enable.test.ts @@ -0,0 +1,136 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { enableCommand, handleEnable } from './enable.js'; +import yargs from 'yargs'; +import { SettingScope } from '../../config/settings.js'; + +const mockEnableExtension = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + enableExtension: mockEnableExtension, + }), +})); + +vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + FatalConfigError: class FatalConfigError extends Error { + constructor(message: string) { + super(message); + this.name = 'FatalConfigError'; + } + }, + getErrorMessage: (error: Error) => error.message, + }; +}); + +describe('extensions enable command', () => { + it('should fail if no name is provided', () => { + const validationParser = yargs([]) + .command(enableCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('enable')).toThrow( + 'Not enough non-option arguments: got 0, need at least 1', + ); + }); + + it('should fail if invalid scope is provided', () => { + const validationParser = yargs([]) + .command(enableCommand) + .fail(false) + .locale('en'); + expect(() => + validationParser.parse('enable test-extension --scope=invalid'), + ).toThrow(/Invalid scope: invalid/); + }); + + it('should accept valid scope values', () => { + const parser = yargs([]).command(enableCommand).fail(false).locale('en'); + // Just check that the scope option is recognized, actual execution needs name first + expect(() => + parser.parse('enable my-extension --scope=user'), + ).not.toThrow(); + }); +}); + +describe('handleEnable', () => { + let consoleLogSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.clearAllMocks(); + }); + + it('should enable an extension with user scope', async () => { + await handleEnable({ + name: 'test-extension', + scope: 'user', + }); + + expect(mockEnableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.User, + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully enabled for scope "user".', + ); + }); + + it('should enable an extension with workspace scope', async () => { + await handleEnable({ + name: 'test-extension', + scope: 'workspace', + }); + + expect(mockEnableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.Workspace, + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully enabled for scope "workspace".', + ); + }); + + it('should default to user scope when no scope is provided', async () => { + await handleEnable({ + name: 'test-extension', + }); + + expect(mockEnableExtension).toHaveBeenCalledWith( + 'test-extension', + SettingScope.User, + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully enabled in all scopes.', + ); + }); + + it('should throw FatalConfigError when enable fails', async () => { + mockEnableExtension.mockImplementationOnce(() => { + throw new Error('Enable failed'); + }); + + await expect( + handleEnable({ + name: 'test-extension', + scope: 'user', + }), + ).rejects.toThrow('Enable failed'); + }); +}); diff --git a/packages/cli/src/commands/extensions/link.test.ts b/packages/cli/src/commands/extensions/link.test.ts new file mode 100644 index 00000000000..babe4ce9013 --- /dev/null +++ b/packages/cli/src/commands/extensions/link.test.ts @@ -0,0 +1,95 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { linkCommand, handleLink } from './link.js'; +import yargs from 'yargs'; + +const mockInstallExtension = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + installExtension: mockInstallExtension, + }), +})); + +vi.mock('./consent.js', () => ({ + requestConsentNonInteractive: vi.fn().mockResolvedValue(true), + requestConsentOrFail: vi.fn(), +})); + +vi.mock('../../utils/errors.js', () => ({ + getErrorMessage: vi.fn((error: Error) => error.message), +})); + +describe('extensions link command', () => { + it('should fail if no path is provided', () => { + const validationParser = yargs([]) + .command(linkCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('link')).toThrow( + 'Not enough non-option arguments: got 0, need at least 1', + ); + }); + + it('should accept a path argument', () => { + const parser = yargs([]).command(linkCommand).fail(false).locale('en'); + expect(() => parser.parse('link /some/path')).not.toThrow(); + }); +}); + +describe('handleLink', () => { + let consoleLogSpy: MockInstance; + let consoleErrorSpy: MockInstance; + let processExitSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + processExitSpy = vi + .spyOn(process, 'exit') + .mockImplementation(() => undefined as never); + vi.clearAllMocks(); + }); + + it('should link an extension from a local path', async () => { + mockInstallExtension.mockResolvedValueOnce({ name: 'linked-extension' }); + + await handleLink({ + path: '/some/local/path', + }); + + expect(mockInstallExtension).toHaveBeenCalledWith( + { + source: '/some/local/path', + type: 'link', + }, + expect.any(Function), + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "linked-extension" linked successfully and enabled.', + ); + }); + + it('should handle errors and exit with code 1', async () => { + mockInstallExtension.mockRejectedValueOnce(new Error('Link failed')); + + await handleLink({ + path: '/some/local/path', + }); + + expect(consoleErrorSpy).toHaveBeenCalledWith('Link failed'); + expect(processExitSpy).toHaveBeenCalledWith(1); + }); +}); diff --git a/packages/cli/src/commands/extensions/list.test.ts b/packages/cli/src/commands/extensions/list.test.ts new file mode 100644 index 00000000000..01e41941cc0 --- /dev/null +++ b/packages/cli/src/commands/extensions/list.test.ts @@ -0,0 +1,90 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { listCommand, handleList } from './list.js'; +import yargs from 'yargs'; + +const mockGetLoadedExtensions = vi.hoisted(() => vi.fn()); +const mockToOutputString = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + getLoadedExtensions: mockGetLoadedExtensions, + toOutputString: mockToOutputString, + }), +})); + +vi.mock('../../utils/errors.js', () => ({ + getErrorMessage: vi.fn((error: Error) => error.message), +})); + +describe('extensions list command', () => { + it('should parse the list command', () => { + const parser = yargs([]).command(listCommand).fail(false).locale('en'); + expect(() => parser.parse('list')).not.toThrow(); + }); +}); + +describe('handleList', () => { + let consoleLogSpy: MockInstance; + let consoleErrorSpy: MockInstance; + let processExitSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + processExitSpy = vi + .spyOn(process, 'exit') + .mockImplementation(() => undefined as never); + vi.clearAllMocks(); + }); + + it('should display message when no extensions are installed', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([]); + + await handleList(); + + expect(consoleLogSpy).toHaveBeenCalledWith('No extensions installed.'); + }); + + it('should list installed extensions', async () => { + const mockExtensions = [ + { name: 'extension-1', version: '1.0.0' }, + { name: 'extension-2', version: '2.0.0' }, + ]; + mockGetLoadedExtensions.mockReturnValueOnce(mockExtensions); + mockToOutputString.mockImplementation( + (ext) => `${ext.name} (${ext.version})`, + ); + + await handleList(); + + expect(mockGetLoadedExtensions).toHaveBeenCalled(); + expect(mockToOutputString).toHaveBeenCalledTimes(2); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'extension-1 (1.0.0)\n\nextension-2 (2.0.0)', + ); + }); + + it('should handle errors and exit with code 1', async () => { + mockGetLoadedExtensions.mockImplementationOnce(() => { + throw new Error('List failed'); + }); + + await handleList(); + + expect(consoleErrorSpy).toHaveBeenCalledWith('List failed'); + expect(processExitSpy).toHaveBeenCalledWith(1); + }); +}); diff --git a/packages/cli/src/commands/extensions/update.test.ts b/packages/cli/src/commands/extensions/update.test.ts new file mode 100644 index 00000000000..7dfeec1d686 --- /dev/null +++ b/packages/cli/src/commands/extensions/update.test.ts @@ -0,0 +1,262 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { updateCommand, handleUpdate } from './update.js'; +import yargs from 'yargs'; +import { ExtensionUpdateState } from '../../ui/state/extensions.js'; + +const mockGetLoadedExtensions = vi.hoisted(() => vi.fn()); +const mockUpdateExtension = vi.hoisted(() => vi.fn()); +const mockCheckForAllExtensionUpdates = vi.hoisted(() => vi.fn()); +const mockUpdateAllUpdatableExtensions = vi.hoisted(() => vi.fn()); +const mockCheckForExtensionUpdate = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + getLoadedExtensions: mockGetLoadedExtensions, + updateExtension: mockUpdateExtension, + checkForAllExtensionUpdates: mockCheckForAllExtensionUpdates, + updateAllUpdatableExtensions: mockUpdateAllUpdatableExtensions, + }), +})); + +vi.mock('@qwen-code/qwen-code-core', () => ({ + checkForExtensionUpdate: mockCheckForExtensionUpdate, +})); + +vi.mock('../../utils/errors.js', () => ({ + getErrorMessage: vi.fn((error: Error) => error.message), +})); + +vi.mock('../../ui/state/extensions.js', () => ({ + ExtensionUpdateState: { + UPDATE_AVAILABLE: 'update available', + UP_TO_DATE: 'up to date', + ERROR: 'error', + }, +})); + +describe('extensions update command', () => { + it('should fail if neither name nor --all is provided', () => { + const validationParser = yargs([]) + .command(updateCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('update')).toThrow( + 'Either an extension name or --all must be provided', + ); + }); + + it('should fail if both name and --all are provided', () => { + const validationParser = yargs([]) + .command(updateCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('update test-extension --all')).toThrow( + /Arguments .* are mutually exclusive/, + ); + }); + + it('should accept --all flag', () => { + const parser = yargs([]).command(updateCommand).fail(false).locale('en'); + expect(() => parser.parse('update --all')).not.toThrow(); + }); + + it('should accept an extension name', () => { + const parser = yargs([]).command(updateCommand).fail(false).locale('en'); + expect(() => parser.parse('update test-extension')).not.toThrow(); + }); +}); + +describe('handleUpdate', () => { + let consoleLogSpy: MockInstance; + let consoleErrorSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.clearAllMocks(); + }); + + describe('update by name', () => { + it('should show message when extension is not found', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([]); + + await handleUpdate({ name: 'non-existent-extension' }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "non-existent-extension" not found.', + ); + }); + + it('should show message when extension has no install metadata', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([ + { name: 'test-extension', installMetadata: undefined }, + ]); + + await handleUpdate({ name: 'test-extension' }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Unable to install extension "test-extension" due to missing install metadata', + ); + }); + + it('should show message when extension is already up to date', async () => { + const mockExtension = { + name: 'test-extension', + installMetadata: { source: 'test' }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockCheckForExtensionUpdate.mockResolvedValueOnce( + ExtensionUpdateState.UP_TO_DATE, + ); + + await handleUpdate({ name: 'test-extension' }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" is already up to date.', + ); + }); + + it('should update extension when update is available', async () => { + const mockExtension = { + name: 'test-extension', + installMetadata: { source: 'test' }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockCheckForExtensionUpdate.mockResolvedValueOnce( + ExtensionUpdateState.UPDATE_AVAILABLE, + ); + mockUpdateExtension.mockResolvedValueOnce({ + name: 'test-extension', + originalVersion: '1.0.0', + updatedVersion: '2.0.0', + }); + + await handleUpdate({ name: 'test-extension' }); + + expect(mockUpdateExtension).toHaveBeenCalledWith( + mockExtension, + ExtensionUpdateState.UPDATE_AVAILABLE, + expect.any(Function), + ); + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" successfully updated: 1.0.0 → 2.0.0.', + ); + }); + + it('should show up to date message when versions are the same after update', async () => { + const mockExtension = { + name: 'test-extension', + installMetadata: { source: 'test' }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockCheckForExtensionUpdate.mockResolvedValueOnce( + ExtensionUpdateState.UPDATE_AVAILABLE, + ); + mockUpdateExtension.mockResolvedValueOnce({ + name: 'test-extension', + originalVersion: '1.0.0', + updatedVersion: '1.0.0', + }); + + await handleUpdate({ name: 'test-extension' }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "test-extension" is already up to date.', + ); + }); + + it('should handle errors during update', async () => { + const mockExtension = { + name: 'test-extension', + installMetadata: { source: 'test' }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockCheckForExtensionUpdate.mockRejectedValueOnce( + new Error('Update check failed'), + ); + + await handleUpdate({ name: 'test-extension' }); + + expect(consoleErrorSpy).toHaveBeenCalledWith('Update check failed'); + }); + }); + + describe('update all', () => { + it('should show message when no extensions to update', async () => { + mockCheckForAllExtensionUpdates.mockResolvedValueOnce(undefined); + mockUpdateAllUpdatableExtensions.mockResolvedValueOnce([]); + + await handleUpdate({ all: true }); + + expect(consoleLogSpy).toHaveBeenCalledWith('No extensions to update.'); + }); + + it('should update all extensions with updates available', async () => { + mockCheckForAllExtensionUpdates.mockResolvedValueOnce(undefined); + mockUpdateAllUpdatableExtensions.mockResolvedValueOnce([ + { + name: 'extension-1', + originalVersion: '1.0.0', + updatedVersion: '2.0.0', + }, + { + name: 'extension-2', + originalVersion: '1.0.0', + updatedVersion: '1.5.0', + }, + ]); + + await handleUpdate({ all: true }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "extension-1" successfully updated: 1.0.0 → 2.0.0.\n' + + 'Extension "extension-2" successfully updated: 1.0.0 → 1.5.0.', + ); + }); + + it('should filter out extensions with same version after update', async () => { + mockCheckForAllExtensionUpdates.mockResolvedValueOnce(undefined); + mockUpdateAllUpdatableExtensions.mockResolvedValueOnce([ + { + name: 'extension-1', + originalVersion: '1.0.0', + updatedVersion: '2.0.0', + }, + { + name: 'extension-2', + originalVersion: '1.0.0', + updatedVersion: '1.0.0', + }, + ]); + + await handleUpdate({ all: true }); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "extension-1" successfully updated: 1.0.0 → 2.0.0.', + ); + }); + + it('should handle errors during update all', async () => { + mockCheckForAllExtensionUpdates.mockRejectedValueOnce( + new Error('Update all failed'), + ); + + await handleUpdate({ all: true }); + + expect(consoleErrorSpy).toHaveBeenCalledWith('Update all failed'); + }); + }); +}); diff --git a/packages/cli/src/commands/extensions/utils.test.ts b/packages/cli/src/commands/extensions/utils.test.ts new file mode 100644 index 00000000000..2168d2d7ce7 --- /dev/null +++ b/packages/cli/src/commands/extensions/utils.test.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { getExtensionManager } from './utils.js'; + +const mockRefreshCache = vi.fn(); +const mockExtensionManagerInstance = { + refreshCache: mockRefreshCache, +}; + +vi.mock('@qwen-code/qwen-code-core', () => ({ + ExtensionManager: vi + .fn() + .mockImplementation(() => mockExtensionManagerInstance), +})); + +vi.mock('../../config/settings.js', () => ({ + loadSettings: vi.fn().mockReturnValue({ + merged: {}, + }), +})); + +vi.mock('../../config/trustedFolders.js', () => ({ + isWorkspaceTrusted: vi.fn().mockReturnValue({ isTrusted: true }), +})); + +vi.mock('./consent.js', () => ({ + requestConsentOrFail: vi.fn(), + requestConsentNonInteractive: vi.fn(), +})); + +describe('getExtensionManager', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockRefreshCache.mockResolvedValue(undefined); + }); + + it('should return an ExtensionManager instance', async () => { + const manager = await getExtensionManager(); + + expect(manager).toBeDefined(); + expect(manager).toBe(mockExtensionManagerInstance); + }); + + it('should call refreshCache on the ExtensionManager', async () => { + await getExtensionManager(); + + expect(mockRefreshCache).toHaveBeenCalled(); + }); + + it('should use current working directory as workspace', async () => { + const { ExtensionManager } = await import('@qwen-code/qwen-code-core'); + + await getExtensionManager(); + + expect(ExtensionManager).toHaveBeenCalledWith( + expect.objectContaining({ + workspaceDir: process.cwd(), + }), + ); + }); +}); diff --git a/packages/cli/src/config/config.integration.test.ts b/packages/cli/src/config/config.integration.test.ts index a76021f8b79..e939a753bb2 100644 --- a/packages/cli/src/config/config.integration.test.ts +++ b/packages/cli/src/config/config.integration.test.ts @@ -231,18 +231,21 @@ describe('Configuration Integration Tests', () => { expect(config.getExtensionContextFilePaths()).toEqual([]); }); - it('should correctly store and return extension context file paths', () => { - const contextFiles = ['/path/to/file1.txt', '/path/to/file2.js']; + it('should correctly store and return extension context file paths with outputLanguageFilePath', () => { + const outputLanguageFilePath = '/path/to/language.txt'; const configParams: ConfigParameters = { cwd: '/tmp', generationConfig: TEST_CONTENT_GENERATOR_CONFIG, embeddingModel: 'test-embedding-model', targetDir: tempDir, debugMode: false, - extensionContextFilePaths: contextFiles, + outputLanguageFilePath, }; const config = new Config(configParams); - expect(config.getExtensionContextFilePaths()).toEqual(contextFiles); + // outputLanguageFilePath should be included in extension context file paths + expect(config.getExtensionContextFilePaths()).toContain( + outputLanguageFilePath, + ); }); }); diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 79bb0e2fcd9..f57b33b1d13 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -16,11 +16,8 @@ import { } from '@qwen-code/qwen-code-core'; import { loadCliConfig, parseArguments, type CliArgs } from './config.js'; import type { Settings } from './settings.js'; -import type { Extension } from './extension.js'; -import { ExtensionStorage } from './extensions/storage.js'; import * as ServerConfig from '@qwen-code/qwen-code-core'; import { isWorkspaceTrusted } from './trustedFolders.js'; -import { ExtensionEnablementManager } from './extensions/extensionEnablement.js'; vi.mock('./trustedFolders.js', () => ({ isWorkspaceTrusted: vi @@ -539,15 +536,7 @@ describe('loadCliConfig', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getOutputFormat()).toBe('stream-json'); expect(config.getInputFormat()).toBe('stream-json'); @@ -558,15 +547,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js', '--show-memory-usage']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getShowMemoryUsage()).toBe(true); }); @@ -574,15 +555,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getShowMemoryUsage()).toBe(false); }); @@ -590,15 +563,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { ui: { showMemoryUsage: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getShowMemoryUsage()).toBe(false); }); @@ -606,15 +571,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js', '--show-memory-usage']; const argv = await parseArguments({} as Settings); const settings: Settings = { ui: { showMemoryUsage: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getShowMemoryUsage()).toBe(true); }); @@ -648,15 +605,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getProxy()).toBeFalsy(); }); @@ -697,15 +646,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getProxy()).toBe(expected); }); }); @@ -714,15 +655,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js', '--proxy', 'http://localhost:7890']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getProxy()).toBe('http://localhost:7890'); }); @@ -731,15 +664,7 @@ describe('loadCliConfig', () => { process.argv = ['node', 'script.js', '--proxy', 'http://localhost:7890']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getProxy()).toBe('http://localhost:7890'); }); }); @@ -764,15 +689,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(false); }); @@ -780,15 +697,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--telemetry']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -796,15 +705,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--no-telemetry']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(false); }); @@ -812,15 +713,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -828,15 +721,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(false); }); @@ -844,15 +729,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--telemetry']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -860,15 +737,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--no-telemetry']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryEnabled()).toBe(false); }); @@ -878,15 +747,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { otlpEndpoint: 'http://settings.example.com' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpEndpoint()).toBe( 'http://settings.example.com', ); @@ -903,15 +764,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { otlpEndpoint: 'http://settings.example.com' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpEndpoint()).toBe('http://cli.example.com'); }); @@ -919,15 +772,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpEndpoint()).toBe('http://localhost:4317'); }); @@ -937,15 +782,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { target: ServerConfig.DEFAULT_TELEMETRY_TARGET }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryTarget()).toBe( ServerConfig.DEFAULT_TELEMETRY_TARGET, ); @@ -957,15 +794,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { target: ServerConfig.DEFAULT_TELEMETRY_TARGET }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryTarget()).toBe('gcp'); }); @@ -973,15 +802,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryTarget()).toBe( ServerConfig.DEFAULT_TELEMETRY_TARGET, ); @@ -991,15 +812,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { logPrompts: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryLogPromptsEnabled()).toBe(false); }); @@ -1007,15 +820,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--telemetry-log-prompts']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { logPrompts: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryLogPromptsEnabled()).toBe(true); }); @@ -1023,15 +828,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js', '--no-telemetry-log-prompts']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { logPrompts: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryLogPromptsEnabled()).toBe(false); }); @@ -1039,15 +836,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryLogPromptsEnabled()).toBe(true); }); @@ -1057,15 +846,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { otlpProtocol: 'http' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpProtocol()).toBe('http'); }); @@ -1075,15 +856,7 @@ describe('loadCliConfig telemetry', () => { const settings: Settings = { telemetry: { otlpProtocol: 'grpc' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpProtocol()).toBe('http'); }); @@ -1091,15 +864,7 @@ describe('loadCliConfig telemetry', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv); expect(config.getTelemetryOtlpProtocol()).toBe('grpc'); }); @@ -1132,384 +897,15 @@ describe('loadCliConfig telemetry', () => { }); }); -describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => { - beforeEach(() => { - vi.resetAllMocks(); - vi.mocked(os.homedir).mockReturnValue('/mock/home/user'); - // Other common mocks would be reset here. - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('should pass extension context file paths to loadServerHierarchicalMemory', async () => { - process.argv = ['node', 'script.js']; - const settings: Settings = {}; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - }, - contextFiles: ['/path/to/ext1/QWEN.md'], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - }, - contextFiles: [], - }, - { - path: '/path/to/ext3', - config: { - name: 'ext3', - version: '1.0.0', - }, - contextFiles: [ - '/path/to/ext3/context1.md', - '/path/to/ext3/context2.md', - ], - }, - ]; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith( - expect.any(String), - [], - false, - expect.any(Object), - [ - '/path/to/ext1/QWEN.md', - '/path/to/ext3/context1.md', - '/path/to/ext3/context2.md', - ], - true, - 'tree', - { - respectGitIgnore: false, - respectQwenIgnore: true, - }, - undefined, // maxDirs - ); - }); - - // NOTE TO FUTURE DEVELOPERS: - // To re-enable tests for loadHierarchicalGeminiMemory, ensure that: - // 1. os.homedir() is reliably mocked *before* the config.ts module is loaded - // and its functions (which use os.homedir()) are called. - // 2. fs/promises and fs mocks correctly simulate file/directory existence, - // readability, and content based on paths derived from the mocked os.homedir(). - // 3. Spies on console functions (for logger output) are correctly set up if needed. - // Example of a previously failing test structure: - it.skip('should correctly use mocked homedir for global path', async () => { - const MOCK_GEMINI_DIR_LOCAL = path.join('/mock/home/user', '.qwen'); - const MOCK_GLOBAL_PATH_LOCAL = path.join(MOCK_GEMINI_DIR_LOCAL, 'QWEN.md'); - mockFs({ - [MOCK_GLOBAL_PATH_LOCAL]: { type: 'file', content: 'GlobalContentOnly' }, - }); - const memory = await loadHierarchicalGeminiMemory('/some/other/cwd', false); - expect(memory).toBe('GlobalContentOnly'); - expect(vi.mocked(os.homedir)).toHaveBeenCalled(); - expect(fsPromises.readFile).toHaveBeenCalledWith( - MOCK_GLOBAL_PATH_LOCAL, - 'utf-8', - ); - }); -}); - -describe('mergeMcpServers', () => { - it('should not modify the original settings object', async () => { - const settings: Settings = { - mcpServers: { - 'test-server': { - url: 'http://localhost:8080', - }, - }, - }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - mcpServers: { - 'ext1-server': { - url: 'http://localhost:8081', - }, - }, - }, - contextFiles: [], - }, - ]; - const originalSettings = JSON.parse(JSON.stringify(settings)); - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(settings).toEqual(originalSettings); - }); -}); - -describe('mergeExcludeTools', () => { - const defaultExcludes = [ShellTool.Name, EditTool.Name, WriteFileTool.Name]; - const originalIsTTY = process.stdin.isTTY; - - beforeEach(() => { - process.stdin.isTTY = true; - }); - - afterEach(() => { - process.stdin.isTTY = originalIsTTY; - }); - - it('should merge excludeTools from settings and extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool3', 'tool4'], - }, - contextFiles: [], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - excludeTools: ['tool5'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3', 'tool4', 'tool5']), - ); - expect(config.getExcludeTools()).toHaveLength(5); - }); - - it('should handle overlapping excludeTools between settings and extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2', 'tool3'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3']), - ); - expect(config.getExcludeTools()).toHaveLength(3); - }); - - it('should handle overlapping excludeTools between extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2', 'tool3'], - }, - contextFiles: [], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - excludeTools: ['tool3', 'tool4'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3', 'tool4']), - ); - expect(config.getExcludeTools()).toHaveLength(4); - }); - - it('should return an empty array when no excludeTools are specified and it is interactive', async () => { - process.stdin.isTTY = true; - const settings: Settings = {}; - const extensions: Extension[] = []; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual([]); - }); - - it('should return default excludes when no excludeTools are specified and it is not interactive', async () => { - process.stdin.isTTY = false; - const settings: Settings = {}; - const extensions: Extension[] = []; - process.argv = ['node', 'script.js', '-p', 'test']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual(defaultExcludes); - }); - - it('should handle settings with excludeTools but no extensions', async () => { - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2']), - ); - expect(config.getExcludeTools()).toHaveLength(2); - }); - - it('should handle extensions with excludeTools but no settings', async () => { - const settings: Settings = {}; - const extensions: Extension[] = [ - { - path: '/path/to/ext', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool1', 'tool2'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2']), - ); - expect(config.getExcludeTools()).toHaveLength(2); - }); - - it('should not modify the original settings object', async () => { - const settings: Settings = { tools: { exclude: ['tool1'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2'], - }, - contextFiles: [], - }, - ]; - const originalSettings = JSON.parse(JSON.stringify(settings)); - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(settings).toEqual(originalSettings); - }); -}); - describe('Approval mode tool exclusion logic', () => { const originalIsTTY = process.stdin.isTTY; beforeEach(() => { process.stdin.isTTY = false; // Ensure non-interactive mode - vi.mocked(isWorkspaceTrusted).mockReturnValue(true); + vi.mocked(isWorkspaceTrusted).mockReturnValue({ + isTrusted: true, + source: 'file', + }); }); afterEach(() => { @@ -1520,17 +916,7 @@ describe('Approval mode tool exclusion logic', () => { process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain(ShellTool.Name); @@ -1549,17 +935,7 @@ describe('Approval mode tool exclusion logic', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain(ShellTool.Name); @@ -1578,17 +954,8 @@ describe('Approval mode tool exclusion logic', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain(ShellTool.Name); @@ -1604,17 +971,8 @@ describe('Approval mode tool exclusion logic', () => { allowed: [ShellTool.Name], }, }; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).not.toContain(ShellTool.Name); @@ -1630,17 +988,8 @@ describe('Approval mode tool exclusion logic', () => { core: [ShellTool.Name], }, }; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).not.toContain(ShellTool.Name); @@ -1659,17 +1008,8 @@ describe('Approval mode tool exclusion logic', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain(ShellTool.Name); @@ -1688,17 +1028,8 @@ describe('Approval mode tool exclusion logic', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).not.toContain(ShellTool.Name); @@ -1710,17 +1041,8 @@ describe('Approval mode tool exclusion logic', () => { process.argv = ['node', 'script.js', '--yolo', '-p', 'test']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).not.toContain(ShellTool.Name); @@ -1744,18 +1066,8 @@ describe('Approval mode tool exclusion logic', () => { process.argv = testCase.args; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const extensions: Extension[] = []; - - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).not.toContain(ShellTool.Name); @@ -1775,17 +1087,7 @@ describe('Approval mode tool exclusion logic', () => { ]; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { exclude: ['custom_tool'] } }; - const extensions: Extension[] = []; - - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain('custom_tool'); // From settings @@ -1804,18 +1106,8 @@ describe('Approval mode tool exclusion logic', () => { }; const settings: Settings = {}; - const extensions: Extension[] = []; await expect( - loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - invalidArgv.extensions, - ), - - invalidArgv as CliArgs, - ), + loadCliConfig(settings, invalidArgv as CliArgs, undefined, []), ).rejects.toThrow( 'Invalid approval mode: invalid_mode. Valid values are: plan, default, auto-edit, yolo', ); @@ -1848,15 +1140,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { it('should allow all MCP servers if the flag is not provided', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - baseSettings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(baseSettings, argv, undefined, []); expect(config.getMcpServers()).toEqual(baseSettings.mcpServers); }); @@ -1868,15 +1152,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { 'server1', ]; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - baseSettings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(baseSettings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server1: { url: 'http://localhost:8080' }, }); @@ -1892,15 +1168,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { 'server3', ]; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - baseSettings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(baseSettings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server1: { url: 'http://localhost:8080' }, server3: { url: 'http://localhost:8082' }, @@ -1917,15 +1185,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { 'server4', ]; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - baseSettings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(baseSettings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server1: { url: 'http://localhost:8080' }, }); @@ -1934,15 +1194,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { it('should allow no MCP servers if the flag is provided but empty', async () => { process.argv = ['node', 'script.js', '--allowed-mcp-server-names', '']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - baseSettings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(baseSettings, argv, undefined, []); expect(config.getMcpServers()).toEqual({}); }); @@ -1953,15 +1205,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { ...baseSettings, mcp: { allowed: ['server1', 'server2'] }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server1: { url: 'http://localhost:8080' }, server2: { url: 'http://localhost:8081' }, @@ -1975,15 +1219,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { ...baseSettings, mcp: { excluded: ['server1', 'server2'] }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server3: { url: 'http://localhost:8082' }, }); @@ -1999,15 +1235,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { allowed: ['server1', 'server2'], }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server2: { url: 'http://localhost:8081' }, }); @@ -2028,15 +1256,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { allowed: ['server2'], }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server1: { url: 'http://localhost:8080' }, }); @@ -2059,15 +1279,7 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { excluded: ['server3'], // Should be ignored }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getMcpServers()).toEqual({ server2: { url: 'http://localhost:8081' }, server3: { url: 'http://localhost:8082' }, @@ -2075,56 +1287,6 @@ describe('loadCliConfig with allowed-mcp-server-names', () => { }); }); -describe('loadCliConfig extensions', () => { - const mockExtensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { name: 'ext1', version: '1.0.0' }, - contextFiles: ['/path/to/ext1.md'], - }, - { - path: '/path/to/ext2', - config: { name: 'ext2', version: '1.0.0' }, - contextFiles: ['/path/to/ext2.md'], - }, - ]; - - it('should not filter extensions if --extensions flag is not used', async () => { - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const settings: Settings = {}; - const config = await loadCliConfig( - settings, - mockExtensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExtensionContextFilePaths()).toEqual([ - '/path/to/ext1.md', - '/path/to/ext2.md', - ]); - }); - - it('should filter extensions if --extensions flag is used', async () => { - process.argv = ['node', 'script.js', '--extensions', 'ext1']; - const argv = await parseArguments({} as Settings); - const settings: Settings = {}; - const config = await loadCliConfig( - settings, - mockExtensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExtensionContextFilePaths()).toEqual(['/path/to/ext1.md']); - }); -}); - describe('loadCliConfig model selection', () => { it.skip('selects a model from settings.json if provided', async () => { process.argv = ['node', 'script.js']; @@ -2135,12 +1297,9 @@ describe('loadCliConfig model selection', () => { name: 'qwen3-coder-plus', }, }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getModel()).toBe('qwen3-coder-plus'); @@ -2153,12 +1312,9 @@ describe('loadCliConfig model selection', () => { { // No model set. }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getModel()).toBe(DEFAULT_QWEN_MODEL); @@ -2180,12 +1336,9 @@ describe('loadCliConfig model selection', () => { name: 'qwen3-coder-flash', }, }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getModel()).toBe('qwen3-coder-plus'); @@ -2205,12 +1358,9 @@ describe('loadCliConfig model selection', () => { { // No model provided via settings. }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getModel()).toBe('qwen3-coder-plus'); @@ -2242,15 +1392,7 @@ describe('loadCliConfig folderTrust', () => { }, }; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getFolderTrust()).toBe(false); }); @@ -2264,15 +1406,7 @@ describe('loadCliConfig folderTrust', () => { }, }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getFolderTrust()).toBe(true); }); @@ -2280,15 +1414,7 @@ describe('loadCliConfig folderTrust', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getFolderTrust()).toBe(false); }); }); @@ -2328,16 +1454,8 @@ describe('loadCliConfig with includeDirectories', () => { path.join(mockCwd, 'settings', 'path3'), ], }, - }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + }; + const config = await loadCliConfig(settings, argv, undefined, []); const expected = [ mockCwd, path.resolve(path.sep, 'cli', 'path1'), @@ -2380,15 +1498,7 @@ describe('loadCliConfig chatCompression', () => { }, }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getChatCompression()).toEqual({ contextPercentageThreshold: 0.5, }); @@ -2398,15 +1508,7 @@ describe('loadCliConfig chatCompression', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getChatCompression()).toBeUndefined(); }); }); @@ -2430,15 +1532,7 @@ describe('loadCliConfig useRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseRipgrep()).toBe(true); }); @@ -2446,15 +1540,7 @@ describe('loadCliConfig useRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { useRipgrep: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseRipgrep()).toBe(false); }); @@ -2462,15 +1548,7 @@ describe('loadCliConfig useRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { useRipgrep: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseRipgrep()).toBe(true); }); }); @@ -2494,15 +1572,7 @@ describe('loadCliConfig useBuiltinRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseBuiltinRipgrep()).toBe(true); }); @@ -2510,15 +1580,7 @@ describe('loadCliConfig useBuiltinRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { useBuiltinRipgrep: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseBuiltinRipgrep()).toBe(false); }); @@ -2526,15 +1588,7 @@ describe('loadCliConfig useBuiltinRipgrep', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { useBuiltinRipgrep: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getUseBuiltinRipgrep()).toBe(true); }); }); @@ -2560,15 +1614,7 @@ describe('screenReader configuration', () => { const settings: Settings = { ui: { accessibility: { screenReader: true } }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getScreenReader()).toBe(true); }); @@ -2578,15 +1624,7 @@ describe('screenReader configuration', () => { const settings: Settings = { ui: { accessibility: { screenReader: false } }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getScreenReader()).toBe(false); }); @@ -2596,15 +1634,7 @@ describe('screenReader configuration', () => { const settings: Settings = { ui: { accessibility: { screenReader: false } }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getScreenReader()).toBe(true); }); @@ -2612,15 +1642,7 @@ describe('screenReader configuration', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = {}; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getScreenReader()).toBe(false); }); }); @@ -2634,7 +1656,10 @@ describe('loadCliConfig tool exclusions', () => { vi.mocked(os.homedir).mockReturnValue('/mock/home/user'); vi.stubEnv('GEMINI_API_KEY', 'test-api-key'); process.stdin.isTTY = true; - vi.mocked(isWorkspaceTrusted).mockReturnValue(true); + vi.mocked(isWorkspaceTrusted).mockReturnValue({ + isTrusted: true, + source: 'file', + }); }); afterEach(() => { @@ -2648,15 +1673,7 @@ describe('loadCliConfig tool exclusions', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getExcludeTools()).not.toContain('run_shell_command'); expect(config.getExcludeTools()).not.toContain('replace'); expect(config.getExcludeTools()).not.toContain('write_file'); @@ -2666,15 +1683,7 @@ describe('loadCliConfig tool exclusions', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js', '--yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getExcludeTools()).not.toContain('run_shell_command'); expect(config.getExcludeTools()).not.toContain('replace'); expect(config.getExcludeTools()).not.toContain('write_file'); @@ -2684,15 +1693,7 @@ describe('loadCliConfig tool exclusions', () => { process.stdin.isTTY = false; process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getExcludeTools()).toContain('run_shell_command'); expect(config.getExcludeTools()).toContain('edit'); expect(config.getExcludeTools()).toContain('write_file'); @@ -2702,15 +1703,7 @@ describe('loadCliConfig tool exclusions', () => { process.stdin.isTTY = false; process.argv = ['node', 'script.js', '-p', 'test', '--yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getExcludeTools()).not.toContain('run_shell_command'); expect(config.getExcludeTools()).not.toContain('replace'); expect(config.getExcludeTools()).not.toContain('write_file'); @@ -2739,15 +1732,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(true); }); @@ -2755,15 +1740,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = false; process.argv = ['node', 'script.js', '--prompt-interactive', 'test']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(true); }); @@ -2771,15 +1748,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = false; process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(false); }); @@ -2787,15 +1756,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js', '--prompt', 'test']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(false); }); @@ -2803,15 +1764,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js', '--model', 'gemini-1.5-pro', 'Hello']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(false); }); @@ -2826,15 +1779,7 @@ describe('loadCliConfig interactive', () => { 'Hello world', ]; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(false); // Verify the question is preserved for one-shot execution expect(argv.prompt).toBe('Hello world'); @@ -2845,15 +1790,7 @@ describe('loadCliConfig interactive', () => { process.stdin.isTTY = true; process.argv = ['node', 'script.js', '--model', 'gemini-1.5-pro']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.isInteractive()).toBe(true); }); }); @@ -2866,7 +1803,10 @@ describe('loadCliConfig approval mode', () => { vi.mocked(os.homedir).mockReturnValue('/mock/home/user'); vi.stubEnv('GEMINI_API_KEY', 'test-api-key'); process.argv = ['node', 'script.js']; // Reset argv for each test - vi.mocked(isWorkspaceTrusted).mockReturnValue(true); + vi.mocked(isWorkspaceTrusted).mockReturnValue({ + isTrusted: true, + source: 'file', + }); }); afterEach(() => { @@ -2878,156 +1818,78 @@ describe('loadCliConfig approval mode', () => { it('should default to DEFAULT approval mode when no flags are set', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should set PLAN approval mode when --approval-mode=plan', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'plan']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.PLAN); }); it('should set YOLO approval mode when --yolo flag is used', async () => { process.argv = ['node', 'script.js', '--yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.YOLO); }); it('should set YOLO approval mode when -y flag is used', async () => { process.argv = ['node', 'script.js', '-y']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.YOLO); }); it('should set DEFAULT approval mode when --approval-mode=default', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'default']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should set AUTO_EDIT approval mode when --approval-mode=auto-edit', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'auto-edit']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.AUTO_EDIT); }); it('should set YOLO approval mode when --approval-mode=yolo', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.YOLO); }); it('should use approval mode from settings when CLI flags are not provided', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { tools: { approvalMode: 'plan' } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + // Using string value to test normalization + const settings = { tools: { approvalMode: 'plan' } } as unknown as Settings; + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.PLAN); }); it('should normalize approval mode values from settings', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { tools: { approvalMode: 'AutoEdit' } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const settings: Settings = { + tools: { approvalMode: ServerConfig.ApprovalMode.AUTO_EDIT }, + }; + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.AUTO_EDIT); }); it('should throw when approval mode in settings is invalid', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { tools: { approvalMode: 'invalid_mode' } }; - await expect( - loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ), - ).rejects.toThrow( + const settings = { + tools: { approvalMode: 'invalid_mode' }, + } as unknown as Settings; + await expect(loadCliConfig(settings, argv, undefined, [])).rejects.toThrow( 'Invalid approval mode: invalid_mode. Valid values are: plan, default, auto-edit, yolo', ); }); @@ -3039,30 +1901,14 @@ describe('loadCliConfig approval mode', () => { const argv = await parseArguments({} as Settings); // Manually set yolo to true to simulate what would happen if validation didn't prevent it argv.yolo = true; - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should fall back to --yolo behavior when --approval-mode is not set', async () => { process.argv = ['node', 'script.js', '--yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.YOLO); }); @@ -3078,80 +1924,35 @@ describe('loadCliConfig approval mode', () => { it('should override --approval-mode=yolo to DEFAULT', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should override --approval-mode=auto-edit to DEFAULT', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'auto-edit']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should override --yolo flag to DEFAULT', async () => { process.argv = ['node', 'script.js', '--yolo']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should remain DEFAULT when --approval-mode=default', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'default']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.DEFAULT); }); it('should allow PLAN approval mode in untrusted folders', async () => { process.argv = ['node', 'script.js', '--approval-mode', 'plan']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getApprovalMode()).toBe(ServerConfig.ApprovalMode.PLAN); }); }); @@ -3174,7 +1975,9 @@ describe('loadCliConfig fileFiltering', () => { }); const testCases: Array<{ - property: keyof NonNullable; + property: keyof NonNullable< + NonNullable['fileFiltering'] + >; getter: (config: ServerConfig.Config) => boolean; value: boolean; }> = [ @@ -3229,16 +2032,7 @@ describe('loadCliConfig fileFiltering', () => { }, }; const argv = await parseArguments(settings); - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(getter(config)).toBe(value); }, ); @@ -3248,15 +2042,7 @@ describe('Output format', () => { it('should default to TEXT', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getOutputFormat()).toBe(OutputFormat.TEXT); }); @@ -3265,12 +2051,9 @@ describe('Output format', () => { const argv = await parseArguments({} as Settings); const config = await loadCliConfig( { output: { format: OutputFormat.JSON } }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getOutputFormat()).toBe(OutputFormat.JSON); }); @@ -3280,12 +2063,9 @@ describe('Output format', () => { const argv = await parseArguments({} as Settings); const config = await loadCliConfig( { output: { format: OutputFormat.JSON } }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getOutputFormat()).toBe(OutputFormat.JSON); }); @@ -3370,15 +2150,7 @@ describe('Telemetry configuration via environment variables', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -3386,16 +2158,10 @@ describe('Telemetry configuration via environment variables', () => { vi.stubEnv('GEMINI_TELEMETRY_TARGET', 'gcp'); process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { telemetry: { target: 'local' } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const settings: Settings = { + telemetry: { target: 'local' }, + } as unknown as Settings; + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryTarget()).toBe('gcp'); }); @@ -3403,19 +2169,10 @@ describe('Telemetry configuration via environment variables', () => { vi.stubEnv('GEMINI_TELEMETRY_TARGET', 'bogus'); process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { telemetry: { target: 'gcp' } }; - await expect( - loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - - argv, - ), - ).rejects.toThrow( + const settings: Settings = { + telemetry: { target: 'gcp' }, + } as unknown as Settings; + await expect(loadCliConfig(settings, argv, undefined, [])).rejects.toThrow( /Invalid telemetry configuration: .*Invalid telemetry target/i, ); vi.unstubAllEnvs(); @@ -3429,15 +2186,7 @@ describe('Telemetry configuration via environment variables', () => { const settings: Settings = { telemetry: { otlpEndpoint: 'http://settings.com' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryOtlpEndpoint()).toBe('http://gemini.env.com'); }); @@ -3446,15 +2195,7 @@ describe('Telemetry configuration via environment variables', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { otlpProtocol: 'grpc' } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryOtlpProtocol()).toBe('http'); }); @@ -3463,15 +2204,7 @@ describe('Telemetry configuration via environment variables', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { logPrompts: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryLogPromptsEnabled()).toBe(false); }); @@ -3482,15 +2215,7 @@ describe('Telemetry configuration via environment variables', () => { const settings: Settings = { telemetry: { outfile: '/settings/telemetry.log' }, }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryOutfile()).toBe('/gemini/env/telemetry.log'); }); @@ -3499,15 +2224,7 @@ describe('Telemetry configuration via environment variables', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { useCollector: false } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryUseCollector()).toBe(true); }); @@ -3516,15 +2233,7 @@ describe('Telemetry configuration via environment variables', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { telemetry: { enabled: true } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -3532,16 +2241,10 @@ describe('Telemetry configuration via environment variables', () => { vi.stubEnv('GEMINI_TELEMETRY_TARGET', undefined); process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const settings: Settings = { telemetry: { target: 'local' } }; - const config = await loadCliConfig( - settings, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const settings: Settings = { + telemetry: { target: 'local' }, + } as unknown as Settings; + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getTelemetryTarget()).toBe('local'); }); @@ -3549,15 +2252,7 @@ describe('Telemetry configuration via environment variables', () => { vi.stubEnv('GEMINI_TELEMETRY_ENABLED', '1'); process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getTelemetryEnabled()).toBe(true); }); @@ -3567,12 +2262,9 @@ describe('Telemetry configuration via environment variables', () => { const argv = await parseArguments({} as Settings); const config = await loadCliConfig( { telemetry: { enabled: true } }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getTelemetryEnabled()).toBe(false); }); @@ -3581,15 +2273,7 @@ describe('Telemetry configuration via environment variables', () => { vi.stubEnv('GEMINI_TELEMETRY_LOG_PROMPTS', '1'); process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - {}, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig({}, argv, undefined, []); expect(config.getTelemetryLogPromptsEnabled()).toBe(true); }); @@ -3599,12 +2283,9 @@ describe('Telemetry configuration via environment variables', () => { const argv = await parseArguments({} as Settings); const config = await loadCliConfig( { telemetry: { logPrompts: true } }, - [], - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), argv, + undefined, + [], ); expect(config.getTelemetryLogPromptsEnabled()).toBe(false); }); diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 66f9f7f2580..e304806eb94 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -862,14 +862,19 @@ export async function loadCliConfig( argv.excludeTools, ); - const allowedMcpServers = argv.allowedMcpServerNames - ? new Set(argv.allowedMcpServerNames.filter(Boolean)) - : settings.mcp?.allowed + let allowedMcpServers: Set | undefined; + let excludedMcpServers: Set | undefined; + if (argv.allowedMcpServerNames) { + allowedMcpServers = new Set(argv.allowedMcpServerNames.filter(Boolean)); + excludedMcpServers = undefined; + } else { + allowedMcpServers = settings.mcp?.allowed ? new Set(settings.mcp.allowed.filter(Boolean)) : undefined; - const excludedMcpServers = settings.mcp?.excluded - ? new Set(settings.mcp.excluded.filter(Boolean)) - : undefined; + excludedMcpServers = settings.mcp?.excluded + ? new Set(settings.mcp.excluded.filter(Boolean)) + : undefined; + } const selectedAuthType = (argv.authType as AuthType | undefined) || diff --git a/packages/cli/src/ui/commands/extensionsCommand.test.ts b/packages/cli/src/ui/commands/extensionsCommand.test.ts index acac19c8556..bad4b87f2a0 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.test.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.test.ts @@ -100,7 +100,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'No extensions installed. Run `/extensions explore` to check out the gallery.', + text: 'No extensions installed.', }, expect.any(Number), ); @@ -241,7 +241,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.ERROR, - text: 'Extension ext-one not found.', + text: 'Extension "ext-one" not found.', }, expect.any(Number), ); @@ -645,7 +645,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Extension "test-extension" disabled for the scope "User"', + text: 'Extension "test-extension" disabled for scope "User"', }, expect.any(Number), ); @@ -663,7 +663,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Extension "test-extension" disabled for the scope "Workspace"', + text: 'Extension "test-extension" disabled for scope "Workspace"', }, expect.any(Number), ); @@ -675,7 +675,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.ERROR, - text: 'Unsupported scope invalid, should be one of "user" or "workspace"', + text: 'Unsupported scope "invalid", should be one of "user" or "workspace"', }, expect.any(Number), ); @@ -741,7 +741,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Extension "test-extension" enabled for the scope "User"', + text: 'Extension "test-extension" enabled for scope "User"', }, expect.any(Number), ); @@ -759,7 +759,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Extension "test-extension" enabled for the scope "Workspace"', + text: 'Extension "test-extension" enabled for scope "Workspace"', }, expect.any(Number), ); @@ -771,7 +771,7 @@ describe('extensionsCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.ERROR, - text: 'Unsupported scope invalid, should be one of "user" or "workspace"', + text: 'Unsupported scope "invalid", should be one of "user" or "workspace"', }, expect.any(Number), ); From 143beb51eda8ac36a84fedc8910cd733003fee58 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Mon, 19 Jan 2026 21:27:31 +0800 Subject: [PATCH 19/30] fix code merge --- packages/cli/src/config/config.test.ts | 331 +------------------------ packages/cli/src/config/config.ts | 1 - packages/core/src/config/config.ts | 9 - 3 files changed, 3 insertions(+), 338 deletions(-) diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index c1a7472c8d5..373b581813e 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -897,138 +897,6 @@ describe('loadCliConfig telemetry', () => { }); }); -describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => { - beforeEach(() => { - vi.resetAllMocks(); - vi.mocked(os.homedir).mockReturnValue('/mock/home/user'); - // Other common mocks would be reset here. - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('should pass extension context file paths to loadServerHierarchicalMemory', async () => { - process.argv = ['node', 'script.js']; - const settings: Settings = {}; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - }, - contextFiles: ['/path/to/ext1/QWEN.md'], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - }, - contextFiles: [], - }, - { - path: '/path/to/ext3', - config: { - name: 'ext3', - version: '1.0.0', - }, - contextFiles: [ - '/path/to/ext3/context1.md', - '/path/to/ext3/context2.md', - ], - }, - ]; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith( - expect.any(String), - [], - false, - expect.any(Object), - [ - '/path/to/ext1/QWEN.md', - '/path/to/ext3/context1.md', - '/path/to/ext3/context2.md', - ], - true, - 'tree', - ); - }); - - // NOTE TO FUTURE DEVELOPERS: - // To re-enable tests for loadHierarchicalGeminiMemory, ensure that: - // 1. os.homedir() is reliably mocked *before* the config.ts module is loaded - // and its functions (which use os.homedir()) are called. - // 2. fs/promises and fs mocks correctly simulate file/directory existence, - // readability, and content based on paths derived from the mocked os.homedir(). - // 3. Spies on console functions (for logger output) are correctly set up if needed. - // Example of a previously failing test structure: - it.skip('should correctly use mocked homedir for global path', async () => { - const MOCK_GEMINI_DIR_LOCAL = path.join('/mock/home/user', '.qwen'); - const MOCK_GLOBAL_PATH_LOCAL = path.join(MOCK_GEMINI_DIR_LOCAL, 'QWEN.md'); - mockFs({ - [MOCK_GLOBAL_PATH_LOCAL]: { type: 'file', content: 'GlobalContentOnly' }, - }); - const memory = await loadHierarchicalGeminiMemory('/some/other/cwd', false); - expect(memory).toBe('GlobalContentOnly'); - expect(vi.mocked(os.homedir)).toHaveBeenCalled(); - expect(fsPromises.readFile).toHaveBeenCalledWith( - MOCK_GLOBAL_PATH_LOCAL, - 'utf-8', - ); - }); -}); - -describe('mergeMcpServers', () => { - it('should not modify the original settings object', async () => { - const settings: Settings = { - mcpServers: { - 'test-server': { - url: 'http://localhost:8080', - }, - }, - }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - mcpServers: { - 'ext1-server': { - url: 'http://localhost:8081', - }, - }, - }, - contextFiles: [], - }, - ]; - const originalSettings = JSON.parse(JSON.stringify(settings)); - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(settings).toEqual(originalSettings); - }); -}); - describe('mergeExcludeTools', () => { const defaultExcludes = [ShellTool.Name, EditTool.Name, WriteFileTool.Name]; const originalIsTTY = process.stdin.isTTY; @@ -1041,147 +909,21 @@ describe('mergeExcludeTools', () => { process.stdin.isTTY = originalIsTTY; }); - it('should merge excludeTools from settings and extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool3', 'tool4'], - }, - contextFiles: [], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - excludeTools: ['tool5'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3', 'tool4', 'tool5']), - ); - expect(config.getExcludeTools()).toHaveLength(5); - }); - - it('should handle overlapping excludeTools between settings and extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2', 'tool3'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3']), - ); - expect(config.getExcludeTools()).toHaveLength(3); - }); - - it('should handle overlapping excludeTools between extensions', async () => { - const settings: Settings = { tools: { exclude: ['tool1'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext1', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2', 'tool3'], - }, - contextFiles: [], - }, - { - path: '/path/to/ext2', - config: { - name: 'ext2', - version: '1.0.0', - excludeTools: ['tool3', 'tool4'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2', 'tool3', 'tool4']), - ); - expect(config.getExcludeTools()).toHaveLength(4); - }); - it('should return an empty array when no excludeTools are specified and it is interactive', async () => { process.stdin.isTTY = true; const settings: Settings = {}; - const extensions: Extension[] = []; process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getExcludeTools()).toEqual([]); }); it('should return default excludes when no excludeTools are specified and it is not interactive', async () => { process.stdin.isTTY = false; const settings: Settings = {}; - const extensions: Extension[] = []; process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getExcludeTools()).toEqual(defaultExcludes); }); @@ -1189,79 +931,12 @@ describe('mergeExcludeTools', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments({} as Settings); const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; - const extensions: Extension[] = []; - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(config.getExcludeTools()).toEqual( - expect.arrayContaining(['tool1', 'tool2']), - ); - expect(config.getExcludeTools()).toHaveLength(2); - }); - - it('should handle extensions with excludeTools but no settings', async () => { - const settings: Settings = {}; - const extensions: Extension[] = [ - { - path: '/path/to/ext', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool1', 'tool2'], - }, - contextFiles: [], - }, - ]; - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - const config = await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); + const config = await loadCliConfig(settings, argv, undefined, []); expect(config.getExcludeTools()).toEqual( expect.arrayContaining(['tool1', 'tool2']), ); expect(config.getExcludeTools()).toHaveLength(2); }); - - it('should not modify the original settings object', async () => { - const settings: Settings = { tools: { exclude: ['tool1'] } }; - const extensions: Extension[] = [ - { - path: '/path/to/ext', - config: { - name: 'ext1', - version: '1.0.0', - excludeTools: ['tool2'], - }, - contextFiles: [], - }, - ]; - const originalSettings = JSON.parse(JSON.stringify(settings)); - process.argv = ['node', 'script.js']; - const argv = await parseArguments({} as Settings); - await loadCliConfig( - settings, - extensions, - new ExtensionEnablementManager( - ExtensionStorage.getUserExtensionsDir(), - argv.extensions, - ), - argv, - ); - expect(settings).toEqual(originalSettings); - }); }); describe('Approval mode tool exclusion logic', () => { diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 39500338953..983e478644d 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -944,7 +944,6 @@ export async function loadCliConfig( loadMemoryFromIncludeDirectories: settings.context?.loadMemoryFromIncludeDirectories || false, importFormat: settings.context?.importFormat || 'tree', - discoveryMaxDirs: settings.context?.discoveryMaxDirs || 200, debugMode, question, fullContext: argv.allFiles || false, diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index bb715abe42a..433dede6d8f 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -335,7 +335,6 @@ export interface ConfigParameters { cliVersion?: string; loadMemoryFromIncludeDirectories?: boolean; importFormat?: 'tree' | 'flat'; - discoveryMaxDirs?: number; chatRecording?: boolean; // Web search providers webSearch?: { @@ -482,7 +481,6 @@ export class Config { private readonly chatRecordingEnabled: boolean; private readonly loadMemoryFromIncludeDirectories: boolean = false; private readonly importFormat: 'tree' | 'flat'; - private readonly discoveryMaxDirs: number; private readonly webSearch?: { provider: Array<{ type: 'tavily' | 'google' | 'dashscope'; @@ -597,7 +595,6 @@ export class Config { this.loadMemoryFromIncludeDirectories = params.loadMemoryFromIncludeDirectories ?? false; this.importFormat = params.importFormat ?? 'tree'; - this.discoveryMaxDirs = params.discoveryMaxDirs ?? 200; this.chatCompression = params.chatCompression; this.interactive = params.interactive ?? false; this.trustedFolder = params.trustedFolder; @@ -721,8 +718,6 @@ export class Config { this.getExtensionContextFilePaths(), this.getFolderTrust(), this.getImportFormat(), - this.getFileFilteringOptions(), - this.getDiscoveryMaxDirs(), ); this.setUserMemory(memoryContent); this.setGeminiMdFileCount(fileCount); @@ -856,10 +851,6 @@ export class Config { return this.importFormat; } - getDiscoveryMaxDirs(): number { - return this.discoveryMaxDirs; - } - getContentGeneratorConfig(): ContentGeneratorConfig { return this.contentGeneratorConfig; } From b0c3e5d884d92b17d7443570d7edb4431b649e3c Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 11:59:14 +0800 Subject: [PATCH 20/30] fix ci test --- .../src/commands/extensions/install.test.ts | 91 +++- packages/cli/src/commands/mcp/add.test.ts | 13 +- packages/cli/src/commands/mcp/list.test.ts | 41 +- packages/cli/src/commands/mcp/remove.test.ts | 12 +- .../FileCommandLoader-extension.test.ts | 440 +++++++++--------- .../src/services/FileCommandLoader.test.ts | 20 +- .../cli/src/ui/hooks/useGitBranchName.test.ts | 5 +- packages/core/src/config/config.test.ts | 9 +- .../src/extension/extensionSettings.test.ts | 18 +- packages/core/src/extension/storage.test.ts | 17 +- packages/core/src/extension/storage.ts | 12 +- 11 files changed, 383 insertions(+), 295 deletions(-) diff --git a/packages/cli/src/commands/extensions/install.test.ts b/packages/cli/src/commands/extensions/install.test.ts index 17a41d8d959..bb18392bca9 100644 --- a/packages/cli/src/commands/extensions/install.test.ts +++ b/packages/cli/src/commands/extensions/install.test.ts @@ -4,28 +4,49 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it, expect, vi, type MockInstance } from 'vitest'; +import { + describe, + it, + expect, + vi, + beforeEach, + afterEach, + type MockInstance, +} from 'vitest'; import { handleInstall, installCommand } from './install.js'; import yargs from 'yargs'; const mockInstallExtension = vi.hoisted(() => vi.fn()); +const mockRefreshCache = vi.hoisted(() => vi.fn()); +const mockParseInstallSource = vi.hoisted(() => vi.fn()); const mockRequestConsentNonInteractive = vi.hoisted(() => vi.fn()); -const mockStat = vi.hoisted(() => vi.fn()); +const mockRequestConsentOrFail = vi.hoisted(() => vi.fn()); +const mockIsWorkspaceTrusted = vi.hoisted(() => vi.fn()); +const mockLoadSettings = vi.hoisted(() => vi.fn()); + +vi.mock('@qwen-code/qwen-code-core', () => ({ + ExtensionManager: vi.fn().mockImplementation(() => ({ + installExtension: mockInstallExtension, + refreshCache: mockRefreshCache, + })), + parseInstallSource: mockParseInstallSource, +})); -vi.mock('../../config/extension.js', () => ({ - installExtension: mockInstallExtension, +vi.mock('./consent.js', () => ({ requestConsentNonInteractive: mockRequestConsentNonInteractive, + requestConsentOrFail: mockRequestConsentOrFail, })); -vi.mock('../../utils/errors.js', () => ({ - getErrorMessage: vi.fn((error: Error) => error.message), +vi.mock('../../config/trustedFolders.js', () => ({ + isWorkspaceTrusted: mockIsWorkspaceTrusted, +})); + +vi.mock('../../config/settings.js', () => ({ + loadSettings: mockLoadSettings, })); -vi.mock('node:fs/promises', () => ({ - stat: mockStat, - default: { - stat: mockStat, - }, +vi.mock('../../utils/errors.js', () => ({ + getErrorMessage: vi.fn((error: Error) => error.message), })); describe('extensions install command', () => { @@ -51,17 +72,21 @@ describe('handleInstall', () => { processSpy = vi .spyOn(process, 'exit') .mockImplementation(() => undefined as never); + mockRefreshCache.mockResolvedValue(undefined); + mockLoadSettings.mockReturnValue({ merged: {} }); + mockIsWorkspaceTrusted.mockReturnValue(true); }); afterEach(() => { - mockInstallExtension.mockClear(); - mockRequestConsentNonInteractive.mockClear(); - mockStat.mockClear(); - vi.resetAllMocks(); + vi.clearAllMocks(); }); it('should install an extension from a http source', async () => { - mockInstallExtension.mockResolvedValue('http-extension'); + mockParseInstallSource.mockResolvedValue({ + type: 'http', + url: 'http://google.com', + }); + mockInstallExtension.mockResolvedValue({ name: 'http-extension' }); await handleInstall({ source: 'http://google.com', @@ -73,7 +98,11 @@ describe('handleInstall', () => { }); it('should install an extension from a https source', async () => { - mockInstallExtension.mockResolvedValue('https-extension'); + mockParseInstallSource.mockResolvedValue({ + type: 'https', + url: 'https://google.com', + }); + mockInstallExtension.mockResolvedValue({ name: 'https-extension' }); await handleInstall({ source: 'https://google.com', @@ -85,7 +114,11 @@ describe('handleInstall', () => { }); it('should install an extension from a git source', async () => { - mockInstallExtension.mockResolvedValue('git-extension'); + mockParseInstallSource.mockResolvedValue({ + type: 'git', + url: 'git@some-url', + }); + mockInstallExtension.mockResolvedValue({ name: 'git-extension' }); await handleInstall({ source: 'git@some-url', @@ -97,7 +130,9 @@ describe('handleInstall', () => { }); it('throws an error from an unknown source', async () => { - mockStat.mockRejectedValue(new Error('ENOENT: no such file or directory')); + mockParseInstallSource.mockRejectedValue( + new Error('Install source not found.'), + ); await handleInstall({ source: 'test://google.com', }); @@ -107,7 +142,11 @@ describe('handleInstall', () => { }); it('should install an extension from a sso source', async () => { - mockInstallExtension.mockResolvedValue('sso-extension'); + mockParseInstallSource.mockResolvedValue({ + type: 'sso', + url: 'sso://google.com', + }); + mockInstallExtension.mockResolvedValue({ name: 'sso-extension' }); await handleInstall({ source: 'sso://google.com', @@ -119,8 +158,12 @@ describe('handleInstall', () => { }); it('should install an extension from a local path', async () => { - mockInstallExtension.mockResolvedValue('local-extension'); - mockStat.mockResolvedValue({}); + mockParseInstallSource.mockResolvedValue({ + type: 'local', + path: '/some/path', + }); + mockInstallExtension.mockResolvedValue({ name: 'local-extension' }); + await handleInstall({ source: '/some/path', }); @@ -131,6 +174,10 @@ describe('handleInstall', () => { }); it('should throw an error if install extension fails', async () => { + mockParseInstallSource.mockResolvedValue({ + type: 'git', + url: 'git@some-url', + }); mockInstallExtension.mockRejectedValue( new Error('Install extension failed'), ); diff --git a/packages/cli/src/commands/mcp/add.test.ts b/packages/cli/src/commands/mcp/add.test.ts index 357235b5fa7..94c85f656b7 100644 --- a/packages/cli/src/commands/mcp/add.test.ts +++ b/packages/cli/src/commands/mcp/add.test.ts @@ -7,11 +7,16 @@ import yargs from 'yargs'; import { addCommand } from './add.js'; import { loadSettings, SettingScope } from '../../config/settings.js'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('fs/promises', () => ({ - readFile: vi.fn(), - writeFile: vi.fn(), -})); +vi.mock('fs/promises', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + readFile: vi.fn(), + writeFile: vi.fn(), + }; +}); vi.mock('os', () => { const homedir = vi.fn(() => '/home/user'); diff --git a/packages/cli/src/commands/mcp/list.test.ts b/packages/cli/src/commands/mcp/list.test.ts index bf186c729ce..438dcad5928 100644 --- a/packages/cli/src/commands/mcp/list.test.ts +++ b/packages/cli/src/commands/mcp/list.test.ts @@ -7,19 +7,15 @@ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { listMcpServers } from './list.js'; import { loadSettings } from '../../config/settings.js'; -import { loadExtensions } from '../../config/extension.js'; -import { ExtensionStorage } from '../../config/extensions/storage.js'; -import { createTransport } from '@qwen-code/qwen-code-core'; +import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; +import { createTransport, ExtensionManager } from '@qwen-code/qwen-code-core'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; vi.mock('../../config/settings.js', () => ({ loadSettings: vi.fn(), })); -vi.mock('../../config/extension.js', () => ({ - loadExtensions: vi.fn(), - ExtensionStorage: { - getUserExtensionsDir: vi.fn(), - }, +vi.mock('../../config/trustedFolders.js', () => ({ + isWorkspaceTrusted: vi.fn(), })); vi.mock('@qwen-code/qwen-code-core', () => ({ createTransport: vi.fn(), @@ -28,20 +24,15 @@ vi.mock('@qwen-code/qwen-code-core', () => ({ CONNECTING: 'CONNECTING', DISCONNECTED: 'DISCONNECTED', }, - Storage: vi.fn().mockImplementation((_cwd: string) => ({ - getGlobalSettingsPath: () => '/tmp/qwen/settings.json', - getWorkspaceSettingsPath: () => '/tmp/qwen/workspace-settings.json', - getProjectTempDir: () => '/test/home/.qwen/tmp/mocked_hash', - })), - QWEN_CONFIG_DIR: '.qwen', + ExtensionManager: vi.fn(), getErrorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)), })); vi.mock('@modelcontextprotocol/sdk/client/index.js'); -const mockedExtensionStorage = ExtensionStorage as vi.Mock; const mockedLoadSettings = loadSettings as vi.Mock; -const mockedLoadExtensions = loadExtensions as vi.Mock; +const mockedIsWorkspaceTrusted = isWorkspaceTrusted as vi.Mock; const mockedCreateTransport = createTransport as vi.Mock; +const MockedExtensionManager = ExtensionManager as vi.Mock; const MockedClient = Client as vi.Mock; interface MockClient { @@ -58,6 +49,10 @@ describe('mcp list command', () => { let consoleSpy: vi.SpyInstance; let mockClient: MockClient; let mockTransport: MockTransport; + let mockExtensionManager: { + refreshCache: vi.Mock; + getLoadedExtensions: vi.Mock; + }; beforeEach(() => { vi.resetAllMocks(); @@ -71,12 +66,15 @@ describe('mcp list command', () => { close: vi.fn(), }; + mockExtensionManager = { + refreshCache: vi.fn().mockResolvedValue(undefined), + getLoadedExtensions: vi.fn().mockReturnValue([]), + }; + MockedClient.mockImplementation(() => mockClient); mockedCreateTransport.mockResolvedValue(mockTransport); - mockedLoadExtensions.mockReturnValue([]); - mockedExtensionStorage.getUserExtensionsDir.mockReturnValue( - '/mocked/extensions/dir', - ); + MockedExtensionManager.mockImplementation(() => mockExtensionManager); + mockedIsWorkspaceTrusted.mockReturnValue(true); }); afterEach(() => { @@ -152,8 +150,9 @@ describe('mcp list command', () => { }, }); - mockedLoadExtensions.mockReturnValue([ + mockExtensionManager.getLoadedExtensions.mockReturnValue([ { + isActive: true, config: { name: 'test-extension', mcpServers: { 'extension-server': { command: '/ext/server' } }, diff --git a/packages/cli/src/commands/mcp/remove.test.ts b/packages/cli/src/commands/mcp/remove.test.ts index eb7dedce50e..0f3847e40a0 100644 --- a/packages/cli/src/commands/mcp/remove.test.ts +++ b/packages/cli/src/commands/mcp/remove.test.ts @@ -9,10 +9,14 @@ import yargs from 'yargs'; import { loadSettings, SettingScope } from '../../config/settings.js'; import { removeCommand } from './remove.js'; -vi.mock('fs/promises', () => ({ - readFile: vi.fn(), - writeFile: vi.fn(), -})); +vi.mock('fs/promises', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + readFile: vi.fn(), + writeFile: vi.fn(), + }; +}); vi.mock('../../config/settings.js', async () => { const actual = await vi.importActual('../../config/settings.js'); diff --git a/packages/cli/src/services/FileCommandLoader-extension.test.ts b/packages/cli/src/services/FileCommandLoader-extension.test.ts index 38af0865d5f..7f579092182 100644 --- a/packages/cli/src/services/FileCommandLoader-extension.test.ts +++ b/packages/cli/src/services/FileCommandLoader-extension.test.ts @@ -4,324 +4,340 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import * as fs from 'node:fs'; +import { describe, it, expect, afterEach, vi } from 'vitest'; import * as path from 'node:path'; -import * as os from 'node:os'; +import mock from 'mock-fs'; import { FileCommandLoader } from './FileCommandLoader.js'; import type { Config } from '@qwen-code/qwen-code-core'; import { Storage } from '@qwen-code/qwen-code-core'; describe('FileCommandLoader - Extension Commands Support', () => { - let tempDir: string; - let mockConfig: Partial; + const projectRoot = '/test/project'; + const userCommandsDir = Storage.getUserCommandsDir(); + const projectCommandsDir = path.join(projectRoot, '.qwen', 'commands'); - beforeEach(async () => { - tempDir = await fs.promises.mkdtemp( - path.join(os.tmpdir(), 'file-command-loader-ext-test-'), - ); - - mockConfig = { - getFolderTrustFeature: () => false, - getFolderTrust: () => true, - getProjectRoot: () => tempDir, - storage: new Storage(tempDir), - getExtensions: () => [], - }; - }); - - afterEach(async () => { - await fs.promises.rm(tempDir, { recursive: true, force: true }); + afterEach(() => { + mock.restore(); }); it('should load commands from extension with config.commands path', async () => { - // Setup extension structure - const extensionDir = path.join(tempDir, '.qwen', 'extensions', 'test-ext'); - const customCommandsDir = path.join(extensionDir, 'custom-cmds'); - await fs.promises.mkdir(customCommandsDir, { recursive: true }); + const extensionDir = path.join( + projectRoot, + '.qwen', + 'extensions', + 'test-ext', + ); - // Create extension config with custom commands path const extensionConfig = { name: 'test-ext', version: '1.0.0', commands: 'custom-cmds', }; - await fs.promises.writeFile( - path.join(extensionDir, 'qwen-extension.json'), - JSON.stringify(extensionConfig), - ); - - // Create a test command in custom directory - const commandContent = - '---\ndescription: Test command from extension\n---\nDo something'; - await fs.promises.writeFile( - path.join(customCommandsDir, 'test.md'), - commandContent, - ); - // Mock config to return the extension - mockConfig.getExtensions = () => [ - { - id: 'test-ext', - config: extensionConfig, - name: 'test-ext', - version: '1.0.0', - isActive: true, - path: extensionDir, - contextFiles: [], + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [extensionDir]: { + 'qwen-extension.json': JSON.stringify(extensionConfig), + 'custom-cmds': { + 'test.md': + '---\ndescription: Test command from extension\n---\nDo something', + }, }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'test-ext', + config: extensionConfig, + name: 'test-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + contextFiles: [], + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); expect(commands).toHaveLength(1); - expect(commands[0].name).toBe('test-ext:test'); + expect(commands[0].name).toBe('test'); + expect(commands[0].extensionName).toBe('test-ext'); expect(commands[0].description).toBe( '[test-ext] Test command from extension', ); }); it('should load commands from extension with multiple commands paths', async () => { - // Setup extension structure - const extensionDir = path.join(tempDir, '.qwen', 'extensions', 'multi-ext'); - const cmdsDir1 = path.join(extensionDir, 'commands1'); - const cmdsDir2 = path.join(extensionDir, 'commands2'); - await fs.promises.mkdir(cmdsDir1, { recursive: true }); - await fs.promises.mkdir(cmdsDir2, { recursive: true }); - - // Create extension config with multiple commands paths + const extensionDir = path.join( + projectRoot, + '.qwen', + 'extensions', + 'multi-ext', + ); + const extensionConfig = { name: 'multi-ext', version: '1.0.0', commands: ['commands1', 'commands2'], }; - await fs.promises.writeFile( - path.join(extensionDir, 'qwen-extension.json'), - JSON.stringify(extensionConfig), - ); - - // Create test commands in both directories - await fs.promises.writeFile( - path.join(cmdsDir1, 'cmd1.md'), - '---\n---\nCommand 1', - ); - await fs.promises.writeFile( - path.join(cmdsDir2, 'cmd2.md'), - '---\n---\nCommand 2', - ); - // Mock config to return the extension - mockConfig.getExtensions = () => [ - { - id: 'multi-ext', - config: extensionConfig, - contextFiles: [], - name: 'multi-ext', - version: '1.0.0', - isActive: true, - path: extensionDir, + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [extensionDir]: { + 'qwen-extension.json': JSON.stringify(extensionConfig), + commands1: { + 'cmd1.md': '---\n---\nCommand 1', + }, + commands2: { + 'cmd2.md': '---\n---\nCommand 2', + }, }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'multi-ext', + config: extensionConfig, + contextFiles: [], + name: 'multi-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); expect(commands).toHaveLength(2); const commandNames = commands.map((c) => c.name).sort(); - expect(commandNames).toEqual(['multi-ext:cmd1', 'multi-ext:cmd2']); + expect(commandNames).toEqual(['cmd1', 'cmd2']); + expect(commands.every((c) => c.extensionName === 'multi-ext')).toBe(true); }); it('should fallback to default "commands" directory when config.commands not specified', async () => { - // Setup extension structure with default commands directory const extensionDir = path.join( - tempDir, + projectRoot, '.qwen', 'extensions', 'default-ext', ); - const defaultCommandsDir = path.join(extensionDir, 'commands'); - await fs.promises.mkdir(defaultCommandsDir, { recursive: true }); - // Create extension config without commands field const extensionConfig = { name: 'default-ext', version: '1.0.0', }; - await fs.promises.writeFile( - path.join(extensionDir, 'qwen-extension.json'), - JSON.stringify(extensionConfig), - ); - - // Create a test command in default directory - await fs.promises.writeFile( - path.join(defaultCommandsDir, 'default.md'), - '---\n---\nDefault command', - ); - // Mock config to return the extension - mockConfig.getExtensions = () => [ - { - id: 'default-ext', - config: extensionConfig, - contextFiles: [], - name: 'default-ext', - version: '1.0.0', - isActive: true, - path: extensionDir, + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [extensionDir]: { + 'qwen-extension.json': JSON.stringify(extensionConfig), + commands: { + 'default.md': '---\n---\nDefault command', + }, }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'default-ext', + config: extensionConfig, + contextFiles: [], + name: 'default-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); expect(commands).toHaveLength(1); - expect(commands[0].name).toBe('default-ext:default'); + expect(commands[0].name).toBe('default'); + expect(commands[0].extensionName).toBe('default-ext'); }); it('should handle extension without commands directory gracefully', async () => { - // Setup extension structure without commands directory const extensionDir = path.join( - tempDir, + projectRoot, '.qwen', 'extensions', 'no-cmds-ext', ); - await fs.promises.mkdir(extensionDir, { recursive: true }); - // Create extension config const extensionConfig = { name: 'no-cmds-ext', version: '1.0.0', }; - await fs.promises.writeFile( - path.join(extensionDir, 'qwen-extension.json'), - JSON.stringify(extensionConfig), - ); - // Mock config to return the extension - mockConfig.getExtensions = () => [ - { - id: 'no-cmds-ext', - config: extensionConfig, - contextFiles: [], - name: 'no-cmds-ext', - version: '1.0.0', - isActive: true, - path: extensionDir, + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [extensionDir]: { + 'qwen-extension.json': JSON.stringify(extensionConfig), + // No commands directory }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'no-cmds-ext', + config: extensionConfig, + contextFiles: [], + name: 'no-cmds-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); // Should not throw and return empty array expect(commands).toHaveLength(0); }); - it('should prefix extension commands with extension name', async () => { - // Setup extension + it('should set extensionName property for extension commands', async () => { const extensionDir = path.join( - tempDir, + projectRoot, '.qwen', 'extensions', 'prefix-ext', ); - const commandsDir = path.join(extensionDir, 'commands'); - await fs.promises.mkdir(commandsDir, { recursive: true }); const extensionConfig = { name: 'prefix-ext', version: '1.0.0', }; - await fs.promises.writeFile( - path.join(extensionDir, 'qwen-extension.json'), - JSON.stringify(extensionConfig), - ); - await fs.promises.writeFile( - path.join(commandsDir, 'mycommand.md'), - '---\n---\nMy command', - ); - - mockConfig.getExtensions = () => [ - { - id: 'prefix-ext', - config: extensionConfig, - contextFiles: [], - name: 'prefix-ext', - version: '1.0.0', - isActive: true, - path: extensionDir, + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [extensionDir]: { + 'qwen-extension.json': JSON.stringify(extensionConfig), + commands: { + 'mycommand.md': '---\n---\nMy command', + }, }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'prefix-ext', + config: extensionConfig, + contextFiles: [], + name: 'prefix-ext', + version: '1.0.0', + isActive: true, + path: extensionDir, + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); expect(commands).toHaveLength(1); - expect(commands[0].name).toBe('prefix-ext:mycommand'); + expect(commands[0].name).toBe('mycommand'); + expect(commands[0].extensionName).toBe('prefix-ext'); + expect(commands[0].description).toMatch(/^\[prefix-ext\]/); }); it('should load commands from multiple extensions in alphabetical order', async () => { - // Setup two extensions - const ext1Dir = path.join(tempDir, '.qwen', 'extensions', 'ext-b'); - const ext2Dir = path.join(tempDir, '.qwen', 'extensions', 'ext-a'); - - await fs.promises.mkdir(path.join(ext1Dir, 'commands'), { - recursive: true, - }); - await fs.promises.mkdir(path.join(ext2Dir, 'commands'), { - recursive: true, - }); - - // Extension B - await fs.promises.writeFile( - path.join(ext1Dir, 'qwen-extension.json'), - JSON.stringify({ name: 'ext-b', version: '1.0.0' }), - ); - await fs.promises.writeFile( - path.join(ext1Dir, 'commands', 'cmd.md'), - '---\n---\nCommand B', - ); - - // Extension A - await fs.promises.writeFile( - path.join(ext2Dir, 'qwen-extension.json'), - JSON.stringify({ name: 'ext-a', version: '1.0.0' }), - ); - await fs.promises.writeFile( - path.join(ext2Dir, 'commands', 'cmd.md'), - '---\n---\nCommand A', - ); - - mockConfig.getExtensions = () => [ - { - id: 'ext-b', - config: { name: 'ext-b', version: '1.0.0' }, - contextFiles: [], - name: 'ext-b', - version: '1.0.0', - isActive: true, - path: ext1Dir, + const ext1Dir = path.join(projectRoot, '.qwen', 'extensions', 'ext-b'); + const ext2Dir = path.join(projectRoot, '.qwen', 'extensions', 'ext-a'); + + mock({ + [userCommandsDir]: {}, + [projectCommandsDir]: {}, + [ext1Dir]: { + 'qwen-extension.json': JSON.stringify({ + name: 'ext-b', + version: '1.0.0', + }), + commands: { + 'cmd.md': '---\n---\nCommand B', + }, }, - { - id: 'ext-a', - config: { name: 'ext-a', version: '1.0.0' }, - contextFiles: [], - name: 'ext-a', - version: '1.0.0', - isActive: true, - path: ext2Dir, + [ext2Dir]: { + 'qwen-extension.json': JSON.stringify({ + name: 'ext-a', + version: '1.0.0', + }), + commands: { + 'cmd.md': '---\n---\nCommand A', + }, }, - ]; + }); - const loader = new FileCommandLoader(mockConfig as Config); + const mockConfig = { + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => true), + getProjectRoot: vi.fn(() => projectRoot), + storage: new Storage(projectRoot), + getExtensions: vi.fn(() => [ + { + id: 'ext-b', + config: { name: 'ext-b', version: '1.0.0' }, + contextFiles: [], + name: 'ext-b', + version: '1.0.0', + isActive: true, + path: ext1Dir, + }, + { + id: 'ext-a', + config: { name: 'ext-a', version: '1.0.0' }, + contextFiles: [], + name: 'ext-a', + version: '1.0.0', + isActive: true, + path: ext2Dir, + }, + ]), + } as unknown as Config; + + const loader = new FileCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); expect(commands).toHaveLength(2); // Extensions are sorted alphabetically, so ext-a comes before ext-b - expect(commands[0].name).toBe('ext-a:cmd'); - expect(commands[1].name).toBe('ext-b:cmd'); + expect(commands[0].extensionName).toBe('ext-a'); + expect(commands[1].extensionName).toBe('ext-b'); }); }); diff --git a/packages/cli/src/services/FileCommandLoader.test.ts b/packages/cli/src/services/FileCommandLoader.test.ts index e9c49127440..a791f423689 100644 --- a/packages/cli/src/services/FileCommandLoader.test.ts +++ b/packages/cli/src/services/FileCommandLoader.test.ts @@ -568,9 +568,9 @@ describe('FileCommandLoader', () => { expect(commands).toHaveLength(3); const commandNames = commands.map((cmd) => cmd.name); - expect(commandNames).toEqual(['user', 'project', 'test-ext:ext']); + expect(commandNames).toEqual(['user', 'project', 'ext']); - const extCommand = commands.find((cmd) => cmd.name === 'test-ext:ext'); + const extCommand = commands.find((cmd) => cmd.name === 'ext'); expect(extCommand?.extensionName).toBe('test-ext'); expect(extCommand?.description).toMatch(/^\[test-ext\]/); }); @@ -656,14 +656,14 @@ describe('FileCommandLoader', () => { expect(result1.content).toEqual([{ text: 'Project deploy command' }]); } - expect(commands[2].name).toBe('test-ext:deploy'); + expect(commands[2].name).toBe('deploy'); expect(commands[2].extensionName).toBe('test-ext'); expect(commands[2].description).toMatch(/^\[test-ext\]/); const result2 = await commands[2].action?.( createMockCommandContext({ invocation: { - raw: '/test-ext:deploy', - name: 'test-ext:deploy', + raw: '/test-ext.deploy', + name: 'test-ext.deploy', args: '', }, }), @@ -729,7 +729,7 @@ describe('FileCommandLoader', () => { const commands = await loader.loadCommands(signal); expect(commands).toHaveLength(1); - expect(commands[0].name).toBe('active-ext:active'); + expect(commands[0].name).toBe('active'); expect(commands[0].extensionName).toBe('active-ext'); expect(commands[0].description).toMatch(/^\[active-ext\]/); }); @@ -803,17 +803,17 @@ describe('FileCommandLoader', () => { expect(commands).toHaveLength(3); const commandNames = commands.map((cmd) => cmd.name).sort(); - expect(commandNames).toEqual(['a:b:c', 'a:b:d:e', 'a:simple']); + expect(commandNames).toEqual(['b:c', 'b:d:e', 'simple']); - const nestedCmd = commands.find((cmd) => cmd.name === 'a:b:c'); + const nestedCmd = commands.find((cmd) => cmd.name === 'b:c'); expect(nestedCmd?.extensionName).toBe('a'); expect(nestedCmd?.description).toMatch(/^\[a\]/); expect(nestedCmd).toBeDefined(); const result = await nestedCmd!.action?.( createMockCommandContext({ invocation: { - raw: '/a:b:c', - name: 'a:b:c', + raw: '/a.b:c', + name: 'a.b:c', args: '', }, }), diff --git a/packages/cli/src/ui/hooks/useGitBranchName.test.ts b/packages/cli/src/ui/hooks/useGitBranchName.test.ts index a752d073100..dcc64289002 100644 --- a/packages/cli/src/ui/hooks/useGitBranchName.test.ts +++ b/packages/cli/src/ui/hooks/useGitBranchName.test.ts @@ -35,7 +35,10 @@ vi.mock('node:fs', async () => { vi.mock('node:fs/promises', async () => { const memfs = await vi.importActual('memfs'); - return memfs.fs.promises; + return { + ...memfs.fs.promises, + default: memfs.fs.promises, + }; }); const CWD = '/test/project'; diff --git a/packages/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index 449add1164f..f50a209f6eb 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -75,7 +75,9 @@ vi.mock('../tools/tool-registry', () => { }); vi.mock('../utils/memoryDiscovery.js', () => ({ - loadServerHierarchicalMemory: vi.fn(), + loadServerHierarchicalMemory: vi + .fn() + .mockResolvedValue({ memoryContent: '', fileCount: 0 }), })); // Mock individual tools if their constructors are complex or have side effects @@ -1303,7 +1305,10 @@ describe('BaseLlmClient Lifecycle', () => { const authType = AuthType.USE_GEMINI; const mockContentConfig = { model: 'gemini-flash', apiKey: 'test-key' }; - vi.mocked(createContentGeneratorConfig).mockReturnValue(mockContentConfig); + vi.mocked(resolveContentGeneratorConfigWithSources).mockReturnValue({ + config: mockContentConfig, + sources: {}, + }); await config.refreshAuth(authType); diff --git a/packages/core/src/extension/extensionSettings.test.ts b/packages/core/src/extension/extensionSettings.test.ts index 3705be5bd8b..8d29fcdd6cc 100644 --- a/packages/core/src/extension/extensionSettings.test.ts +++ b/packages/core/src/extension/extensionSettings.test.ts @@ -215,7 +215,7 @@ describe('extensionSettings', () => { SENSITIVE_VAR: 'secret', }; const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345`, + `Qwen Code Extensions test-ext 12345`, ); await userKeychain.setSecret('SENSITIVE_VAR', 'secret'); const envPath = path.join(extensionDir, '.env'); @@ -255,7 +255,7 @@ describe('extensionSettings', () => { }; const previousSettings = { SENSITIVE_VAR: 'secret' }; const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345`, + `Qwen Code Extensions test-ext 12345`, ); await userKeychain.setSecret('SENSITIVE_VAR', 'secret'); @@ -520,7 +520,7 @@ describe('extensionSettings', () => { const userEnvPath = path.join(extensionDir, EXTENSION_SETTINGS_FILENAME); await fsPromises.writeFile(userEnvPath, 'VAR1=user-value1'); const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345`, + `Qwen Code Extensions test-ext 12345`, ); await userKeychain.setSecret('SENSITIVE_VAR', 'user-secret'); @@ -543,7 +543,7 @@ describe('extensionSettings', () => { ); await fsPromises.writeFile(workspaceEnvPath, 'VAR1=workspace-value1'); const workspaceKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345 ${tempWorkspaceDir}`, + `Qwen Code Extensions test-ext 12345 ${tempWorkspaceDir}`, ); await workspaceKeychain.setSecret('SENSITIVE_VAR', 'workspace-secret'); @@ -580,7 +580,7 @@ describe('extensionSettings', () => { 'VAR1=user-value1\nVAR3=user-value3', ); const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext ${extensionId}`, + `Qwen Code Extensions test-ext ${extensionId}`, ); await userKeychain.setSecret('VAR2', 'user-secret2'); @@ -591,7 +591,7 @@ describe('extensionSettings', () => { ); await fsPromises.writeFile(workspaceEnvPath, 'VAR1=workspace-value1'); const workspaceKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext ${extensionId} ${tempWorkspaceDir}`, + `Qwen Code Extensions test-ext ${extensionId} ${tempWorkspaceDir}`, ); await workspaceKeychain.setSecret('VAR2', 'workspace-secret2'); @@ -620,7 +620,7 @@ describe('extensionSettings', () => { const userEnvPath = path.join(extensionDir, '.env'); await fsPromises.writeFile(userEnvPath, 'VAR1=value1\n'); const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345`, + `Qwen Code Extensions test-ext 12345`, ); await userKeychain.setSecret('VAR2', 'value2'); mockRequestSetting.mockClear(); @@ -670,7 +670,7 @@ describe('extensionSettings', () => { ); const userKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345`, + `Qwen Code Extensions test-ext 12345`, ); expect(await userKeychain.getSecret('VAR2')).toBe('new-value2'); }); @@ -687,7 +687,7 @@ describe('extensionSettings', () => { ); const workspaceKeychain = new KeychainTokenStorage( - `Gemini CLI Extensions test-ext 12345 ${tempWorkspaceDir}`, + `Qwen Code Extensions test-ext 12345 ${tempWorkspaceDir}`, ); expect(await workspaceKeychain.getSecret('VAR2')).toBe( 'new-workspace-secret', diff --git a/packages/core/src/extension/storage.test.ts b/packages/core/src/extension/storage.test.ts index 7f0b7df0e49..fbbeba3b706 100644 --- a/packages/core/src/extension/storage.test.ts +++ b/packages/core/src/extension/storage.test.ts @@ -26,7 +26,7 @@ vi.mock('node:fs', async (importOriginal) => { }, }; }); -vi.mock('@google/gemini-cli-core'); +vi.mock('../config/storage.js'); describe('ExtensionStorage', () => { const mockHomeDir = '/mock/home'; @@ -38,8 +38,7 @@ describe('ExtensionStorage', () => { vi.mocked(Storage).mockImplementation( () => ({ - getExtensionsDir: () => - path.join(mockHomeDir, '.gemini', 'extensions'), + getExtensionsDir: () => path.join(mockHomeDir, '.qwen', 'extensions'), }) as any, // eslint-disable-line @typescript-eslint/no-explicit-any ); storage = new ExtensionStorage(extensionName); @@ -52,7 +51,7 @@ describe('ExtensionStorage', () => { it('should return the correct extension directory', () => { const expectedDir = path.join( mockHomeDir, - '.gemini', + '.qwen', 'extensions', extensionName, ); @@ -62,7 +61,7 @@ describe('ExtensionStorage', () => { it('should return the correct config path', () => { const expectedPath = path.join( mockHomeDir, - '.gemini', + '.qwen', 'extensions', extensionName, EXTENSIONS_CONFIG_FILENAME, // EXTENSIONS_CONFIG_FILENAME @@ -73,7 +72,7 @@ describe('ExtensionStorage', () => { it('should return the correct env file path', () => { const expectedPath = path.join( mockHomeDir, - '.gemini', + '.qwen', 'extensions', extensionName, EXTENSION_SETTINGS_FILENAME, // EXTENSION_SETTINGS_FILENAME @@ -82,19 +81,19 @@ describe('ExtensionStorage', () => { }); it('should return the correct user extensions directory', () => { - const expectedDir = path.join(mockHomeDir, '.gemini', 'extensions'); + const expectedDir = path.join(mockHomeDir, '.qwen', 'extensions'); expect(ExtensionStorage.getUserExtensionsDir()).toBe(expectedDir); }); it('should create a temporary directory', async () => { - const mockTmpDir = '/tmp/gemini-extension-123'; + const mockTmpDir = '/tmp/qwen-extension-123'; vi.mocked(fs.promises.mkdtemp).mockResolvedValue(mockTmpDir); vi.mocked(os.tmpdir).mockReturnValue('/tmp'); const result = await ExtensionStorage.createTmpDir(); expect(fs.promises.mkdtemp).toHaveBeenCalledWith( - path.join('/tmp', 'gemini-extension'), + path.join('/tmp', 'qwen-extension'), ); expect(result).toBe(mockTmpDir); }); diff --git a/packages/core/src/extension/storage.ts b/packages/core/src/extension/storage.ts index 30d95b34e69..41aa2d120c0 100644 --- a/packages/core/src/extension/storage.ts +++ b/packages/core/src/extension/storage.ts @@ -30,7 +30,17 @@ export class ExtensionStorage { } static getUserExtensionsDir(): string { - const storage = new Storage(os.homedir()); + const homeDir = os.homedir(); + // Fallback for test environments where os.homedir might be mocked to return undefined + if (!homeDir) { + const tmpDir = os.tmpdir(); + if (!tmpDir) { + // Ultimate fallback when both os.homedir and os.tmpdir are mocked + return '/tmp/.qwen/extensions'; + } + return path.join(tmpDir, '.qwen', 'extensions'); + } + const storage = new Storage(homeDir); return storage.getExtensionsDir(); } From 2e80f7ffbce73bcfb2f2c7efbb1db50554951ee7 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 14:35:52 +0800 Subject: [PATCH 21/30] fix config test --- packages/cli/src/commands/extensions/link.ts | 4 ++++ packages/cli/src/commands/extensions/list.ts | 2 +- packages/core/src/config/config.test.ts | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/extensions/link.ts b/packages/cli/src/commands/extensions/link.ts index d3eff0a6ee2..5baeee3f26a 100644 --- a/packages/cli/src/commands/extensions/link.ts +++ b/packages/cli/src/commands/extensions/link.ts @@ -29,6 +29,10 @@ export async function handleLink(args: InstallArgs) { installMetadata, requestConsentOrFail.bind(null, requestConsentNonInteractive), ); + if (!extension) { + console.log('Link extension failed to install.'); + return; + } console.log( `Extension "${extension.name}" linked successfully and enabled.`, ); diff --git a/packages/cli/src/commands/extensions/list.ts b/packages/cli/src/commands/extensions/list.ts index ea0fcba9149..ef6545f206d 100644 --- a/packages/cli/src/commands/extensions/list.ts +++ b/packages/cli/src/commands/extensions/list.ts @@ -13,7 +13,7 @@ export async function handleList() { const extensionManager = await getExtensionManager(); const extensions = extensionManager.getLoadedExtensions(); - if (extensions.length === 0) { + if (!extensions || extensions.length === 0) { console.log('No extensions installed.'); return; } diff --git a/packages/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index f50a209f6eb..a6dfe135e28 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -208,6 +208,7 @@ describe('Server Config (config.ts)', () => { telemetry: TELEMETRY_SETTINGS, model: MODEL, usageStatisticsEnabled: false, + overrideExtensions: [], }; beforeEach(() => { From 452bbc1939ac3c7aed3c5c86794836db56fe09a5 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 14:50:57 +0800 Subject: [PATCH 22/30] fix test online --- packages/core/src/extension/extensionManager.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 0d146af9a43..6a5c88d1c91 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -551,12 +551,17 @@ export class ExtensionManager { async loadExtensionsFromDir(dir: string): Promise { const storage = new Storage(dir); const extensionsDir = storage.getExtensionsDir(); - if (!fs.existsSync(extensionsDir)) { + + let subdirs: string[]; + try { + subdirs = fs.readdirSync(extensionsDir); + } catch { + // Directory doesn't exist or is inaccessible return []; } const extensions: Extension[] = []; - for (const subdir of fs.readdirSync(extensionsDir)) { + for (const subdir of subdirs) { const extensionDir = path.join(extensionsDir, subdir); const extension = await this.loadExtension({ From 2c22961f92b6dd93cfac55e8ddb9781c45d0364e Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 15:19:46 +0800 Subject: [PATCH 23/30] fix test on windows --- packages/cli/src/services/command-migration-tool.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/services/command-migration-tool.test.ts b/packages/cli/src/services/command-migration-tool.test.ts index 128755b3c78..8eae0b02185 100644 --- a/packages/cli/src/services/command-migration-tool.test.ts +++ b/packages/cli/src/services/command-migration-tool.test.ts @@ -57,7 +57,8 @@ describe('command-migration-tool', () => { const tomlFiles = await detectTomlCommands(tempDir); - expect(tomlFiles).toContain('subdir/nested.toml'); + expect(tomlFiles).toHaveLength(1); + expect(tomlFiles[0]).toContain('nested.toml'); }); it('should return empty array for non-existent directory', async () => { From ba14e9e531f2331695a6c0560b13aabdd2da151e Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 16:43:04 +0800 Subject: [PATCH 24/30] add settings command and update extension examples --- packages/cli/src/commands/extensions.tsx | 2 + .../extensions/examples/agent/agents/diary.md | 87 +++++ .../examples/agent/qwen-extension.json | 4 + .../commands/fs/grep-code.md | 0 .../examples/commands/qwen-extension.json | 4 + .../custom-commands/qwen-extension.json | 4 - .../exclude-tools/qwen-extension.json | 4 +- .../examples/mcp-server/package.json | 2 +- .../examples/skills/qwen-extension.json | 4 + .../examples/skills/skills/synonyms/SKILL.md | 48 +++ .../src/commands/extensions/settings.test.ts | 345 ++++++++++++++++++ .../cli/src/commands/extensions/settings.ts | 148 ++++++++ .../core/src/extension/extensionManager.ts | 18 +- .../core/src/extension/extensionSettings.ts | 14 + .../core/src/extension/gemini-converter.ts | 3 +- packages/core/src/extension/index.ts | 1 + packages/core/src/extension/settings.test.ts | 2 +- packages/core/src/extension/settings.ts | 2 +- scripts/prepare-package.js | 40 ++ 19 files changed, 708 insertions(+), 24 deletions(-) create mode 100644 packages/cli/src/commands/extensions/examples/agent/agents/diary.md create mode 100644 packages/cli/src/commands/extensions/examples/agent/qwen-extension.json rename packages/cli/src/commands/extensions/examples/{custom-commands => commands}/commands/fs/grep-code.md (100%) create mode 100644 packages/cli/src/commands/extensions/examples/commands/qwen-extension.json delete mode 100644 packages/cli/src/commands/extensions/examples/custom-commands/qwen-extension.json create mode 100644 packages/cli/src/commands/extensions/examples/skills/qwen-extension.json create mode 100644 packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md create mode 100644 packages/cli/src/commands/extensions/settings.test.ts create mode 100644 packages/cli/src/commands/extensions/settings.ts diff --git a/packages/cli/src/commands/extensions.tsx b/packages/cli/src/commands/extensions.tsx index 12b49e89459..a69a1d85b35 100644 --- a/packages/cli/src/commands/extensions.tsx +++ b/packages/cli/src/commands/extensions.tsx @@ -13,6 +13,7 @@ import { disableCommand } from './extensions/disable.js'; import { enableCommand } from './extensions/enable.js'; import { linkCommand } from './extensions/link.js'; import { newCommand } from './extensions/new.js'; +import { settingsCommand } from './extensions/settings.js'; export const extensionsCommand: CommandModule = { command: 'extensions ', @@ -27,6 +28,7 @@ export const extensionsCommand: CommandModule = { .command(enableCommand) .command(linkCommand) .command(newCommand) + .command(settingsCommand) .demandCommand(1, 'You need at least one command before continuing.') .version(false), handler: () => { diff --git a/packages/cli/src/commands/extensions/examples/agent/agents/diary.md b/packages/cli/src/commands/extensions/examples/agent/agents/diary.md new file mode 100644 index 00000000000..8c0c76a9170 --- /dev/null +++ b/packages/cli/src/commands/extensions/examples/agent/agents/diary.md @@ -0,0 +1,87 @@ +--- +name: diary-writer +description: generate a diary for user +color: yellow +tools: + - Glob + - Grep + - ListFiles + - ReadFile + - ReadManyFiles + - NotebookRead + - WebFetch + - TodoWrite + - WebSearch +modelConfig: + model: qwen3-coder-plus +--- + +You are a personal diary writing assistant who helps users capture their daily experiences, thoughts, and reflections in meaningful journal entries. + +## Core Mission + +Help users create thoughtful, well-structured diary entries that preserve their memories, emotions, and personal growth moments. + +## Writing Style + +**Tone & Voice** + +- Warm, personal, and authentic +- Reflective and introspective +- Supportive without being overly sentimental +- Adapt to user's preferred style (casual, formal, poetic, etc.) + +**Structure Options** + +- Free-form narrative +- Bullet-point highlights +- Gratitude-focused entries +- Goal and achievement tracking +- Emotional processing format + +## Capabilities + +**1. Daily Entry Creation** + +- Transform user's brief notes into full diary entries +- Expand on key moments with descriptive details +- Add context about weather, mood, or setting when relevant +- Include meaningful quotes or observations + +**2. Reflection Prompts** + +- Ask thoughtful questions to deepen entries +- Suggest areas worth exploring further +- Help identify patterns in thoughts and behaviors +- Encourage gratitude and positive reflection + +**3. Memory Enhancement** + +- Help recall specific details from the day +- Connect current events to past experiences +- Highlight personal growth and progress +- Preserve important conversations or interactions + +**4. Organization** + +- Suggest tags or themes for entries +- Create summaries for weekly/monthly reviews +- Track recurring topics or goals +- Maintain consistency in formatting + +## Guidelines + +- **Privacy First**: Treat all content as deeply personal and confidential +- **User's Voice**: Write in a way that sounds like the user, not generic +- **No Judgment**: Accept all emotions and experiences without criticism +- **Encourage Honesty**: Create a safe space for authentic expression +- **Balance**: Mix facts with feelings, events with reflections + +## Output Format + +When creating a diary entry, include: + +1. **Date & Title** (optional creative title) +2. **Main Content** - The narrative or bullet points +3. **Reflection** - A brief closing thought or takeaway +4. **Tags** (optional) - For organization and future reference diff --git a/packages/cli/src/commands/extensions/examples/agent/qwen-extension.json b/packages/cli/src/commands/extensions/examples/agent/qwen-extension.json new file mode 100644 index 00000000000..a9a8e8a6804 --- /dev/null +++ b/packages/cli/src/commands/extensions/examples/agent/qwen-extension.json @@ -0,0 +1,4 @@ +{ + "name": "agent-example", + "version": "1.0.0" +} diff --git a/packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.md b/packages/cli/src/commands/extensions/examples/commands/commands/fs/grep-code.md similarity index 100% rename from packages/cli/src/commands/extensions/examples/custom-commands/commands/fs/grep-code.md rename to packages/cli/src/commands/extensions/examples/commands/commands/fs/grep-code.md diff --git a/packages/cli/src/commands/extensions/examples/commands/qwen-extension.json b/packages/cli/src/commands/extensions/examples/commands/qwen-extension.json new file mode 100644 index 00000000000..277a405485b --- /dev/null +++ b/packages/cli/src/commands/extensions/examples/commands/qwen-extension.json @@ -0,0 +1,4 @@ +{ + "name": "commands-example", + "version": "1.0.0" +} diff --git a/packages/cli/src/commands/extensions/examples/custom-commands/qwen-extension.json b/packages/cli/src/commands/extensions/examples/custom-commands/qwen-extension.json deleted file mode 100644 index d973ab8fe44..00000000000 --- a/packages/cli/src/commands/extensions/examples/custom-commands/qwen-extension.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "custom-commands", - "version": "1.0.0" -} diff --git a/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json b/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json index 5023fb7ad06..584b6abc050 100644 --- a/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json +++ b/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json @@ -1,5 +1,5 @@ { - "name": "excludeTools", + "name": "exclude-tools-example", "version": "1.0.0", - "excludeTools": ["run_shell_command(rm -rf)"] + "excludeTools": ["Shell(rm -rf)"] } diff --git a/packages/cli/src/commands/extensions/examples/mcp-server/package.json b/packages/cli/src/commands/extensions/examples/mcp-server/package.json index d38f7ee99d9..59c1c45c12e 100644 --- a/packages/cli/src/commands/extensions/examples/mcp-server/package.json +++ b/packages/cli/src/commands/extensions/examples/mcp-server/package.json @@ -1,7 +1,7 @@ { "name": "mcp-server-example", "version": "1.0.0", - "description": "Example MCP Server for Gemini CLI Extension", + "description": "Example MCP Server for Qwen Code Extension", "type": "module", "main": "example.js", "scripts": { diff --git a/packages/cli/src/commands/extensions/examples/skills/qwen-extension.json b/packages/cli/src/commands/extensions/examples/skills/qwen-extension.json new file mode 100644 index 00000000000..2674ef9e0f4 --- /dev/null +++ b/packages/cli/src/commands/extensions/examples/skills/qwen-extension.json @@ -0,0 +1,4 @@ +{ + "name": "skills-example", + "version": "1.0.0" +} diff --git a/packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md b/packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md new file mode 100644 index 00000000000..ed2878771f5 --- /dev/null +++ b/packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md @@ -0,0 +1,48 @@ +--- +name: synonyms +description: Generate synonyms for words or phrases. Use this skill when the user needs alternative words with similar meanings, wants to expand vocabulary, or seeks varied expressions for writing. +license: Complete terms in LICENSE.txt +--- + +This skill helps generate synonyms and alternative expressions for given words or phrases. It provides contextually appropriate alternatives to enhance vocabulary and improve writing variety. + +The user provides a word, phrase, or sentence where they need synonym suggestions. They may specify the context, tone, or formality level desired. + +## Synonym Generation Guidelines + +When generating synonyms, consider: + +- **Context**: The specific domain or situation where the word will be used +- **Tone**: Formal, informal, neutral, academic, conversational, etc. +- **Nuance**: Subtle differences in meaning between similar words +- **Register**: Appropriate level of formality for the intended audience + +## Output Format + +For each input word or phrase, provide: + +1. **Direct Synonyms**: Words with nearly identical meanings +2. **Related Alternatives**: Words with similar but slightly different connotations +3. **Context Examples**: Brief usage examples when helpful + +## Best Practices + +- Prioritize commonly used synonyms over obscure alternatives +- Note any subtle differences in meaning or usage +- Consider regional variations when relevant +- Indicate formality levels (formal/informal/neutral) +- Provide multiple options to give users choices + +## Example + +**Input**: "happy" + +**Synonyms**: + +- **Direct**: joyful, cheerful, delighted, pleased, content +- **Informal**: thrilled, stoked, over the moon +- **Formal**: elated, gratified, blissful +- **Subtle variations**: + - _content_ - peaceful satisfaction + - _ecstatic_ - intense, overwhelming happiness + - _cheerful_ - outwardly expressing happiness diff --git a/packages/cli/src/commands/extensions/settings.test.ts b/packages/cli/src/commands/extensions/settings.test.ts new file mode 100644 index 00000000000..042965eec4c --- /dev/null +++ b/packages/cli/src/commands/extensions/settings.test.ts @@ -0,0 +1,345 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + describe, + it, + expect, + vi, + beforeEach, + type MockInstance, +} from 'vitest'; +import { settingsCommand } from './settings.js'; +import yargs from 'yargs'; + +const mockGetLoadedExtensions = vi.hoisted(() => vi.fn()); +const mockGetScopedEnvContents = vi.hoisted(() => vi.fn()); +const mockUpdateSetting = vi.hoisted(() => vi.fn()); +const mockPromptForSetting = vi.hoisted(() => vi.fn()); + +vi.mock('./utils.js', () => ({ + getExtensionManager: vi.fn().mockResolvedValue({ + getLoadedExtensions: mockGetLoadedExtensions, + }), +})); + +vi.mock('@qwen-code/qwen-code-core', () => ({ + ExtensionSettingScope: { + USER: 'user', + WORKSPACE: 'workspace', + }, + getScopedEnvContents: mockGetScopedEnvContents, + promptForSetting: mockPromptForSetting, + updateSetting: mockUpdateSetting, +})); + +describe('extensions settings command', () => { + it('should fail if no subcommand is provided', () => { + const validationParser = yargs([]) + .command(settingsCommand) + .fail(false) + .locale('en'); + expect(() => validationParser.parse('settings')).toThrow( + 'Not enough non-option arguments: got 0, need at least 1', + ); + }); + + it('should register set subcommand', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => parser.parse('settings set')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should register list subcommand', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => parser.parse('settings list')).toThrow( + 'Not enough non-option arguments', + ); + }); + + it('should accept set command with name and setting', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => + parser.parse('settings set my-extension API_KEY'), + ).not.toThrow(); + }); + + it('should accept set command with scope option', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => + parser.parse('settings set my-extension API_KEY --scope=workspace'), + ).not.toThrow(); + }); + + it('should fail set command with invalid scope', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => + parser.parse('settings set my-extension API_KEY --scope=invalid'), + ).toThrow(); + }); + + it('should accept list command with name', () => { + const parser = yargs([]).command(settingsCommand).fail(false).locale('en'); + expect(() => parser.parse('settings list my-extension')).not.toThrow(); + }); +}); + +describe('settings set handler', () => { + let consoleLogSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.clearAllMocks(); + }); + + it('should return early if extension manager is not available', async () => { + const { getExtensionManager } = await import('./utils.js'); + vi.mocked(getExtensionManager).mockResolvedValueOnce(null as never); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings set my-extension API_KEY'); + + expect(mockUpdateSetting).not.toHaveBeenCalled(); + }); + + it('should return early if no extensions are loaded', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings set my-extension API_KEY'); + + expect(mockUpdateSetting).not.toHaveBeenCalled(); + }); + + it('should log error if extension is not found', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([ + { name: 'other-extension', id: 'other-id', config: {} }, + ]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings set my-extension API_KEY'); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "my-extension" not found.', + ); + expect(mockUpdateSetting).not.toHaveBeenCalled(); + }); + + it('should call updateSetting with correct arguments for user scope', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension', settings: [] }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings set my-extension API_KEY'); + + expect(mockUpdateSetting).toHaveBeenCalledWith( + mockExtension.config, + mockExtension.id, + 'API_KEY', + mockPromptForSetting, + 'user', + ); + }); + + it('should call updateSetting with workspace scope when specified', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension', settings: [] }, + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync( + 'settings set my-extension API_KEY --scope=workspace', + ); + + expect(mockUpdateSetting).toHaveBeenCalledWith( + mockExtension.config, + mockExtension.id, + 'API_KEY', + mockPromptForSetting, + 'workspace', + ); + }); +}); + +describe('settings list handler', () => { + let consoleLogSpy: MockInstance; + + beforeEach(() => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.clearAllMocks(); + }); + + it('should return early if extension manager is not available', async () => { + const { getExtensionManager } = await import('./utils.js'); + vi.mocked(getExtensionManager).mockResolvedValueOnce(null as never); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(mockGetScopedEnvContents).not.toHaveBeenCalled(); + }); + + it('should return early if no extensions are loaded', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(mockGetScopedEnvContents).not.toHaveBeenCalled(); + }); + + it('should log error if extension is not found', async () => { + mockGetLoadedExtensions.mockReturnValueOnce([ + { name: 'other-extension', id: 'other-id', config: {} }, + ]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "my-extension" not found.', + ); + }); + + it('should log message if extension has no settings', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension' }, + settings: [], + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(consoleLogSpy).toHaveBeenCalledWith( + 'Extension "my-extension" has no settings to configure.', + ); + }); + + it('should list settings with their values', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension' }, + settings: [ + { + name: 'API Key', + envVar: 'API_KEY', + description: 'Your API key', + sensitive: false, + }, + { + name: 'Secret Token', + envVar: 'SECRET_TOKEN', + description: 'A secret token', + sensitive: true, + }, + ], + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockGetScopedEnvContents + .mockResolvedValueOnce({ API_KEY: 'my-api-key' }) // user scope + .mockResolvedValueOnce({}); // workspace scope + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(consoleLogSpy).toHaveBeenCalledWith('Settings for "my-extension":'); + expect(consoleLogSpy).toHaveBeenCalledWith('\n- API Key (API_KEY)'); + expect(consoleLogSpy).toHaveBeenCalledWith(' Description: Your API key'); + expect(consoleLogSpy).toHaveBeenCalledWith(' Value: my-api-key (user)'); + }); + + it('should show workspace scope for workspace-scoped settings', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension' }, + settings: [ + { + name: 'API Key', + envVar: 'API_KEY', + description: 'Your API key', + sensitive: false, + }, + ], + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockGetScopedEnvContents + .mockResolvedValueOnce({ API_KEY: 'user-value' }) // user scope + .mockResolvedValueOnce({ API_KEY: 'workspace-value' }); // workspace scope + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + // Workspace should override user, and show (workspace) scope + expect(consoleLogSpy).toHaveBeenCalledWith( + ' Value: workspace-value (workspace)', + ); + }); + + it('should show [not set] for undefined settings', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension' }, + settings: [ + { + name: 'API Key', + envVar: 'API_KEY', + description: 'Your API key', + sensitive: false, + }, + ], + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockGetScopedEnvContents + .mockResolvedValueOnce({}) // user scope + .mockResolvedValueOnce({}); // workspace scope + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(consoleLogSpy).toHaveBeenCalledWith(' Value: [not set]'); + }); + + it('should show [value stored in keychain] for sensitive settings', async () => { + const mockExtension = { + name: 'my-extension', + id: 'ext-id-123', + config: { name: 'my-extension' }, + settings: [ + { + name: 'Secret Token', + envVar: 'SECRET_TOKEN', + description: 'A secret token', + sensitive: true, + }, + ], + }; + mockGetLoadedExtensions.mockReturnValueOnce([mockExtension]); + mockGetScopedEnvContents + .mockResolvedValueOnce({ SECRET_TOKEN: 'secret-value' }) // user scope + .mockResolvedValueOnce({}); // workspace scope + + const parser = yargs([]).command(settingsCommand); + await parser.parseAsync('settings list my-extension'); + + expect(consoleLogSpy).toHaveBeenCalledWith( + ' Value: [value stored in keychain] (user)', + ); + }); +}); diff --git a/packages/cli/src/commands/extensions/settings.ts b/packages/cli/src/commands/extensions/settings.ts new file mode 100644 index 00000000000..edcdadfd995 --- /dev/null +++ b/packages/cli/src/commands/extensions/settings.ts @@ -0,0 +1,148 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { CommandModule } from 'yargs'; +import { getExtensionManager } from './utils.js'; +import { + ExtensionSettingScope, + getScopedEnvContents, + promptForSetting, + updateSetting, +} from '@qwen-code/qwen-code-core'; + +// --- SET COMMAND --- +interface SetArgs { + name: string; + setting: string; + scope: string; +} + +const setCommand: CommandModule = { + command: 'set [--scope] ', + describe: 'Set a specific setting for an extension.', + builder: (yargs) => + yargs + .positional('name', { + describe: 'Name of the extension to configure.', + type: 'string', + demandOption: true, + }) + .positional('setting', { + describe: 'The setting to configure (name or env var).', + type: 'string', + demandOption: true, + }) + .option('scope', { + describe: 'The scope to set the setting in.', + type: 'string', + choices: ['user', 'workspace'], + default: 'user', + }), + handler: async (args) => { + const { name, setting, scope } = args; + const extensionManager = await getExtensionManager(); + if (!extensionManager) return; + const extensions = extensionManager.getLoadedExtensions(); + if (!extensions || extensions.length === 0) return; + const extension = extensions.find((e) => e.name === name); + if (!extension) { + console.log(`Extension "${name}" not found.`); + return; + } + await updateSetting( + extension.config, + extension.id, + setting, + promptForSetting, + scope as ExtensionSettingScope, + ); + }, +}; + +// --- LIST COMMAND --- +interface ListArgs { + name: string; +} + +const listCommand: CommandModule = { + command: 'list ', + describe: 'List all settings for an extension.', + builder: (yargs) => + yargs.positional('name', { + describe: 'Name of the extension.', + type: 'string', + demandOption: true, + }), + handler: async (args) => { + const { name } = args; + const extensionManager = await getExtensionManager(); + if (!extensionManager) return; + const extensions = extensionManager.getLoadedExtensions(); + if (!extensions || extensions.length === 0) return; + const extension = extensions.find((e) => e.name === name); + if (!extension) { + console.log(`Extension "${name}" not found.`); + return; + } + if (!extension || !extension.settings || extension.settings.length === 0) { + console.log(`Extension "${name}" has no settings to configure.`); + return; + } + + const userSettings = await getScopedEnvContents( + extension.config, + extension.id, + ExtensionSettingScope.USER, + ); + const workspaceSettings = await getScopedEnvContents( + extension.config, + extension.id, + ExtensionSettingScope.WORKSPACE, + ); + const mergedSettings = { ...userSettings, ...workspaceSettings }; + + console.log(`Settings for "${name}":`); + for (const setting of extension.settings) { + const value = mergedSettings[setting.envVar]; + let displayValue: string; + let scopeInfo = ''; + + if (workspaceSettings[setting.envVar] !== undefined) { + scopeInfo = ' (workspace)'; + } else if (userSettings[setting.envVar] !== undefined) { + scopeInfo = ' (user)'; + } + + if (value === undefined) { + displayValue = '[not set]'; + } else if (setting.sensitive) { + displayValue = '[value stored in keychain]'; + } else { + displayValue = value; + } + console.log(` +- ${setting.name} (${setting.envVar})`); + console.log(` Description: ${setting.description}`); + console.log(` Value: ${displayValue}${scopeInfo}`); + } + }, +}; + +// --- SETTINGS COMMAND --- +export const settingsCommand: CommandModule = { + command: 'settings ', + describe: 'Manage extension settings.', + builder: (yargs) => + yargs + .command(setCommand) + .command(listCommand) + .demandCommand(1, 'You need to specify a command (set or list).') + .version(false), + handler: () => { + // This handler is not called when a subcommand is provided. + // Yargs will show the help menu. + }, +}; diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 6a5c88d1c91..93a4d357706 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -50,6 +50,10 @@ import { maybePromptForSettings, promptForSetting, } from './extensionSettings.js'; +import type { + ExtensionSetting, + ResolvedExtensionSetting, +} from './extensionSettings.js'; import type { TelemetrySettings } from '../config/config.js'; import { logExtensionUpdateEvent } from '../telemetry/loggers.js'; import { @@ -106,20 +110,6 @@ export interface ExtensionConfig { settings?: ExtensionSetting[]; } -export interface ExtensionSetting { - name: string; - description: string; - envVar: string; - sensitive?: boolean; -} - -export interface ResolvedExtensionSetting { - name: string; - envVar: string; - value: string; - sensitive: boolean; -} - export interface ExtensionUpdateInfo { name: string; originalVersion: string; diff --git a/packages/core/src/extension/extensionSettings.ts b/packages/core/src/extension/extensionSettings.ts index d35573d52d2..e821788ba7e 100644 --- a/packages/core/src/extension/extensionSettings.ts +++ b/packages/core/src/extension/extensionSettings.ts @@ -14,6 +14,20 @@ import prompts from 'prompts'; import { EXTENSION_SETTINGS_FILENAME } from './variables.js'; import { KeychainTokenStorage } from '../mcp/token-storage/keychain-token-storage.js'; +export interface ExtensionSetting { + name: string; + description: string; + envVar: string; + sensitive?: boolean; +} + +export interface ResolvedExtensionSetting { + name: string; + envVar: string; + value: string; + sensitive: boolean; +} + export enum ExtensionSettingScope { USER = 'user', WORKSPACE = 'workspace', diff --git a/packages/core/src/extension/gemini-converter.ts b/packages/core/src/extension/gemini-converter.ts index c3dee4966fb..fa5ad499e1c 100644 --- a/packages/core/src/extension/gemini-converter.ts +++ b/packages/core/src/extension/gemini-converter.ts @@ -11,7 +11,8 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { glob } from 'glob'; -import type { ExtensionConfig, ExtensionSetting } from './extensionManager.js'; +import type { ExtensionConfig } from './extensionManager.js'; +import type { ExtensionSetting } from './extensionSettings.js'; import { ExtensionStorage } from './storage.js'; import { convertTomlToMarkdown } from '../utils/toml-to-markdown-converter.js'; diff --git a/packages/core/src/extension/index.ts b/packages/core/src/extension/index.ts index dd4b413fb53..2940d584791 100644 --- a/packages/core/src/extension/index.ts +++ b/packages/core/src/extension/index.ts @@ -1,3 +1,4 @@ export * from './extensionManager.js'; export * from './variables.js'; export * from './github.js'; +export * from './extensionSettings.js'; diff --git a/packages/core/src/extension/settings.test.ts b/packages/core/src/extension/settings.test.ts index cef81dd01a1..3a2c08c57e3 100644 --- a/packages/core/src/extension/settings.test.ts +++ b/packages/core/src/extension/settings.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect } from 'vitest'; import { parseEnvFile, generateEnvFile, validateSettings } from './settings.js'; -import type { ExtensionSetting } from './extensionManager.js'; +import type { ExtensionSetting } from './extensionSettings.js'; describe('Extension Settings', () => { describe('parseEnvFile', () => { diff --git a/packages/core/src/extension/settings.ts b/packages/core/src/extension/settings.ts index 522ffd0916a..a31436c9041 100644 --- a/packages/core/src/extension/settings.ts +++ b/packages/core/src/extension/settings.ts @@ -11,7 +11,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import type { ExtensionSetting } from './extensionManager.js'; +import type { ExtensionSetting } from './extensionSettings.js'; /** * Parse .env file content into key-value pairs. diff --git a/scripts/prepare-package.js b/scripts/prepare-package.js index 534f104c879..ac886268661 100644 --- a/scripts/prepare-package.js +++ b/scripts/prepare-package.js @@ -93,6 +93,46 @@ if (fs.existsSync(localesSourceDir)) { console.warn(`Warning: locales folder not found at ${localesSourceDir}`); } +// Copy extensions folder +console.log('Copying extension examples folder...'); +const extensionExamplesDir = path.join( + rootDir, + 'packages', + 'cli', + 'src', + 'commands', + 'extensions', + 'examples', +); +const extensionExamplesDestDir = path.join(distDir, 'examples'); + +if (fs.existsSync(extensionExamplesDir)) { + // Recursive copy function + function copyRecursiveSync(src, dest) { + const stats = fs.statSync(src); + if (stats.isDirectory()) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest, { recursive: true }); + } + const entries = fs.readdirSync(src); + for (const entry of entries) { + const srcPath = path.join(src, entry); + const destPath = path.join(dest, entry); + copyRecursiveSync(srcPath, destPath); + } + } else { + fs.copyFileSync(src, dest); + } + } + + copyRecursiveSync(extensionExamplesDir, extensionExamplesDestDir); + console.log('Copied extension examples folder'); +} else { + console.warn( + `Warning: extension examples folder not found at ${extensionExamplesDir}`, + ); +} + // Copy package.json from root and modify it for publishing console.log('Creating package.json for distribution...'); const rootPackageJson = JSON.parse( From e87376e06cfab6bca8a0e92912a238f2ecabed2e Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 17:20:20 +0800 Subject: [PATCH 25/30] i18n add extension commands --- .../cli/src/commands/extensions/disable.ts | 23 +++-- .../cli/src/commands/extensions/enable.ts | 28 +++--- .../cli/src/commands/extensions/install.ts | 26 ++++-- packages/cli/src/commands/extensions/link.ts | 12 ++- packages/cli/src/commands/extensions/list.ts | 5 +- .../cli/src/commands/extensions/settings.ts | 39 +++++---- .../cli/src/commands/extensions/uninstall.ts | 13 ++- .../cli/src/commands/extensions/update.ts | 47 +++++++--- packages/cli/src/i18n/locales/de.js | 85 +++++++++++++++++++ packages/cli/src/i18n/locales/en.js | 79 +++++++++++++++++ packages/cli/src/i18n/locales/ru.js | 78 +++++++++++++++++ packages/cli/src/i18n/locales/zh.js | 72 ++++++++++++++++ 12 files changed, 440 insertions(+), 67 deletions(-) diff --git a/packages/cli/src/commands/extensions/disable.ts b/packages/cli/src/commands/extensions/disable.ts index 35be4aa8c11..92ebd6fa8fe 100644 --- a/packages/cli/src/commands/extensions/disable.ts +++ b/packages/cli/src/commands/extensions/disable.ts @@ -8,6 +8,7 @@ import { type CommandModule } from 'yargs'; import { SettingScope } from '../../config/settings.js'; import { getErrorMessage } from '../../utils/errors.js'; import { getExtensionManager } from './utils.js'; +import { t } from '../../i18n/index.js'; interface DisableArgs { name: string; @@ -23,7 +24,10 @@ export async function handleDisable(args: DisableArgs) { extensionManager.disableExtension(args.name, SettingScope.User); } console.log( - `Extension "${args.name}" successfully disabled for scope "${args.scope}".`, + t('Extension "{{name}}" successfully disabled for scope "{{scope}}".', { + name: args.name, + scope: args.scope || SettingScope.User, + }), ); } catch (error) { console.error(getErrorMessage(error)); @@ -33,15 +37,15 @@ export async function handleDisable(args: DisableArgs) { export const disableCommand: CommandModule = { command: 'disable [--scope] ', - describe: 'Disables an extension.', + describe: t('Disables an extension.'), builder: (yargs) => yargs .positional('name', { - describe: 'The name of the extension to disable.', + describe: t('The name of the extension to disable.'), type: 'string', }) .option('scope', { - describe: 'The scope to disable the extenison in.', + describe: t('The scope to disable the extenison in.'), type: 'string', default: SettingScope.User, }) @@ -53,11 +57,12 @@ export const disableCommand: CommandModule = { .includes((argv.scope as string).toLowerCase()) ) { throw new Error( - `Invalid scope: ${argv.scope}. Please use one of ${Object.values( - SettingScope, - ) - .map((s) => s.toLowerCase()) - .join(', ')}.`, + t('Invalid scope: {{scope}}. Please use one of {{scopes}}.', { + scope: argv.scope as string, + scopes: Object.values(SettingScope) + .map((s) => s.toLowerCase()) + .join(', '), + }), ); } return true; diff --git a/packages/cli/src/commands/extensions/enable.ts b/packages/cli/src/commands/extensions/enable.ts index 2286105271a..b36e50ac9eb 100644 --- a/packages/cli/src/commands/extensions/enable.ts +++ b/packages/cli/src/commands/extensions/enable.ts @@ -8,6 +8,7 @@ import { type CommandModule } from 'yargs'; import { FatalConfigError, getErrorMessage } from '@qwen-code/qwen-code-core'; import { SettingScope } from '../../config/settings.js'; import { getExtensionManager } from './utils.js'; +import { t } from '../../i18n/index.js'; interface EnableArgs { name: string; @@ -25,11 +26,16 @@ export async function handleEnable(args: EnableArgs) { } if (args.scope) { console.log( - `Extension "${args.name}" successfully enabled for scope "${args.scope}".`, + t('Extension "{{name}}" successfully enabled for scope "{{scope}}".', { + name: args.name, + scope: args.scope, + }), ); } else { console.log( - `Extension "${args.name}" successfully enabled in all scopes.`, + t('Extension "{{name}}" successfully enabled in all scopes.', { + name: args.name, + }), ); } } catch (error) { @@ -39,16 +45,17 @@ export async function handleEnable(args: EnableArgs) { export const enableCommand: CommandModule = { command: 'enable [--scope] ', - describe: 'Enables an extension.', + describe: t('Enables an extension.'), builder: (yargs) => yargs .positional('name', { - describe: 'The name of the extension to enable.', + describe: t('The name of the extension to enable.'), type: 'string', }) .option('scope', { - describe: + describe: t( 'The scope to enable the extenison in. If not set, will be enabled in all scopes.', + ), type: 'string', }) .check((argv) => { @@ -59,11 +66,12 @@ export const enableCommand: CommandModule = { .includes((argv.scope as string).toLowerCase()) ) { throw new Error( - `Invalid scope: ${argv.scope}. Please use one of ${Object.values( - SettingScope, - ) - .map((s) => s.toLowerCase()) - .join(', ')}.`, + t('Invalid scope: {{scope}}. Please use one of {{scopes}}.', { + scope: argv.scope as string, + scopes: Object.values(SettingScope) + .map((s) => s.toLowerCase()) + .join(', '), + }), ); } return true; diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index 64b89003c7a..6a9ce49296d 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -17,6 +17,7 @@ import { requestConsentOrFail, requestConsentNonInteractive, } from './consent.js'; +import { t } from '../../i18n/index.js'; interface InstallArgs { source: string; @@ -36,7 +37,9 @@ export async function handleInstall(args: InstallArgs) { ) { if (args.ref || args.autoUpdate) { throw new Error( - '--ref and --auto-update are not applicable for marketplace extensions.', + t( + '--ref and --auto-update are not applicable for marketplace extensions.', + ), ); } } @@ -64,7 +67,9 @@ export async function handleInstall(args: InstallArgs) { requestConsent, ); console.log( - `Extension "${extension.name}" installed successfully and enabled.`, + t('Extension "{{name}}" installed successfully and enabled.', { + name: extension.name, + }), ); } catch (error) { console.error(getErrorMessage(error)); @@ -74,37 +79,40 @@ export async function handleInstall(args: InstallArgs) { export const installCommand: CommandModule = { command: 'install ', - describe: + describe: t( 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).', + ), builder: (yargs) => yargs .positional('source', { - describe: + describe: t( 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.', + ), type: 'string', demandOption: true, }) .option('ref', { - describe: 'The git ref to install from.', + describe: t('The git ref to install from.'), type: 'string', }) .option('auto-update', { - describe: 'Enable auto-update for this extension.', + describe: t('Enable auto-update for this extension.'), type: 'boolean', }) .option('pre-release', { - describe: 'Enable pre-release versions for this extension.', + describe: t('Enable pre-release versions for this extension.'), type: 'boolean', }) .option('consent', { - describe: + describe: t( 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.', + ), type: 'boolean', default: false, }) .check((argv) => { if (!argv.source) { - throw new Error('The source argument must be provided.'); + throw new Error(t('The source argument must be provided.')); } return true; }), diff --git a/packages/cli/src/commands/extensions/link.ts b/packages/cli/src/commands/extensions/link.ts index 5baeee3f26a..545899cda01 100644 --- a/packages/cli/src/commands/extensions/link.ts +++ b/packages/cli/src/commands/extensions/link.ts @@ -12,6 +12,7 @@ import { requestConsentOrFail, } from './consent.js'; import { getExtensionManager } from './utils.js'; +import { t } from '../../i18n/index.js'; interface InstallArgs { path: string; @@ -30,11 +31,13 @@ export async function handleLink(args: InstallArgs) { requestConsentOrFail.bind(null, requestConsentNonInteractive), ); if (!extension) { - console.log('Link extension failed to install.'); + console.log(t('Link extension failed to install.')); return; } console.log( - `Extension "${extension.name}" linked successfully and enabled.`, + t('Extension "{{name}}" linked successfully and enabled.', { + name: extension.name, + }), ); } catch (error) { console.error(getErrorMessage(error)); @@ -44,12 +47,13 @@ export async function handleLink(args: InstallArgs) { export const linkCommand: CommandModule = { command: 'link ', - describe: + describe: t( 'Links an extension from a local path. Updates made to the local path will always be reflected.', + ), builder: (yargs) => yargs .positional('path', { - describe: 'The name of the extension to link.', + describe: t('The name of the extension to link.'), type: 'string', }) .check((_) => true), diff --git a/packages/cli/src/commands/extensions/list.ts b/packages/cli/src/commands/extensions/list.ts index ef6545f206d..9f8a3a7f6ae 100644 --- a/packages/cli/src/commands/extensions/list.ts +++ b/packages/cli/src/commands/extensions/list.ts @@ -7,6 +7,7 @@ import type { CommandModule } from 'yargs'; import { getErrorMessage } from '../../utils/errors.js'; import { getExtensionManager } from './utils.js'; +import { t } from '../../i18n/index.js'; export async function handleList() { try { @@ -14,7 +15,7 @@ export async function handleList() { const extensions = extensionManager.getLoadedExtensions(); if (!extensions || extensions.length === 0) { - console.log('No extensions installed.'); + console.log(t('No extensions installed.')); return; } console.log( @@ -32,7 +33,7 @@ export async function handleList() { export const listCommand: CommandModule = { command: 'list', - describe: 'Lists installed extensions.', + describe: t('Lists installed extensions.'), builder: (yargs) => yargs, handler: async () => { await handleList(); diff --git a/packages/cli/src/commands/extensions/settings.ts b/packages/cli/src/commands/extensions/settings.ts index edcdadfd995..49baf2cc43b 100644 --- a/packages/cli/src/commands/extensions/settings.ts +++ b/packages/cli/src/commands/extensions/settings.ts @@ -12,6 +12,7 @@ import { promptForSetting, updateSetting, } from '@qwen-code/qwen-code-core'; +import { t } from '../../i18n/index.js'; // --- SET COMMAND --- interface SetArgs { @@ -22,21 +23,21 @@ interface SetArgs { const setCommand: CommandModule = { command: 'set [--scope] ', - describe: 'Set a specific setting for an extension.', + describe: t('Set a specific setting for an extension.'), builder: (yargs) => yargs .positional('name', { - describe: 'Name of the extension to configure.', + describe: t('Name of the extension to configure.'), type: 'string', demandOption: true, }) .positional('setting', { - describe: 'The setting to configure (name or env var).', + describe: t('The setting to configure (name or env var).'), type: 'string', demandOption: true, }) .option('scope', { - describe: 'The scope to set the setting in.', + describe: t('The scope to set the setting in.'), type: 'string', choices: ['user', 'workspace'], default: 'user', @@ -49,7 +50,7 @@ const setCommand: CommandModule = { if (!extensions || extensions.length === 0) return; const extension = extensions.find((e) => e.name === name); if (!extension) { - console.log(`Extension "${name}" not found.`); + console.log(t('Extension "{{name}}" not found.', { name })); return; } await updateSetting( @@ -69,10 +70,10 @@ interface ListArgs { const listCommand: CommandModule = { command: 'list ', - describe: 'List all settings for an extension.', + describe: t('List all settings for an extension.'), builder: (yargs) => yargs.positional('name', { - describe: 'Name of the extension.', + describe: t('Name of the extension.'), type: 'string', demandOption: true, }), @@ -84,11 +85,13 @@ const listCommand: CommandModule = { if (!extensions || extensions.length === 0) return; const extension = extensions.find((e) => e.name === name); if (!extension) { - console.log(`Extension "${name}" not found.`); + console.log(t('Extension "{{name}}" not found.', { name })); return; } if (!extension || !extension.settings || extension.settings.length === 0) { - console.log(`Extension "${name}" has no settings to configure.`); + console.log( + t('Extension "{{name}}" has no settings to configure.', { name }), + ); return; } @@ -104,29 +107,29 @@ const listCommand: CommandModule = { ); const mergedSettings = { ...userSettings, ...workspaceSettings }; - console.log(`Settings for "${name}":`); + console.log(t('Settings for "{{name}}":', { name })); for (const setting of extension.settings) { const value = mergedSettings[setting.envVar]; let displayValue: string; let scopeInfo = ''; if (workspaceSettings[setting.envVar] !== undefined) { - scopeInfo = ' (workspace)'; + scopeInfo = ' ' + t('(workspace)'); } else if (userSettings[setting.envVar] !== undefined) { - scopeInfo = ' (user)'; + scopeInfo = ' ' + t('(user)'); } if (value === undefined) { - displayValue = '[not set]'; + displayValue = t('[not set]'); } else if (setting.sensitive) { - displayValue = '[value stored in keychain]'; + displayValue = t('[value stored in keychain]'); } else { displayValue = value; } console.log(` - ${setting.name} (${setting.envVar})`); - console.log(` Description: ${setting.description}`); - console.log(` Value: ${displayValue}${scopeInfo}`); + console.log(` ${t('Description:')} ${setting.description}`); + console.log(` ${t('Value:')} ${displayValue}${scopeInfo}`); } }, }; @@ -134,12 +137,12 @@ const listCommand: CommandModule = { // --- SETTINGS COMMAND --- export const settingsCommand: CommandModule = { command: 'settings ', - describe: 'Manage extension settings.', + describe: t('Manage extension settings.'), builder: (yargs) => yargs .command(setCommand) .command(listCommand) - .demandCommand(1, 'You need to specify a command (set or list).') + .demandCommand(1, t('You need to specify a command (set or list).')) .version(false), handler: () => { // This handler is not called when a subcommand is provided. diff --git a/packages/cli/src/commands/extensions/uninstall.ts b/packages/cli/src/commands/extensions/uninstall.ts index 9d40f9d55de..980472a680c 100644 --- a/packages/cli/src/commands/extensions/uninstall.ts +++ b/packages/cli/src/commands/extensions/uninstall.ts @@ -13,6 +13,7 @@ import { } from './consent.js'; import { isWorkspaceTrusted } from '../../config/trustedFolders.js'; import { loadSettings } from '../../config/settings.js'; +import { t } from '../../i18n/index.js'; interface UninstallArgs { name: string; // can be extension name or source URL. @@ -33,7 +34,9 @@ export async function handleUninstall(args: UninstallArgs) { }); await extensionManager.refreshCache(); await extensionManager.uninstallExtension(args.name, false); - console.log(`Extension "${args.name}" successfully uninstalled.`); + console.log( + t('Extension "{{name}}" successfully uninstalled.', { name: args.name }), + ); } catch (error) { console.error(getErrorMessage(error)); process.exit(1); @@ -42,17 +45,19 @@ export async function handleUninstall(args: UninstallArgs) { export const uninstallCommand: CommandModule = { command: 'uninstall ', - describe: 'Uninstalls an extension.', + describe: t('Uninstalls an extension.'), builder: (yargs) => yargs .positional('name', { - describe: 'The name or source path of the extension to uninstall.', + describe: t('The name or source path of the extension to uninstall.'), type: 'string', }) .check((argv) => { if (!argv.name) { throw new Error( - 'Please include the name of the extension to uninstall as a positional argument.', + t( + 'Please include the name of the extension to uninstall as a positional argument.', + ), ); } return true; diff --git a/packages/cli/src/commands/extensions/update.ts b/packages/cli/src/commands/extensions/update.ts index d254cac5ad1..9325a25f19a 100644 --- a/packages/cli/src/commands/extensions/update.ts +++ b/packages/cli/src/commands/extensions/update.ts @@ -12,6 +12,7 @@ import { type ExtensionUpdateInfo, } from '@qwen-code/qwen-code-core'; import { getExtensionManager } from './utils.js'; +import { t } from '../../i18n/index.js'; interface UpdateArgs { name?: string; @@ -19,7 +20,14 @@ interface UpdateArgs { } const updateOutput = (info: ExtensionUpdateInfo) => - `Extension "${info.name}" successfully updated: ${info.originalVersion} → ${info.updatedVersion}.`; + t( + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.', + { + name: info.name, + oldVersion: info.originalVersion, + newVersion: info.updatedVersion, + }, + ); export async function handleUpdate(args: UpdateArgs) { const extensionManager = await getExtensionManager(); @@ -31,12 +39,15 @@ export async function handleUpdate(args: UpdateArgs) { (extension) => extension.name === args.name, ); if (!extension) { - console.log(`Extension "${args.name}" not found.`); + console.log(t('Extension "{{name}}" not found.', { name: args.name })); return; } if (!extension.installMetadata) { console.log( - `Unable to install extension "${args.name}" due to missing install metadata`, + t( + 'Unable to install extension "{{name}}" due to missing install metadata', + { name: args.name }, + ), ); return; } @@ -45,7 +56,9 @@ export async function handleUpdate(args: UpdateArgs) { extensionManager, ); if (updateState !== ExtensionUpdateState.UPDATE_AVAILABLE) { - console.log(`Extension "${args.name}" is already up to date.`); + console.log( + t('Extension "{{name}}" is already up to date.', { name: args.name }), + ); return; } // TODO(chrstnb): we should list extensions if the requested extension is not installed. @@ -59,10 +72,19 @@ export async function handleUpdate(args: UpdateArgs) { updatedExtensionInfo.updatedVersion ) { console.log( - `Extension "${args.name}" successfully updated: ${updatedExtensionInfo.originalVersion} → ${updatedExtensionInfo.updatedVersion}.`, + t( + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.', + { + name: args.name, + oldVersion: updatedExtensionInfo.originalVersion, + newVersion: updatedExtensionInfo.updatedVersion, + }, + ), ); } else { - console.log(`Extension "${args.name}" is already up to date.`); + console.log( + t('Extension "{{name}}" is already up to date.', { name: args.name }), + ); } } catch (error) { console.error(getErrorMessage(error)); @@ -87,7 +109,7 @@ export async function handleUpdate(args: UpdateArgs) { (info) => info.originalVersion !== info.updatedVersion, ); if (updateInfos.length === 0) { - console.log('No extensions to update.'); + console.log(t('No extensions to update.')); return; } console.log(updateInfos.map((info) => updateOutput(info)).join('\n')); @@ -99,22 +121,25 @@ export async function handleUpdate(args: UpdateArgs) { export const updateCommand: CommandModule = { command: 'update [] [--all]', - describe: + describe: t( 'Updates all extensions or a named extension to the latest version.', + ), builder: (yargs) => yargs .positional('name', { - describe: 'The name of the extension to update.', + describe: t('The name of the extension to update.'), type: 'string', }) .option('all', { - describe: 'Update all extensions.', + describe: t('Update all extensions.'), type: 'boolean', }) .conflicts('name', 'all') .check((argv) => { if (!argv.all && !argv.name) { - throw new Error('Either an extension name or --all must be provided'); + throw new Error( + t('Either an extension name or --all must be provided'), + ); } return true; }), diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index ba36414c65a..b96ddda6168 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -412,6 +412,91 @@ export default { 'Diese Erweiterung wird folgende Unteragenten installieren:', 'Installation cancelled for "{{name}}".': 'Installation von "{{name}}" abgebrochen.', + '--ref and --auto-update are not applicable for marketplace extensions.': + '--ref und --auto-update sind nicht anwendbar für Marketplace-Erweiterungen.', + 'Extension "{{name}}" installed successfully and enabled.': + 'Erweiterung "{{name}}" erfolgreich installiert und aktiviert.', + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).': + 'Installiert eine Erweiterung von einer Git-Repository-URL, einem lokalen Pfad oder dem Claude-Marketplace (marketplace-url:plugin-name).', + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.': + 'Die GitHub-URL, der lokale Pfad oder die Marketplace-Quelle (marketplace-url:plugin-name) der zu installierenden Erweiterung.', + 'The git ref to install from.': 'Die Git-Referenz für die Installation.', + 'Enable auto-update for this extension.': + 'Automatisches Update für diese Erweiterung aktivieren.', + 'Enable pre-release versions for this extension.': + 'Pre-Release-Versionen für diese Erweiterung aktivieren.', + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.': + 'Sicherheitsrisiken der Erweiterungsinstallation bestätigen und Bestätigungsaufforderung überspringen.', + 'The source argument must be provided.': + 'Das Quellargument muss angegeben werden.', + 'Extension "{{name}}" successfully uninstalled.': + 'Erweiterung "{{name}}" erfolgreich deinstalliert.', + 'Uninstalls an extension.': 'Deinstalliert eine Erweiterung.', + 'The name or source path of the extension to uninstall.': + 'Der Name oder Quellpfad der zu deinstallierenden Erweiterung.', + 'Please include the name of the extension to uninstall as a positional argument.': + 'Bitte geben Sie den Namen der zu deinstallierenden Erweiterung als Positionsargument an.', + 'Enables an extension.': 'Aktiviert eine Erweiterung.', + 'The name of the extension to enable.': + 'Der Name der zu aktivierenden Erweiterung.', + 'The scope to enable the extenison in. If not set, will be enabled in all scopes.': + 'Der Bereich, in dem die Erweiterung aktiviert werden soll. Wenn nicht gesetzt, wird sie in allen Bereichen aktiviert.', + 'Extension "{{name}}" successfully enabled for scope "{{scope}}".': + 'Erweiterung "{{name}}" erfolgreich für Bereich "{{scope}}" aktiviert.', + 'Extension "{{name}}" successfully enabled in all scopes.': + 'Erweiterung "{{name}}" erfolgreich in allen Bereichen aktiviert.', + 'Invalid scope: {{scope}}. Please use one of {{scopes}}.': + 'Ungültiger Bereich: {{scope}}. Bitte verwenden Sie einen von {{scopes}}.', + 'Disables an extension.': 'Deaktiviert eine Erweiterung.', + 'The name of the extension to disable.': + 'Der Name der zu deaktivierenden Erweiterung.', + 'The scope to disable the extenison in.': + 'Der Bereich, in dem die Erweiterung deaktiviert werden soll.', + 'Extension "{{name}}" successfully disabled for scope "{{scope}}".': + 'Erweiterung "{{name}}" erfolgreich für Bereich "{{scope}}" deaktiviert.', + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.': + 'Erweiterung "{{name}}" erfolgreich aktualisiert: {{oldVersion}} → {{newVersion}}.', + 'Unable to install extension "{{name}}" due to missing install metadata': + 'Erweiterung "{{name}}" kann aufgrund fehlender Installationsmetadaten nicht installiert werden', + 'Extension "{{name}}" is already up to date.': + 'Erweiterung "{{name}}" ist bereits aktuell.', + 'Updates all extensions or a named extension to the latest version.': + 'Aktualisiert alle Erweiterungen oder eine benannte Erweiterung auf die neueste Version.', + 'The name of the extension to update.': + 'Der Name der zu aktualisierenden Erweiterung.', + 'Update all extensions.': 'Alle Erweiterungen aktualisieren.', + 'Either an extension name or --all must be provided': + 'Entweder ein Erweiterungsname oder --all muss angegeben werden', + 'Lists installed extensions.': 'Listet installierte Erweiterungen auf.', + 'Link extension failed to install.': + 'Verknüpfte Erweiterung konnte nicht installiert werden.', + 'Extension "{{name}}" linked successfully and enabled.': + 'Erweiterung "{{name}}" erfolgreich verknüpft und aktiviert.', + 'Links an extension from a local path. Updates made to the local path will always be reflected.': + 'Verknüpft eine Erweiterung von einem lokalen Pfad. Änderungen am lokalen Pfad werden immer widergespiegelt.', + 'The name of the extension to link.': + 'Der Name der zu verknüpfenden Erweiterung.', + 'Set a specific setting for an extension.': + 'Legt eine bestimmte Einstellung für eine Erweiterung fest.', + 'Name of the extension to configure.': + 'Name der zu konfigurierenden Erweiterung.', + 'The setting to configure (name or env var).': + 'Die zu konfigurierende Einstellung (Name oder Umgebungsvariable).', + 'The scope to set the setting in.': + 'Der Bereich, in dem die Einstellung gesetzt werden soll.', + 'List all settings for an extension.': + 'Listet alle Einstellungen einer Erweiterung auf.', + 'Name of the extension.': 'Name der Erweiterung.', + 'Extension "{{name}}" has no settings to configure.': + 'Erweiterung "{{name}}" hat keine zu konfigurierenden Einstellungen.', + 'Settings for "{{name}}":': 'Einstellungen für "{{name}}":', + '(workspace)': '(Arbeitsbereich)', + '(user)': '(Benutzer)', + '[not set]': '[nicht gesetzt]', + '[value stored in keychain]': '[Wert in Schlüsselbund gespeichert]', + 'Manage extension settings.': 'Erweiterungseinstellungen verwalten.', + 'You need to specify a command (set or list).': + 'Sie müssen einen Befehl angeben (set oder list).', 'manage IDE integration': 'IDE-Integration verwalten', 'check status of IDE integration': 'Status der IDE-Integration prüfen', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 8736a1ae3d4..08c6ed5d0f8 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -406,6 +406,85 @@ export default { 'This extension will install the following subagents:', 'Installation cancelled for "{{name}}".': 'Installation cancelled for "{{name}}".', + '--ref and --auto-update are not applicable for marketplace extensions.': + '--ref and --auto-update are not applicable for marketplace extensions.', + 'Extension "{{name}}" installed successfully and enabled.': + 'Extension "{{name}}" installed successfully and enabled.', + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).': + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).', + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.': + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.', + 'The git ref to install from.': 'The git ref to install from.', + 'Enable auto-update for this extension.': + 'Enable auto-update for this extension.', + 'Enable pre-release versions for this extension.': + 'Enable pre-release versions for this extension.', + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.': + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.', + 'The source argument must be provided.': + 'The source argument must be provided.', + 'Extension "{{name}}" successfully uninstalled.': + 'Extension "{{name}}" successfully uninstalled.', + 'Uninstalls an extension.': 'Uninstalls an extension.', + 'The name or source path of the extension to uninstall.': + 'The name or source path of the extension to uninstall.', + 'Please include the name of the extension to uninstall as a positional argument.': + 'Please include the name of the extension to uninstall as a positional argument.', + 'Enables an extension.': 'Enables an extension.', + 'The name of the extension to enable.': + 'The name of the extension to enable.', + 'The scope to enable the extenison in. If not set, will be enabled in all scopes.': + 'The scope to enable the extenison in. If not set, will be enabled in all scopes.', + 'Extension "{{name}}" successfully enabled for scope "{{scope}}".': + 'Extension "{{name}}" successfully enabled for scope "{{scope}}".', + 'Extension "{{name}}" successfully enabled in all scopes.': + 'Extension "{{name}}" successfully enabled in all scopes.', + 'Invalid scope: {{scope}}. Please use one of {{scopes}}.': + 'Invalid scope: {{scope}}. Please use one of {{scopes}}.', + 'Disables an extension.': 'Disables an extension.', + 'The name of the extension to disable.': + 'The name of the extension to disable.', + 'The scope to disable the extenison in.': + 'The scope to disable the extenison in.', + 'Extension "{{name}}" successfully disabled for scope "{{scope}}".': + 'Extension "{{name}}" successfully disabled for scope "{{scope}}".', + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.': + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.', + 'Unable to install extension "{{name}}" due to missing install metadata': + 'Unable to install extension "{{name}}" due to missing install metadata', + 'Extension "{{name}}" is already up to date.': + 'Extension "{{name}}" is already up to date.', + 'Updates all extensions or a named extension to the latest version.': + 'Updates all extensions or a named extension to the latest version.', + 'Update all extensions.': 'Update all extensions.', + 'Either an extension name or --all must be provided': + 'Either an extension name or --all must be provided', + 'Lists installed extensions.': 'Lists installed extensions.', + 'Link extension failed to install.': 'Link extension failed to install.', + 'Extension "{{name}}" linked successfully and enabled.': + 'Extension "{{name}}" linked successfully and enabled.', + 'Links an extension from a local path. Updates made to the local path will always be reflected.': + 'Links an extension from a local path. Updates made to the local path will always be reflected.', + 'The name of the extension to link.': 'The name of the extension to link.', + 'Set a specific setting for an extension.': + 'Set a specific setting for an extension.', + 'Name of the extension to configure.': 'Name of the extension to configure.', + 'The setting to configure (name or env var).': + 'The setting to configure (name or env var).', + 'The scope to set the setting in.': 'The scope to set the setting in.', + 'List all settings for an extension.': 'List all settings for an extension.', + 'Name of the extension.': 'Name of the extension.', + 'Extension "{{name}}" has no settings to configure.': + 'Extension "{{name}}" has no settings to configure.', + 'Settings for "{{name}}":': 'Settings for "{{name}}":', + '(workspace)': '(workspace)', + '(user)': '(user)', + '[not set]': '[not set]', + '[value stored in keychain]': '[value stored in keychain]', + 'Value:': 'Value:', + 'Manage extension settings.': 'Manage extension settings.', + 'You need to specify a command (set or list).': + 'You need to specify a command (set or list).', 'manage IDE integration': 'manage IDE integration', 'check status of IDE integration': 'check status of IDE integration', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index 596db3b085f..42e2fa2cab4 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -410,6 +410,84 @@ export default { 'This extension will install the following subagents:': 'Это расширение установит следующие подагенты:', 'Installation cancelled for "{{name}}".': 'Установка "{{name}}" отменена.', + '--ref and --auto-update are not applicable for marketplace extensions.': + '--ref и --auto-update неприменимы для расширений из маркетплейса.', + 'Extension "{{name}}" installed successfully and enabled.': + 'Расширение "{{name}}" успешно установлено и включено.', + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).': + 'Устанавливает расширение из URL Git-репозитория, локального пути или маркетплейса Claude (marketplace-url:plugin-name).', + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.': + 'URL GitHub, локальный путь или источник в маркетплейсе (marketplace-url:plugin-name) устанавливаемого расширения.', + 'The git ref to install from.': 'Git-ссылка для установки.', + 'Enable auto-update for this extension.': + 'Включить автообновление для этого расширения.', + 'Enable pre-release versions for this extension.': + 'Включить пре-релизные версии для этого расширения.', + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.': + 'Подтвердить риски безопасности установки расширения и пропустить запрос подтверждения.', + 'The source argument must be provided.': + 'Необходимо указать аргумент источника.', + 'Extension "{{name}}" successfully uninstalled.': + 'Расширение "{{name}}" успешно удалено.', + 'Uninstalls an extension.': 'Удаляет расширение.', + 'The name or source path of the extension to uninstall.': + 'Имя или путь к источнику удаляемого расширения.', + 'Please include the name of the extension to uninstall as a positional argument.': + 'Пожалуйста, укажите имя удаляемого расширения как позиционный аргумент.', + 'Enables an extension.': 'Включает расширение.', + 'The name of the extension to enable.': 'Имя включаемого расширения.', + 'The scope to enable the extenison in. If not set, will be enabled in all scopes.': + 'Область для включения расширения. Если не задана, будет включено во всех областях.', + 'Extension "{{name}}" successfully enabled for scope "{{scope}}".': + 'Расширение "{{name}}" успешно включено для области "{{scope}}".', + 'Extension "{{name}}" successfully enabled in all scopes.': + 'Расширение "{{name}}" успешно включено во всех областях.', + 'Invalid scope: {{scope}}. Please use one of {{scopes}}.': + 'Недопустимая область: {{scope}}. Пожалуйста, используйте одну из {{scopes}}.', + 'Disables an extension.': 'Отключает расширение.', + 'The name of the extension to disable.': 'Имя отключаемого расширения.', + 'The scope to disable the extenison in.': + 'Область для отключения расширения.', + 'Extension "{{name}}" successfully disabled for scope "{{scope}}".': + 'Расширение "{{name}}" успешно отключено для области "{{scope}}".', + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.': + 'Расширение "{{name}}" успешно обновлено: {{oldVersion}} → {{newVersion}}.', + 'Unable to install extension "{{name}}" due to missing install metadata': + 'Невозможно установить расширение "{{name}}" из-за отсутствия метаданных установки', + 'Extension "{{name}}" is already up to date.': + 'Расширение "{{name}}" уже актуально.', + 'Updates all extensions or a named extension to the latest version.': + 'Обновляет все расширения или указанное расширение до последней версии.', + 'The name of the extension to update.': 'Имя обновляемого расширения.', + 'Update all extensions.': 'Обновить все расширения.', + 'Either an extension name or --all must be provided': + 'Необходимо указать имя расширения или --all', + 'Lists installed extensions.': 'Показывает установленные расширения.', + 'Link extension failed to install.': + 'Не удалось установить связанное расширение.', + 'Extension "{{name}}" linked successfully and enabled.': + 'Расширение "{{name}}" успешно связано и включено.', + 'Links an extension from a local path. Updates made to the local path will always be reflected.': + 'Связывает расширение из локального пути. Изменения в локальном пути будут всегда отражаться.', + 'The name of the extension to link.': 'Имя связываемого расширения.', + 'Set a specific setting for an extension.': + 'Установить конкретную настройку для расширения.', + 'Name of the extension to configure.': 'Имя настраиваемого расширения.', + 'The setting to configure (name or env var).': + 'Настройка для конфигурирования (имя или переменная окружения).', + 'The scope to set the setting in.': 'Область для установки настройки.', + 'List all settings for an extension.': 'Показать все настройки расширения.', + 'Name of the extension.': 'Имя расширения.', + 'Extension "{{name}}" has no settings to configure.': + 'Расширение "{{name}}" не имеет настроек для конфигурирования.', + 'Settings for "{{name}}":': 'Настройки для "{{name}}":', + '(workspace)': '(рабочее пространство)', + '(user)': '(пользователь)', + '[not set]': '[не задано]', + '[value stored in keychain]': '[значение хранится в связке ключей]', + 'Manage extension settings.': 'Управление настройками расширений.', + 'You need to specify a command (set or list).': + 'Необходимо указать команду (set или list).', 'manage IDE integration': 'Управление интеграцией с IDE', 'check status of IDE integration': 'Проверить статус интеграции с IDE', 'install required IDE companion for {{ideName}}': diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index f8f3f492480..c33b47ed5bc 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -388,6 +388,78 @@ export default { 'This extension will install the following subagents:': '此扩展将安装以下子代理:', 'Installation cancelled for "{{name}}".': '已取消安装 "{{name}}"。', + '--ref and --auto-update are not applicable for marketplace extensions.': + '--ref 和 --auto-update 不适用于市场扩展。', + 'Extension "{{name}}" installed successfully and enabled.': + '扩展 "{{name}}" 安装成功并已启用。', + 'Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).': + '从 Git 仓库 URL、本地路径或 Claude 市场(marketplace-url:plugin-name)安装扩展。', + 'The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.': + '要安装的扩展的 GitHub URL、本地路径或市场源(marketplace-url:plugin-name)。', + 'The git ref to install from.': '要安装的 Git 引用。', + 'Enable auto-update for this extension.': '为此扩展启用自动更新。', + 'Enable pre-release versions for this extension.': '为此扩展启用预发布版本。', + 'Acknowledge the security risks of installing an extension and skip the confirmation prompt.': + '确认安装扩展的安全风险并跳过确认提示。', + 'The source argument must be provided.': '必须提供来源参数。', + 'Extension "{{name}}" successfully uninstalled.': + '扩展 "{{name}}" 卸载成功。', + 'Uninstalls an extension.': '卸载扩展。', + 'The name or source path of the extension to uninstall.': + '要卸载的扩展的名称或源路径。', + 'Please include the name of the extension to uninstall as a positional argument.': + '请将要卸载的扩展名称作为位置参数。', + 'Enables an extension.': '启用扩展。', + 'The name of the extension to enable.': '要启用的扩展名称。', + 'The scope to enable the extenison in. If not set, will be enabled in all scopes.': + '启用扩展的作用域。如果未设置,将在所有作用域中启用。', + 'Extension "{{name}}" successfully enabled for scope "{{scope}}".': + '扩展 "{{name}}" 已在作用域 "{{scope}}" 中启用。', + 'Extension "{{name}}" successfully enabled in all scopes.': + '扩展 "{{name}}" 已在所有作用域中启用。', + 'Invalid scope: {{scope}}. Please use one of {{scopes}}.': + '无效的作用域:{{scope}}。请使用 {{scopes}} 之一。', + 'Disables an extension.': '禁用扩展。', + 'The name of the extension to disable.': '要禁用的扩展名称。', + 'The scope to disable the extenison in.': '禁用扩展的作用域。', + 'Extension "{{name}}" successfully disabled for scope "{{scope}}".': + '扩展 "{{name}}" 已在作用域 "{{scope}}" 中禁用。', + 'Extension "{{name}}" successfully updated: {{oldVersion}} → {{newVersion}}.': + '扩展 "{{name}}" 更新成功:{{oldVersion}} → {{newVersion}}。', + 'Unable to install extension "{{name}}" due to missing install metadata': + '由于缺少安装元数据,无法安装扩展 "{{name}}"', + 'Extension "{{name}}" is already up to date.': + '扩展 "{{name}}" 已是最新版本。', + 'Updates all extensions or a named extension to the latest version.': + '将所有扩展或指定扩展更新到最新版本。', + 'The name of the extension to update.': '要更新的扩展名称。', + 'Update all extensions.': '更新所有扩展。', + 'Either an extension name or --all must be provided': + '必须提供扩展名称或 --all', + 'Lists installed extensions.': '列出已安装的扩展。', + 'Link extension failed to install.': '链接扩展安装失败。', + 'Extension "{{name}}" linked successfully and enabled.': + '扩展 "{{name}}" 链接成功并已启用。', + 'Links an extension from a local path. Updates made to the local path will always be reflected.': + '从本地路径链接扩展。对本地路径的更新将始终反映。', + 'The name of the extension to link.': '要链接的扩展名称。', + 'Set a specific setting for an extension.': '为扩展设置特定配置。', + 'Name of the extension to configure.': '要配置的扩展名称。', + 'The setting to configure (name or env var).': + '要配置的设置(名称或环境变量)。', + 'The scope to set the setting in.': '设置配置的作用域。', + 'List all settings for an extension.': '列出扩展的所有设置。', + 'Name of the extension.': '扩展名称。', + 'Extension "{{name}}" has no settings to configure.': + '扩展 "{{name}}" 没有可配置的设置。', + 'Settings for "{{name}}":': '"{{name}}" 的设置:', + '(workspace)': '(工作区)', + '(user)': '(用户)', + '[not set]': '[未设置]', + '[value stored in keychain]': '[值存储在钥匙串中]', + 'Manage extension settings.': '管理扩展设置。', + 'You need to specify a command (set or list).': + '您需要指定命令(set 或 list)。', 'manage IDE integration': '管理 IDE 集成', 'check status of IDE integration': '检查 IDE 集成状态', 'install required IDE companion for {{ideName}}': From f467054372ef7a65af0661ce226a833294577244 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Tue, 20 Jan 2026 17:50:18 +0800 Subject: [PATCH 26/30] feat: remove excludeTools in extension --- docs/developers/extensions/extension.md | 2 - .../src/commands/extensions/consent.test.ts | 30 ---- .../cli/src/commands/extensions/consent.ts | 7 - .../exclude-tools/qwen-extension.json | 5 - packages/core/src/config/config.ts | 9 +- .../src/extension/extensionManager.test.ts | 135 +----------------- .../core/src/extension/extensionManager.ts | 27 +--- .../src/extension/gemini-converter.test.ts | 2 - .../core/src/extension/gemini-converter.ts | 2 - 9 files changed, 9 insertions(+), 210 deletions(-) delete mode 100644 packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json diff --git a/docs/developers/extensions/extension.md b/docs/developers/extensions/extension.md index 2ad06d06d9d..ae29ef1aa37 100644 --- a/docs/developers/extensions/extension.md +++ b/docs/developers/extensions/extension.md @@ -112,7 +112,6 @@ The `qwen-extension.json` file contains the configuration for the extension. The } }, "contextFileName": "QWEN.md", - "excludeTools": ["run_shell_command"], "commands": "commands", "skills": "skills", "agents": "agents", @@ -132,7 +131,6 @@ The `qwen-extension.json` file contains the configuration for the extension. The - `mcpServers`: A map of MCP servers to configure. The key is the name of the server, and the value is the server configuration. These servers will be loaded on startup just like MCP servers configured in a [`settings.json` file](./cli/configuration.md). If both an extension and a `settings.json` file configure an MCP server with the same name, the server defined in the `settings.json` file takes precedence. - Note that all MCP server configuration options are supported except for `trust`. - `contextFileName`: The name of the file that contains the context for the extension. This will be used to load the context from the extension directory. If this property is not used but a `QWEN.md` file is present in your extension directory, then that file will be loaded. -- `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. Note that this differs from the MCP server `excludeTools` functionality, which can be listed in the MCP server config. **Important:** Tools specified in `excludeTools` will be disabled for the entire conversation context and will affect all subsequent queries in the current session. - `commands`: The directory containing custom commands (default: `commands`). Commands are `.md` files that define prompts. - `skills`: The directory containing custom skills (default: `skills`). Skills are discovered automatically and become available via the `/skills` command. - `agents`: The directory containing custom subagents (default: `agents`). Subagents are `.yaml` or `.md` files that define specialized AI assistants. diff --git a/packages/cli/src/commands/extensions/consent.test.ts b/packages/cli/src/commands/extensions/consent.test.ts index 1b3b2801387..3b9808bc476 100644 --- a/packages/cli/src/commands/extensions/consent.test.ts +++ b/packages/cli/src/commands/extensions/consent.test.ts @@ -118,21 +118,6 @@ describe('extensionConsentString', () => { expect(result).toContain('FILE1.md, FILE2.md'); }); - it('should include excluded tools when present', () => { - const config: ExtensionConfig = { - name: 'test-extension', - version: '1.0.0', - excludeTools: ['tool1', 'tool2'], - }; - - const result = extensionConsentString(config); - - expect(result).toContain( - 'This extension will exclude the following core tools', - ); - expect(result).toContain('tool1, tool2'); - }); - it('should include skills when present', () => { const config: ExtensionConfig = { name: 'test-extension', @@ -243,21 +228,6 @@ describe('requestConsentOrFail', () => { expect(mockRequestConsent).not.toHaveBeenCalled(); }); - it('should request consent when consent string changes', async () => { - mockRequestConsent.mockResolvedValueOnce(true); - - await requestConsentOrFail(mockRequestConsent, { - extensionConfig: { - name: 'test-extension', - version: '1.0.0', - excludeTools: ['tool1'], - }, - previousExtensionConfig: { name: 'test-extension', version: '1.0.0' }, - }); - - expect(mockRequestConsent).toHaveBeenCalled(); - }); - it('should request consent when commands change', async () => { mockRequestConsent.mockResolvedValueOnce(true); diff --git a/packages/cli/src/commands/extensions/consent.ts b/packages/cli/src/commands/extensions/consent.ts index 65886e64644..c3da6a282fa 100644 --- a/packages/cli/src/commands/extensions/consent.ts +++ b/packages/cli/src/commands/extensions/consent.ts @@ -145,13 +145,6 @@ export function extensionConsentString( ), ); } - if (extensionConfig.excludeTools) { - output.push( - t('This extension will exclude the following core tools: {{tools}}', { - tools: extensionConfig.excludeTools.join(', '), - }), - ); - } if (skills.length > 0) { output.push(t('This extension will install the following skills:')); for (const skill of skills) { diff --git a/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json b/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json deleted file mode 100644 index 584b6abc050..00000000000 --- a/packages/cli/src/commands/extensions/examples/exclude-tools/qwen-extension.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "exclude-tools-example", - "version": "1.0.0", - "excludeTools": ["Shell(rm -rf)"] -} diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 433dede6d8f..d9c0d2c2f13 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -1044,14 +1044,7 @@ export class Config { } getExcludeTools(): string[] | undefined { - const allExcludeTools = new Set(this.excludeTools || []); - const extensions = this.getActiveExtensions(); - for (const extension of extensions) { - for (const tool of extension.config.excludeTools || []) { - allExcludeTools.add(tool); - } - } - return [...allExcludeTools]; + return this.excludeTools; } getToolDiscoveryCommand(): string | undefined { diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index cfa6feb9732..a155f08924e 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -607,132 +607,8 @@ describe('extension tests', () => { describe('refreshTools and refreshMemory', () => { it('refreshTools should return early if config is not set', async () => { const manager = createExtensionManager(); - const extension = { - name: 'test-ext', - config: { name: 'test-ext', version: '1.0.0' }, - excludeTools: ['tool1'], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - // Should not throw when config is undefined - await expect(manager.refreshTools(extension)).resolves.not.toThrow(); - }); - - it('refreshTools should call setTools when extension has excludeTools', async () => { - const mockSetTools = vi.fn().mockResolvedValue(undefined); - const mockRefreshCache = vi.fn(); - const mockRestartMcpServers = vi.fn(); - const mockRefreshHierarchicalMemory = vi.fn(); - - const mockConfig = { - getGeminiClient: () => ({ - isInitialized: () => true, - setTools: mockSetTools, - }), - getToolRegistry: () => ({ - restartMcpServers: mockRestartMcpServers, - }), - getSkillManager: () => ({ - refreshCache: mockRefreshCache, - }), - getSubagentManager: () => ({ - refreshCache: mockRefreshCache, - }), - refreshHierarchicalMemory: mockRefreshHierarchicalMemory, - }; - - const manager = createExtensionManager(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (manager as any).config = mockConfig; - - const extension = { - name: 'test-ext', - config: { name: 'test-ext', version: '1.0.0' }, - excludeTools: ['tool1', 'tool2'], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - - await manager.refreshTools(extension); - - expect(mockSetTools).toHaveBeenCalledOnce(); - }); - - it('refreshTools should not call setTools when extension has no excludeTools', async () => { - const mockSetTools = vi.fn().mockResolvedValue(undefined); - const mockRefreshCache = vi.fn(); - const mockRestartMcpServers = vi.fn(); - const mockRefreshHierarchicalMemory = vi.fn(); - - const mockConfig = { - getGeminiClient: () => ({ - isInitialized: () => true, - setTools: mockSetTools, - }), - getToolRegistry: () => ({ - restartMcpServers: mockRestartMcpServers, - }), - getSkillManager: () => ({ - refreshCache: mockRefreshCache, - }), - getSubagentManager: () => ({ - refreshCache: mockRefreshCache, - }), - refreshHierarchicalMemory: mockRefreshHierarchicalMemory, - }; - - const manager = createExtensionManager(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (manager as any).config = mockConfig; - - const extension = { - name: 'test-ext', - config: { name: 'test-ext', version: '1.0.0' }, - excludeTools: [], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - - await manager.refreshTools(extension); - - expect(mockSetTools).not.toHaveBeenCalled(); - }); - - it('refreshTools should not call setTools when geminiClient is not initialized', async () => { - const mockSetTools = vi.fn().mockResolvedValue(undefined); - const mockRefreshCache = vi.fn(); - const mockRestartMcpServers = vi.fn(); - const mockRefreshHierarchicalMemory = vi.fn(); - - const mockConfig = { - getGeminiClient: () => ({ - isInitialized: () => false, - setTools: mockSetTools, - }), - getToolRegistry: () => ({ - restartMcpServers: mockRestartMcpServers, - }), - getSkillManager: () => ({ - refreshCache: mockRefreshCache, - }), - getSubagentManager: () => ({ - refreshCache: mockRefreshCache, - }), - refreshHierarchicalMemory: mockRefreshHierarchicalMemory, - }; - - const manager = createExtensionManager(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (manager as any).config = mockConfig; - - const extension = { - name: 'test-ext', - config: { name: 'test-ext', version: '1.0.0' }, - excludeTools: ['tool1'], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - - await manager.refreshTools(extension); - - expect(mockSetTools).not.toHaveBeenCalled(); + await expect(manager.refreshTools()).resolves.not.toThrow(); }); it('refreshTools should always call refreshMemory', async () => { @@ -761,14 +637,7 @@ describe('extension tests', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any (manager as any).config = mockConfig; - const extension = { - name: 'test-ext', - config: { name: 'test-ext', version: '1.0.0' }, - excludeTools: [], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - - await manager.refreshTools(extension); + await manager.refreshTools(); // refreshMemory should be called which includes these expect(mockRestartMcpServers).toHaveBeenCalledOnce(); diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 93a4d357706..7c6ed12bf81 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -90,7 +90,6 @@ export interface Extension { mcpServers?: Record; contextFiles: string[]; - excludeTools?: string[]; settings?: ExtensionSetting[]; resolvedSettings?: ResolvedExtensionSetting[]; commands?: string[]; @@ -103,7 +102,6 @@ export interface ExtensionConfig { version: string; mcpServers?: Record; contextFileName?: string | string[]; - excludeTools?: string[]; commands?: string | string[]; skills?: string | string[]; agents?: string | string[]; @@ -384,7 +382,7 @@ export class ExtensionManager { const config = getTelemetryConfig(currentDir, this.telemetrySettings); logExtensionEnable(config, new ExtensionEnableEvent(name, scope)); extension.isActive = true; - await this.refreshTools(extension); + await this.refreshTools(); } /** @@ -414,7 +412,7 @@ export class ExtensionManager { this.disableByPath(name, true, scopePath); logExtensionDisable(config, new ExtensionDisableEvent(name, scope)); extension.isActive = false; - await this.refreshTools(extension); + await this.refreshTools(); } /** @@ -597,7 +595,6 @@ export class ExtensionManager { isActive: this.isEnabled(config.name, this.workspaceDir), config, settings: config.settings, - excludeTools: config.excludeTools, contextFiles: [], }; @@ -928,7 +925,7 @@ export class ExtensionManager { 'success', ), ); - this.refreshTools(extension); + this.refreshTools(); } else { logExtensionInstallEvent( telemetryConfig, @@ -1041,7 +1038,7 @@ export class ExtensionManager { if (isUpdate) return; this.removeEnablementConfig(extension.name); - this.refreshTools(extension); + this.refreshTools(); logExtensionUninstall( telemetryConfig, @@ -1089,12 +1086,6 @@ export class ExtensionManager { output += `\n ${key}`; }); } - if (extension.config.excludeTools) { - output += `\n Excluded tools:`; - extension.config.excludeTools.forEach((tool) => { - output += `\n ${tool}`; - }); - } return output; } @@ -1234,7 +1225,6 @@ export class ExtensionManager { async refreshMemory(): Promise { if (!this.config) return; // refresh mcp servers - // FIXME: restart all mcp servers, can be optimized by only restarting changed ones and move to 'refreshTools' this.config.getToolRegistry().restartMcpServers(); // refresh skills this.config.getSkillManager()?.refreshCache(); @@ -1244,14 +1234,9 @@ export class ExtensionManager { this.config.refreshHierarchicalMemory(); } - async refreshTools(extension: Extension): Promise { + async refreshTools(): Promise { if (!this.config) return; - if (extension.excludeTools && extension.excludeTools.length > 0) { - const geminiClient = this.config?.getGeminiClient(); - if (geminiClient?.isInitialized()) { - await geminiClient.setTools(); - } - } + // FIXME: restart all mcp servers now, this can be optimized by only restarting changed ones at here this.refreshMemory(); } } diff --git a/packages/core/src/extension/gemini-converter.test.ts b/packages/core/src/extension/gemini-converter.test.ts index b53b2ccaa50..b65556b3137 100644 --- a/packages/core/src/extension/gemini-converter.test.ts +++ b/packages/core/src/extension/gemini-converter.test.ts @@ -58,7 +58,6 @@ describe('convertGeminiToQwenConfig', () => { version: '2.0.0', mcpServers: { server1: {} }, contextFileName: 'context.txt', - excludeTools: ['tool1', 'tool2'], settings: [ { name: 'Setting1', envVar: 'VAR1', description: 'Test setting' }, ], @@ -72,7 +71,6 @@ describe('convertGeminiToQwenConfig', () => { expect(result.version).toBe('2.0.0'); expect(result.mcpServers).toEqual({ server1: {} }); expect(result.contextFileName).toBe('context.txt'); - expect(result.excludeTools).toEqual(['tool1', 'tool2']); expect(result.settings).toHaveLength(1); expect(result.settings?.[0].name).toBe('Setting1'); }); diff --git a/packages/core/src/extension/gemini-converter.ts b/packages/core/src/extension/gemini-converter.ts index fa5ad499e1c..5c0da4dd063 100644 --- a/packages/core/src/extension/gemini-converter.ts +++ b/packages/core/src/extension/gemini-converter.ts @@ -21,7 +21,6 @@ export interface GeminiExtensionConfig { version: string; mcpServers?: Record; contextFileName?: string | string[]; - excludeTools?: string[]; settings?: ExtensionSetting[]; } @@ -51,7 +50,6 @@ export function convertGeminiToQwenConfig( version: geminiConfig.version, mcpServers: geminiConfig.mcpServers as ExtensionConfig['mcpServers'], contextFileName: geminiConfig.contextFileName, - excludeTools: geminiConfig.excludeTools, settings, }; } From 1e41965a7eb91d3e3bf5c8359555d84a68b77065 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 21 Jan 2026 11:29:48 +0800 Subject: [PATCH 27/30] fix settings in interactive mode --- packages/cli/src/i18n/locales/de.js | 8 + packages/cli/src/i18n/locales/en.js | 8 + packages/cli/src/i18n/locales/ru.js | 8 + packages/cli/src/i18n/locales/zh.js | 7 + packages/cli/src/ui/AppContainer.tsx | 28 ++- .../cli/src/ui/components/DialogManager.tsx | 16 ++ .../ui/components/SettingInputPrompt.test.tsx | 133 ++++++++++++ .../src/ui/components/SettingInputPrompt.tsx | 157 ++++++++++++++ .../cli/src/ui/contexts/UIStateContext.tsx | 2 + .../src/ui/hooks/useExtensionUpdates.test.ts | 204 +++++++++++++++++- .../cli/src/ui/hooks/useExtensionUpdates.ts | 74 ++++++- packages/cli/src/ui/types.ts | 8 + .../core/src/extension/extensionManager.ts | 24 ++- 13 files changed, 668 insertions(+), 9 deletions(-) create mode 100644 packages/cli/src/ui/components/SettingInputPrompt.test.tsx create mode 100644 packages/cli/src/ui/components/SettingInputPrompt.tsx diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index b96ddda6168..c19f89c7998 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -1285,4 +1285,12 @@ export default { 'Haben Sie versucht, es aus- und wieder einzuschalten? (Den Ladebildschirm, nicht mich.)', 'Zusätzliche Pylonen werden gebaut...', ], + + // ============================================================================ + // Extension Settings Input + // ============================================================================ + 'Enter value...': 'Wert eingeben...', + 'Enter sensitive value...': 'Sensiblen Wert eingeben...', + 'Press Enter to submit, Escape to cancel': + 'Enter zum Absenden, Escape zum Abbrechen drücken', }; diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 08c6ed5d0f8..b08d9fbdfc9 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -1249,4 +1249,12 @@ export default { 'Have you tried turning it off and on again? (The loading screen, not me.)', 'Constructing additional pylons...', ], + + // ============================================================================ + // Extension Settings Input + // ============================================================================ + 'Enter value...': 'Enter value...', + 'Enter sensitive value...': 'Enter sensitive value...', + 'Press Enter to submit, Escape to cancel': + 'Press Enter to submit, Escape to cancel', }; diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index 42e2fa2cab4..b5235362cb3 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -1268,4 +1268,12 @@ export default { 'Пробовали выключить и включить снова? (Экран загрузки, не меня!)', 'Нужно построить больше пилонов...', ], + + // ============================================================================ + // Extension Settings Input + // ============================================================================ + 'Enter value...': 'Введите значение...', + 'Enter sensitive value...': 'Введите секретное значение...', + 'Press Enter to submit, Escape to cancel': + 'Нажмите Enter для отправки, Escape для отмены', }; diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index c33b47ed5bc..c6b3b32310a 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -1092,4 +1092,11 @@ export default { '哪怕只有 0.1% 的进度,也是在向目标靠近...', '加载的是字节,承载的是对技术的热爱...', ], + + // ============================================================================ + // Extension Settings Input + // ============================================================================ + 'Enter value...': '请输入值...', + 'Enter sensitive value...': '请输入敏感值...', + 'Press Enter to submit, Escape to cancel': '按 Enter 提交,Escape 取消', }; diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 0a2a4a6b84e..d1a24d97fc5 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -92,6 +92,7 @@ import { useGitBranchName } from './hooks/useGitBranchName.js'; import { useExtensionUpdates, useConfirmUpdateRequests, + useSettingInputRequests, } from './hooks/useExtensionUpdates.js'; import { ShellFocusContext } from './contexts/ShellFocusContext.js'; import { t } from '../i18n/index.js'; @@ -169,14 +170,34 @@ export const AppContainer = (props: AppContainerProps) => { const extensionManager = config.getExtensionManager(); + const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = + useConfirmUpdateRequests(); + + const { addSettingInputRequest, settingInputRequests } = + useSettingInputRequests(); + extensionManager.setRequestConsent( requestConsentOrFail.bind(null, (description) => requestConsentInteractive(description, addConfirmUpdateExtensionRequest), ), ); - const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = - useConfirmUpdateRequests(); + extensionManager.setRequestSetting( + (setting) => + new Promise((resolve, reject) => { + addSettingInputRequest({ + settingName: setting.name, + settingDescription: setting.description, + sensitive: setting.sensitive ?? false, + onSubmit: (value) => { + resolve(value); + }, + onCancel: () => { + reject(new Error('Setting input cancelled')); + }, + }); + }), + ); const { extensionsUpdateState, @@ -1284,6 +1305,7 @@ export const AppContainer = (props: AppContainerProps) => { !!shellConfirmationRequest || !!confirmationRequest || confirmUpdateExtensionRequests.length > 0 || + settingInputRequests.length > 0 || !!loopDetectionConfirmationRequest || isThemeDialogOpen || isSettingsDialogOpen || @@ -1345,6 +1367,7 @@ export const AppContainer = (props: AppContainerProps) => { shellConfirmationRequest, confirmationRequest, confirmUpdateExtensionRequests, + settingInputRequests, loopDetectionConfirmationRequest, geminiMdFileCount, streamingState, @@ -1436,6 +1459,7 @@ export const AppContainer = (props: AppContainerProps) => { shellConfirmationRequest, confirmationRequest, confirmUpdateExtensionRequests, + settingInputRequests, loopDetectionConfirmationRequest, geminiMdFileCount, streamingState, diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index 48a622e7079..675d1799565 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -11,6 +11,7 @@ import { LoopDetectionConfirmation } from './LoopDetectionConfirmation.js'; import { FolderTrustDialog } from './FolderTrustDialog.js'; import { ShellConfirmationDialog } from './ShellConfirmationDialog.js'; import { ConsentPrompt } from './ConsentPrompt.js'; +import { SettingInputPrompt } from './SettingInputPrompt.js'; import { ThemeDialog } from './ThemeDialog.js'; import { SettingsDialog } from './SettingsDialog.js'; import { QwenOAuthProgress } from './QwenOAuthProgress.js'; @@ -131,6 +132,21 @@ export const DialogManager = ({ /> ); } + if (uiState.settingInputRequests.length > 0) { + const request = uiState.settingInputRequests[0]; + // Use settingName as key to force re-mount when switching between different settings + return ( + + ); + } if (uiState.isThemeDialogOpen) { return ( diff --git a/packages/cli/src/ui/components/SettingInputPrompt.test.tsx b/packages/cli/src/ui/components/SettingInputPrompt.test.tsx new file mode 100644 index 00000000000..ff2755fb99f --- /dev/null +++ b/packages/cli/src/ui/components/SettingInputPrompt.test.tsx @@ -0,0 +1,133 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render } from 'ink-testing-library'; +import { SettingInputPrompt } from './SettingInputPrompt.js'; +import { TextInput } from './shared/TextInput.js'; + +vi.mock('./shared/TextInput.js', () => ({ + TextInput: vi.fn(() => null), +})); + +vi.mock('../hooks/useKeypress.js', () => ({ + useKeypress: vi.fn(), +})); + +const MockedTextInput = vi.mocked(TextInput); + +describe('SettingInputPrompt', () => { + const onSubmit = vi.fn(); + const onCancel = vi.fn(); + const terminalWidth = 80; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('renders setting name and description', () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('API_KEY'); + expect(lastFrame()).toContain('Enter your API key'); + }); + + it('renders TextInput for non-sensitive values', () => { + render( + , + ); + + expect(MockedTextInput).toHaveBeenCalled(); + }); + + it('does not render TextInput for sensitive values (uses PasswordInput)', () => { + MockedTextInput.mockClear(); + render( + , + ); + + // TextInput should not be called for sensitive input + expect(MockedTextInput).not.toHaveBeenCalled(); + }); + + it('shows masked input placeholder for sensitive mode', () => { + const { lastFrame } = render( + , + ); + + // Should show the sensitive placeholder hint + expect(lastFrame()).toContain('PASSWORD'); + expect(lastFrame()).toContain('Enter your password'); + }); + + it('displays help text for submit and cancel', () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Enter'); + expect(lastFrame()).toContain('Escape'); + }); + + it('passes correct props to TextInput for non-sensitive input', () => { + render( + , + ); + + expect(MockedTextInput).toHaveBeenCalledWith( + expect.objectContaining({ + value: '', + isActive: true, + inputWidth: expect.any(Number), + }), + undefined, + ); + }); +}); diff --git a/packages/cli/src/ui/components/SettingInputPrompt.tsx b/packages/cli/src/ui/components/SettingInputPrompt.tsx new file mode 100644 index 00000000000..6f4c432ca5f --- /dev/null +++ b/packages/cli/src/ui/components/SettingInputPrompt.tsx @@ -0,0 +1,157 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { Box, Text } from 'ink'; +import { useState } from 'react'; +import { theme } from '../semantic-colors.js'; +import { TextInput } from './shared/TextInput.js'; +import { t } from '../../i18n/index.js'; +import { useKeypress, type Key } from '../hooks/useKeypress.js'; +import chalk from 'chalk'; + +type SettingInputPromptProps = { + settingName: string; + settingDescription: string; + sensitive: boolean; + onSubmit: (value: string) => void; + onCancel: () => void; + terminalWidth: number; +}; + +/** + * A simple password input component that masks the input with asterisks. + */ +const PasswordInput = ({ + value, + onChange, + onSubmit, + placeholder, +}: { + value: string; + onChange: (value: string) => void; + onSubmit: () => void; + placeholder: string; +}) => { + useKeypress( + (key: Key) => { + // Handle submit + if (key.name === 'return') { + onSubmit(); + return; + } + + // Handle backspace + if (key.name === 'backspace' || key.name === 'delete') { + onChange(value.slice(0, -1)); + return; + } + + // Handle clear (Ctrl+U) + if (key.ctrl && key.name === 'u') { + onChange(''); + return; + } + + // Handle printable characters + if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1) { + const charCode = key.sequence.charCodeAt(0); + // Only accept printable ASCII characters (32-126) + if (charCode >= 32 && charCode <= 126) { + onChange(value + key.sequence); + } + } + }, + { isActive: true }, + ); + + const maskedValue = '*'.repeat(value.length); + const displayValue = maskedValue || ''; + const cursorChar = chalk.inverse(' '); + + return ( + + {'> '} + {value.length === 0 ? ( + + {cursorChar} + {placeholder.slice(1)} + + ) : ( + + {displayValue} + {cursorChar} + + )} + + ); +}; + +export const SettingInputPrompt = (props: SettingInputPromptProps) => { + const { + settingName, + settingDescription, + sensitive, + onSubmit, + onCancel, + terminalWidth, + } = props; + + const [value, setValue] = useState(''); + + useKeypress( + (key) => { + if (key.name === 'escape') { + onCancel(); + } + }, + { isActive: true }, + ); + + const handleSubmit = () => { + if (value.trim()) { + onSubmit(value); + } + }; + + return ( + + + {settingName} + + + {settingDescription} + + + {sensitive ? ( + + ) : ( + + )} + + + {t('Press Enter to submit, Escape to cancel')} + + + ); +}; diff --git a/packages/cli/src/ui/contexts/UIStateContext.tsx b/packages/cli/src/ui/contexts/UIStateContext.tsx index 75e568b4e12..e52dc7fd9ad 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -14,6 +14,7 @@ import type { LoopDetectionConfirmationRequest, HistoryItemWithoutId, StreamingState, + SettingInputRequest, } from '../types.js'; import type { QwenAuthState } from '../hooks/useQwenAuth.js'; import type { CommandContext, SlashCommand } from '../commands/types.js'; @@ -59,6 +60,7 @@ export interface UIState { shellConfirmationRequest: ShellConfirmationRequest | null; confirmationRequest: ConfirmationRequest | null; confirmUpdateExtensionRequests: ConfirmationRequest[]; + settingInputRequests: SettingInputRequest[]; loopDetectionConfirmationRequest: LoopDetectionConfirmationRequest | null; geminiMdFileCount: number; streamingState: StreamingState; diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts index 0475b0badb9..bb297b473ed 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.test.ts @@ -9,7 +9,11 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { useExtensionUpdates } from './useExtensionUpdates.js'; +import { + useExtensionUpdates, + useSettingInputRequests, + useConfirmUpdateRequests, +} from './useExtensionUpdates.js'; import { QWEN_DIR, type ExtensionManager, @@ -17,7 +21,7 @@ import { type ExtensionUpdateInfo, ExtensionUpdateState, } from '@qwen-code/qwen-code-core'; -import { renderHook, waitFor } from '@testing-library/react'; +import { renderHook, waitFor, act } from '@testing-library/react'; import { MessageType } from '../types.js'; vi.mock('os', async (importOriginal) => { @@ -71,6 +75,202 @@ function createMockExtensionManager( } as unknown as ExtensionManager; } +describe('useConfirmUpdateRequests', () => { + it('should add a confirmation request', () => { + const { result } = renderHook(() => useConfirmUpdateRequests()); + + const onConfirm = vi.fn(); + act(() => { + result.current.addConfirmUpdateExtensionRequest({ + prompt: 'Test prompt', + onConfirm, + }); + }); + + expect(result.current.confirmUpdateExtensionRequests).toHaveLength(1); + expect(result.current.confirmUpdateExtensionRequests[0].prompt).toBe( + 'Test prompt', + ); + }); + + it('should remove a confirmation request when confirmed', () => { + const { result } = renderHook(() => useConfirmUpdateRequests()); + + const onConfirm = vi.fn(); + act(() => { + result.current.addConfirmUpdateExtensionRequest({ + prompt: 'Test prompt', + onConfirm, + }); + }); + + expect(result.current.confirmUpdateExtensionRequests).toHaveLength(1); + + // Confirm the request + act(() => { + result.current.confirmUpdateExtensionRequests[0].onConfirm(true); + }); + + expect(result.current.confirmUpdateExtensionRequests).toHaveLength(0); + expect(onConfirm).toHaveBeenCalledWith(true); + }); + + it('should handle multiple confirmation requests', () => { + const { result } = renderHook(() => useConfirmUpdateRequests()); + + const onConfirm1 = vi.fn(); + const onConfirm2 = vi.fn(); + + act(() => { + result.current.addConfirmUpdateExtensionRequest({ + prompt: 'Prompt 1', + onConfirm: onConfirm1, + }); + result.current.addConfirmUpdateExtensionRequest({ + prompt: 'Prompt 2', + onConfirm: onConfirm2, + }); + }); + + expect(result.current.confirmUpdateExtensionRequests).toHaveLength(2); + + // Confirm first request + act(() => { + result.current.confirmUpdateExtensionRequests[0].onConfirm(false); + }); + + expect(result.current.confirmUpdateExtensionRequests).toHaveLength(1); + expect(result.current.confirmUpdateExtensionRequests[0].prompt).toBe( + 'Prompt 2', + ); + expect(onConfirm1).toHaveBeenCalledWith(false); + }); +}); + +describe('useSettingInputRequests', () => { + it('should add a setting input request', () => { + const { result } = renderHook(() => useSettingInputRequests()); + + const onSubmit = vi.fn(); + const onCancel = vi.fn(); + act(() => { + result.current.addSettingInputRequest({ + settingName: 'API_KEY', + settingDescription: 'Enter your API key', + sensitive: true, + onSubmit, + onCancel, + }); + }); + + expect(result.current.settingInputRequests).toHaveLength(1); + expect(result.current.settingInputRequests[0].settingName).toBe('API_KEY'); + expect(result.current.settingInputRequests[0].settingDescription).toBe( + 'Enter your API key', + ); + expect(result.current.settingInputRequests[0].sensitive).toBe(true); + }); + + it('should remove a setting input request when submitted', () => { + const { result } = renderHook(() => useSettingInputRequests()); + + const onSubmit = vi.fn(); + const onCancel = vi.fn(); + act(() => { + result.current.addSettingInputRequest({ + settingName: 'API_KEY', + settingDescription: 'Enter your API key', + sensitive: true, + onSubmit, + onCancel, + }); + }); + + expect(result.current.settingInputRequests).toHaveLength(1); + + // Submit the value + act(() => { + result.current.settingInputRequests[0].onSubmit('my-secret-key'); + }); + + expect(result.current.settingInputRequests).toHaveLength(0); + expect(onSubmit).toHaveBeenCalledWith('my-secret-key'); + expect(onCancel).not.toHaveBeenCalled(); + }); + + it('should remove a setting input request when cancelled', () => { + const { result } = renderHook(() => useSettingInputRequests()); + + const onSubmit = vi.fn(); + const onCancel = vi.fn(); + act(() => { + result.current.addSettingInputRequest({ + settingName: 'API_KEY', + settingDescription: 'Enter your API key', + sensitive: true, + onSubmit, + onCancel, + }); + }); + + expect(result.current.settingInputRequests).toHaveLength(1); + + // Cancel the request + act(() => { + result.current.settingInputRequests[0].onCancel(); + }); + + expect(result.current.settingInputRequests).toHaveLength(0); + expect(onCancel).toHaveBeenCalled(); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('should handle multiple setting input requests in sequence', () => { + const { result } = renderHook(() => useSettingInputRequests()); + + const onSubmit1 = vi.fn(); + const onCancel1 = vi.fn(); + const onSubmit2 = vi.fn(); + const onCancel2 = vi.fn(); + + act(() => { + result.current.addSettingInputRequest({ + settingName: 'USERNAME', + settingDescription: 'Enter username', + sensitive: false, + onSubmit: onSubmit1, + onCancel: onCancel1, + }); + result.current.addSettingInputRequest({ + settingName: 'PASSWORD', + settingDescription: 'Enter password', + sensitive: true, + onSubmit: onSubmit2, + onCancel: onCancel2, + }); + }); + + expect(result.current.settingInputRequests).toHaveLength(2); + + // Submit first request + act(() => { + result.current.settingInputRequests[0].onSubmit('john_doe'); + }); + + expect(result.current.settingInputRequests).toHaveLength(1); + expect(result.current.settingInputRequests[0].settingName).toBe('PASSWORD'); + expect(onSubmit1).toHaveBeenCalledWith('john_doe'); + + // Submit second request + act(() => { + result.current.settingInputRequests[0].onSubmit('secret123'); + }); + + expect(result.current.settingInputRequests).toHaveLength(0); + expect(onSubmit2).toHaveBeenCalledWith('secret123'); + }); +}); + describe('useExtensionUpdates', () => { let tempHomeDir: string; let userExtensionsDir: string; diff --git a/packages/cli/src/ui/hooks/useExtensionUpdates.ts b/packages/cli/src/ui/hooks/useExtensionUpdates.ts index 4d409e100af..b547698f91d 100644 --- a/packages/cli/src/ui/hooks/useExtensionUpdates.ts +++ b/packages/cli/src/ui/hooks/useExtensionUpdates.ts @@ -13,7 +13,11 @@ import { } from '../state/extensions.js'; import { useCallback, useEffect, useMemo, useReducer } from 'react'; import type { UseHistoryManagerReturn } from './useHistoryManager.js'; -import { MessageType, type ConfirmationRequest } from '../types.js'; +import { + MessageType, + type ConfirmationRequest, + type SettingInputRequest, +} from '../types.js'; import { checkExhaustive } from '../../utils/checks.js'; type ConfirmationRequestWrapper = { @@ -72,6 +76,74 @@ export const useConfirmUpdateRequests = () => { }; }; +type SettingInputRequestWrapper = { + settingName: string; + settingDescription: string; + sensitive: boolean; + onSubmit: (value: string) => void; + onCancel: () => void; +}; + +type SettingInputRequestAction = + | { type: 'add'; request: SettingInputRequestWrapper } + | { type: 'remove'; request: SettingInputRequestWrapper }; + +function settingInputRequestsReducer( + state: SettingInputRequestWrapper[], + action: SettingInputRequestAction, +): SettingInputRequestWrapper[] { + switch (action.type) { + case 'add': + return [...state, action.request]; + case 'remove': + return state.filter((r) => r !== action.request); + default: + checkExhaustive(action); + return state; + } +} + +export const useSettingInputRequests = () => { + const [settingInputRequests, dispatchSettingInputRequests] = useReducer( + settingInputRequestsReducer, + [], + ); + const addSettingInputRequest = useCallback( + (original: SettingInputRequest) => { + const wrappedRequest: SettingInputRequestWrapper = { + settingName: original.settingName, + settingDescription: original.settingDescription, + sensitive: original.sensitive, + onSubmit: (value: string) => { + // Remove it from the outstanding list of requests by identity. + dispatchSettingInputRequests({ + type: 'remove', + request: wrappedRequest, + }); + original.onSubmit(value); + }, + onCancel: () => { + dispatchSettingInputRequests({ + type: 'remove', + request: wrappedRequest, + }); + original.onCancel(); + }, + }; + dispatchSettingInputRequests({ + type: 'add', + request: wrappedRequest, + }); + }, + [dispatchSettingInputRequests], + ); + return { + addSettingInputRequest, + settingInputRequests, + dispatchSettingInputRequests, + }; +}; + export const useExtensionUpdates = ( extensionManager: ExtensionManager, addItem: UseHistoryManagerReturn['addItem'], diff --git a/packages/cli/src/ui/types.ts b/packages/cli/src/ui/types.ts index ff7e68aaf75..bc1bd3dcde5 100644 --- a/packages/cli/src/ui/types.ts +++ b/packages/cli/src/ui/types.ts @@ -414,3 +414,11 @@ export interface ConfirmationRequest { export interface LoopDetectionConfirmationRequest { onComplete: (result: { userSelection: 'disable' | 'keep' }) => void; } + +export interface SettingInputRequest { + settingName: string; + settingDescription: string; + sensitive: boolean; + onSubmit: (value: string) => void; + onCancel: () => void; +} diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 7c6ed12bf81..d41207ae2df 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -151,6 +151,7 @@ export interface ExtensionManagerOptions { telemetrySettings?: TelemetrySettings; config?: Config; requestConsent?: (options?: ExtensionRequestOptions) => Promise; + requestSetting?: (setting: ExtensionSetting) => Promise; } // ============================================================================ @@ -273,6 +274,7 @@ export class ExtensionManager { private telemetrySettings?: TelemetrySettings; private isWorkspaceTrusted: boolean; private requestConsent: (options?: ExtensionRequestOptions) => Promise; + private requestSetting?: (setting: ExtensionSetting) => Promise; constructor(options: ExtensionManagerOptions) { this.workspaceDir = options.workspaceDir ?? process.cwd(); @@ -284,6 +286,7 @@ export class ExtensionManager { this.configDir, 'extension-enablement.json', ); + this.requestSetting = options.requestSetting; this.requestConsent = options.requestConsent || (() => Promise.resolve()); this.config = options.config; this.telemetrySettings = options.telemetrySettings; @@ -300,6 +303,12 @@ export class ExtensionManager { this.requestConsent = requestConsent; } + setRequestSetting( + requestSetting?: (setting: ExtensionSetting) => Promise, + ): void { + this.requestSetting = requestSetting; + } + // ========================================================================== // Enablement functionality (directly implemented) // ========================================================================== @@ -690,6 +699,7 @@ export class ExtensionManager { async installExtension( installMetadata: ExtensionInstallMetadata, requestConsent?: (options?: ExtensionRequestOptions) => Promise, + requestSetting?: (setting: ExtensionSetting) => Promise, cwd?: string, previousExtensionConfig?: ExtensionConfig, ): Promise { @@ -847,7 +857,7 @@ export class ExtensionManager { previousSubagents, }); } else { - this.requestConsent({ + await this.requestConsent({ extensionConfig: newExtensionConfig, commands, skills, @@ -876,7 +886,7 @@ export class ExtensionManager { await maybePromptForSettings( newExtensionConfig, extensionId, - promptForSetting, + requestSetting || this.requestSetting || promptForSetting, previousExtensionConfig, previousSettings, ); @@ -884,7 +894,7 @@ export class ExtensionManager { await maybePromptForSettings( newExtensionConfig, extensionId, - promptForSetting, + requestSetting || this.requestSetting || promptForSetting, ); } @@ -1092,6 +1102,7 @@ export class ExtensionManager { async performWorkspaceExtensionMigration( extensions: Extension[], requestConsent: (options?: ExtensionRequestOptions) => Promise, + requestSetting?: (setting: ExtensionSetting) => Promise, ): Promise { const failedInstallNames: string[] = []; @@ -1101,7 +1112,11 @@ export class ExtensionManager { source: extension.path, type: 'local', }; - await this.installExtension(installMetadata, requestConsent); + await this.installExtension( + installMetadata, + requestConsent, + requestSetting, + ); } catch (_) { failedInstallNames.push(extension.config.name); } @@ -1164,6 +1179,7 @@ export class ExtensionManager { installMetadata, undefined, undefined, + undefined, previousExtensionConfig, ); } catch (e) { From 3f3c5ff255bff6a485db377beddc00d2ef7c5299 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 21 Jan 2026 18:11:19 +0800 Subject: [PATCH 28/30] feat add explore command --- packages/cli/src/i18n/locales/de.js | 42 ++++++++ packages/cli/src/i18n/locales/en.js | 43 +++++++++ packages/cli/src/i18n/locales/ru.js | 43 +++++++++ packages/cli/src/i18n/locales/zh.js | 38 ++++++++ .../src/services/command-migration-tool.ts | 34 ++++--- .../cli/src/ui/commands/extensionsCommand.ts | 95 +++++++++++++++++++ 6 files changed, 280 insertions(+), 15 deletions(-) diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index c19f89c7998..ca04fb25268 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -1293,4 +1293,46 @@ export default { 'Enter sensitive value...': 'Sensiblen Wert eingeben...', 'Press Enter to submit, Escape to cancel': 'Enter zum Absenden, Escape zum Abbrechen drücken', + + // ============================================================================ + // Command Migration Tool + // ============================================================================ + 'Markdown file already exists: {{filename}}': + 'Markdown-Datei existiert bereits: {{filename}}', + 'TOML Command Format Deprecation Notice': + 'TOML-Befehlsformat Veraltet-Hinweis', + 'Found {{count}} command file(s) in TOML format:': + '{{count}} Befehlsdatei(en) im TOML-Format gefunden:', + 'The TOML format for commands is being deprecated in favor of Markdown format.': + 'Das TOML-Format für Befehle wird zugunsten des Markdown-Formats eingestellt.', + 'Markdown format is more readable and easier to edit.': + 'Das Markdown-Format ist lesbarer und einfacher zu bearbeiten.', + 'You can migrate these files automatically using:': + 'Sie können diese Dateien automatisch migrieren mit:', + 'Or manually convert each file:': 'Oder jede Datei manuell konvertieren:', + 'TOML: prompt = "..." / description = "..."': + 'TOML: prompt = "..." / description = "..."', + 'Markdown: YAML frontmatter + content': 'Markdown: YAML-Frontmatter + Inhalt', + 'The migration tool will:': 'Das Migrationstool wird:', + 'Convert TOML files to Markdown': 'TOML-Dateien in Markdown konvertieren', + 'Create backups of original files': + 'Sicherungen der Originaldateien erstellen', + 'Preserve all command functionality': 'Alle Befehlsfunktionen beibehalten', + 'TOML format will continue to work for now, but migration is recommended.': + 'Das TOML-Format funktioniert vorerst weiter, aber eine Migration wird empfohlen.', + + // ============================================================================ + // Extensions - Explore Command + // ============================================================================ + 'Open extensions page in your browser': 'Erweiterungsseite im Browser öffnen', + 'Unknown extensions source: {{source}}.': + 'Unbekannte Erweiterungsquelle: {{source}}.', + 'Would open extensions page in your browser: {{url}} (skipped in test environment)': + 'Würde Erweiterungsseite im Browser öffnen: {{url}} (übersprungen in Testumgebung)', + 'View available extensions at {{url}}': + 'Verfügbare Erweiterungen ansehen unter {{url}}', + 'Opening extensions page in your browser: {{url}}': + 'Erweiterungsseite wird im Browser geöffnet: {{url}}', + 'Failed to open browser. Check out the extensions gallery at {{url}}': + 'Browser konnte nicht geöffnet werden. Besuchen Sie die Erweiterungsgalerie unter {{url}}', }; diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index b08d9fbdfc9..622b4c77336 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -1257,4 +1257,47 @@ export default { 'Enter sensitive value...': 'Enter sensitive value...', 'Press Enter to submit, Escape to cancel': 'Press Enter to submit, Escape to cancel', + + // ============================================================================ + // Command Migration Tool + // ============================================================================ + 'Markdown file already exists: {{filename}}': + 'Markdown file already exists: {{filename}}', + 'TOML Command Format Deprecation Notice': + 'TOML Command Format Deprecation Notice', + 'Found {{count}} command file(s) in TOML format:': + 'Found {{count}} command file(s) in TOML format:', + 'The TOML format for commands is being deprecated in favor of Markdown format.': + 'The TOML format for commands is being deprecated in favor of Markdown format.', + 'Markdown format is more readable and easier to edit.': + 'Markdown format is more readable and easier to edit.', + 'You can migrate these files automatically using:': + 'You can migrate these files automatically using:', + 'Or manually convert each file:': 'Or manually convert each file:', + 'TOML: prompt = "..." / description = "..."': + 'TOML: prompt = "..." / description = "..."', + 'Markdown: YAML frontmatter + content': + 'Markdown: YAML frontmatter + content', + 'The migration tool will:': 'The migration tool will:', + 'Convert TOML files to Markdown': 'Convert TOML files to Markdown', + 'Create backups of original files': 'Create backups of original files', + 'Preserve all command functionality': 'Preserve all command functionality', + 'TOML format will continue to work for now, but migration is recommended.': + 'TOML format will continue to work for now, but migration is recommended.', + + // ============================================================================ + // Extensions - Explore Command + // ============================================================================ + 'Open extensions page in your browser': + 'Open extensions page in your browser', + 'Unknown extensions source: {{source}}.': + 'Unknown extensions source: {{source}}.', + 'Would open extensions page in your browser: {{url}} (skipped in test environment)': + 'Would open extensions page in your browser: {{url}} (skipped in test environment)', + 'View available extensions at {{url}}': + 'View available extensions at {{url}}', + 'Opening extensions page in your browser: {{url}}': + 'Opening extensions page in your browser: {{url}}', + 'Failed to open browser. Check out the extensions gallery at {{url}}': + 'Failed to open browser. Check out the extensions gallery at {{url}}', }; diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index b5235362cb3..2f33a47bb53 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -1276,4 +1276,47 @@ export default { 'Enter sensitive value...': 'Введите секретное значение...', 'Press Enter to submit, Escape to cancel': 'Нажмите Enter для отправки, Escape для отмены', + + // ============================================================================ + // Command Migration Tool + // ============================================================================ + 'Markdown file already exists: {{filename}}': + 'Markdown-файл уже существует: {{filename}}', + 'TOML Command Format Deprecation Notice': + 'Уведомление об устаревании формата TOML', + 'Found {{count}} command file(s) in TOML format:': + 'Найдено {{count}} файл(ов) команд в формате TOML:', + 'The TOML format for commands is being deprecated in favor of Markdown format.': + 'Формат TOML для команд устаревает в пользу формата Markdown.', + 'Markdown format is more readable and easier to edit.': + 'Формат Markdown более читаемый и простой для редактирования.', + 'You can migrate these files automatically using:': + 'Вы можете автоматически мигрировать эти файлы с помощью:', + 'Or manually convert each file:': 'Или вручную конвертировать каждый файл:', + 'TOML: prompt = "..." / description = "..."': + 'TOML: prompt = "..." / description = "..."', + 'Markdown: YAML frontmatter + content': + 'Markdown: YAML frontmatter + содержимое', + 'The migration tool will:': 'Инструмент миграции:', + 'Convert TOML files to Markdown': 'Конвертирует TOML-файлы в Markdown', + 'Create backups of original files': 'Создаёт резервные копии исходных файлов', + 'Preserve all command functionality': 'Сохраняет всю функциональность команд', + 'TOML format will continue to work for now, but migration is recommended.': + 'Формат TOML пока продолжит работать, но миграция рекомендуется.', + + // ============================================================================ + // Extensions - Explore Command + // ============================================================================ + 'Open extensions page in your browser': + 'Открыть страницу расширений в браузере', + 'Unknown extensions source: {{source}}.': + 'Неизвестный источник расширений: {{source}}.', + 'Would open extensions page in your browser: {{url}} (skipped in test environment)': + 'Страница расширений была бы открыта в браузере: {{url}} (пропущено в тестовой среде)', + 'View available extensions at {{url}}': + 'Посмотреть доступные расширения на {{url}}', + 'Opening extensions page in your browser: {{url}}': + 'Открываем страницу расширений в браузере: {{url}}', + 'Failed to open browser. Check out the extensions gallery at {{url}}': + 'Не удалось открыть браузер. Посетите галерею расширений по адресу {{url}}', }; diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index c6b3b32310a..fba14c90916 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -1099,4 +1099,42 @@ export default { 'Enter value...': '请输入值...', 'Enter sensitive value...': '请输入敏感值...', 'Press Enter to submit, Escape to cancel': '按 Enter 提交,Escape 取消', + + // ============================================================================ + // Command Migration Tool + // ============================================================================ + 'Markdown file already exists: {{filename}}': + 'Markdown 文件已存在:{{filename}}', + 'TOML Command Format Deprecation Notice': 'TOML 命令格式弃用通知', + 'Found {{count}} command file(s) in TOML format:': + '发现 {{count}} 个 TOML 格式的命令文件:', + 'The TOML format for commands is being deprecated in favor of Markdown format.': + '命令的 TOML 格式正在被弃用,推荐使用 Markdown 格式。', + 'Markdown format is more readable and easier to edit.': + 'Markdown 格式更易读、更易编辑。', + 'You can migrate these files automatically using:': + '您可以使用以下命令自动迁移这些文件:', + 'Or manually convert each file:': '或手动转换每个文件:', + 'TOML: prompt = "..." / description = "..."': + 'TOML:prompt = "..." / description = "..."', + 'Markdown: YAML frontmatter + content': 'Markdown:YAML frontmatter + 内容', + 'The migration tool will:': '迁移工具将:', + 'Convert TOML files to Markdown': '将 TOML 文件转换为 Markdown', + 'Create backups of original files': '创建原始文件的备份', + 'Preserve all command functionality': '保留所有命令功能', + 'TOML format will continue to work for now, but migration is recommended.': + 'TOML 格式目前仍可使用,但建议迁移。', + + // ============================================================================ + // Extensions - Explore Command + // ============================================================================ + 'Open extensions page in your browser': '在浏览器中打开扩展市场页面', + 'Unknown extensions source: {{source}}.': '未知的扩展来源:{{source}}。', + 'Would open extensions page in your browser: {{url}} (skipped in test environment)': + '将在浏览器中打开扩展页面:{{url}}(测试环境中已跳过)', + 'View available extensions at {{url}}': '在 {{url}} 查看可用扩展', + 'Opening extensions page in your browser: {{url}}': + '正在浏览器中打开扩展页面:{{url}}', + 'Failed to open browser. Check out the extensions gallery at {{url}}': + '打开浏览器失败。请访问扩展市场:{{url}}', }; diff --git a/packages/cli/src/services/command-migration-tool.ts b/packages/cli/src/services/command-migration-tool.ts index e8f32b61361..68324ed1713 100644 --- a/packages/cli/src/services/command-migration-tool.ts +++ b/packages/cli/src/services/command-migration-tool.ts @@ -12,6 +12,7 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; import { glob } from 'glob'; import { convertTomlToMarkdown } from '@qwen-code/qwen-code-core'; +import { t } from '../i18n/index.js'; export interface MigrationResult { success: boolean; @@ -93,7 +94,9 @@ export async function migrateTomlCommands( try { await fs.access(markdownPath); throw new Error( - `Markdown file already exists: ${path.basename(markdownPath)}`, + t('Markdown file already exists: {{filename}}', { + filename: path.basename(markdownPath), + }), ); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { @@ -138,32 +141,33 @@ export function generateMigrationPrompt(tomlFiles: string[]): string { } const count = tomlFiles.length; + const moreCount = tomlFiles.length - 3; const fileList = tomlFiles.length <= 5 ? tomlFiles.map((f) => ` - ${f}`).join('\n') - : ` - ${tomlFiles.slice(0, 3).join('\n - ')}\n - ... and ${tomlFiles.length - 3} more`; + : ` - ${tomlFiles.slice(0, 3).join('\n - ')}\n - ${t('... and {{count}} more', { count: String(moreCount) })}`; return ` -⚠️ TOML Command Format Deprecation Notice +⚠️ ${t('TOML Command Format Deprecation Notice')} -Found ${count} command file${count > 1 ? 's' : ''} in TOML format: +${t('Found {{count}} command file(s) in TOML format:', { count: String(count) })} ${fileList} -The TOML format for commands is being deprecated in favor of Markdown format. -Markdown format is more readable and easier to edit. +${t('The TOML format for commands is being deprecated in favor of Markdown format.')} +${t('Markdown format is more readable and easier to edit.')} -You can migrate these files automatically using: +${t('You can migrate these files automatically using:')} qwen-code migrate-commands -Or manually convert each file: - - TOML: prompt = "..." / description = "..." - - Markdown: YAML frontmatter + content +${t('Or manually convert each file:')} + - ${t('TOML: prompt = "..." / description = "..."')} + - ${t('Markdown: YAML frontmatter + content')} -The migration tool will: - ✓ Convert TOML files to Markdown - ✓ Create backups of original files - ✓ Preserve all command functionality +${t('The migration tool will:')} + ✓ ${t('Convert TOML files to Markdown')} + ✓ ${t('Create backups of original files')} + ✓ ${t('Preserve all command functionality')} -TOML format will continue to work for now, but migration is recommended. +${t('TOML format will continue to work for now, but migration is recommended.')} `.trim(); } diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index c50db9dbfaa..2ae4b574fe6 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -19,6 +19,14 @@ import { type ExtensionUpdateInfo, } from '@qwen-code/qwen-code-core'; import { SettingScope } from '../../config/settings.js'; +import open from 'open'; + +const EXTENSION_EXPLORE_URL = { + Gemini: 'https://geminicli.com/extensions/', + ClaudeCode: 'https://claudemarketplaces.com/', +} as const; + +type ExtensionExploreSource = keyof typeof EXTENSION_EXPLORE_URL; function showMessageIfNoExtensions( context: CommandContext, @@ -37,6 +45,71 @@ function showMessageIfNoExtensions( return false; } +async function exploreAction(context: CommandContext, args: string) { + const source = args.trim(); + const extensionsUrl = source + ? EXTENSION_EXPLORE_URL[source as ExtensionExploreSource] + : ''; + if (!extensionsUrl) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: t('Unknown extensions source: {{source}}.', { source }), + }, + Date.now(), + ); + return; + } + // Only check for NODE_ENV for explicit test mode, not for unit test framework + if (process.env['NODE_ENV'] === 'test') { + context.ui.addItem( + { + type: MessageType.INFO, + text: t( + 'Would open extensions page in your browser: {{url}} (skipped in test environment)', + { url: extensionsUrl }, + ), + }, + Date.now(), + ); + } else if ( + process.env['SANDBOX'] && + process.env['SANDBOX'] !== 'sandbox-exec' + ) { + context.ui.addItem( + { + type: MessageType.INFO, + text: t('View available extensions at {{url}}', { url: extensionsUrl }), + }, + Date.now(), + ); + } else { + context.ui.addItem( + { + type: MessageType.INFO, + text: t('Opening extensions page in your browser: {{url}}', { + url: extensionsUrl, + }), + }, + Date.now(), + ); + try { + await open(extensionsUrl); + } catch (_error) { + context.ui.addItem( + { + type: MessageType.ERROR, + text: t( + 'Failed to open browser. Check out the extensions gallery at {{url}}', + { url: extensionsUrl }, + ), + }, + Date.now(), + ); + } + } +} + async function listAction(context: CommandContext) { const extensions = context.services.config ? context.services.config.getExtensions() @@ -440,6 +513,27 @@ export async function completeExtensionsAndScopes( ]); } +export async function completeExtensionsExplore( + context: CommandContext, + partialArg: string, +) { + const suggestions = Object.keys(EXTENSION_EXPLORE_URL).filter((name) => + name.startsWith(partialArg), + ); + + return suggestions; +} + +const exploreExtensionsCommand: SlashCommand = { + name: 'explore', + get description() { + return t('Open extensions page in your browser'); + }, + kind: CommandKind.BUILT_IN, + action: exploreAction, + completion: completeExtensionsExplore, +}; + const listExtensionsCommand: SlashCommand = { name: 'list', get description() { @@ -511,6 +605,7 @@ export const extensionsCommand: SlashCommand = { enableCommand, installCommand, uninstallCommand, + exploreExtensionsCommand, ], action: (context, args) => // Default to list if no subcommand is provided From 5f3f81b666edb75611d7677514ac8ad88ad3c338 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Wed, 21 Jan 2026 19:57:26 +0800 Subject: [PATCH 29/30] docs move extension to user and hide create docs --- docs/developers/_meta.ts | 3 - docs/users/_meta.ts | 1 + docs/users/extension/_meta.ts | 9 ++ .../extension}/extension-releasing.md | 0 .../extension}/getting-started-extensions.md | 12 -- .../extension/introduction.md} | 134 ++++++++++++++---- 6 files changed, 113 insertions(+), 46 deletions(-) create mode 100644 docs/users/extension/_meta.ts rename docs/{developers/extensions => users/extension}/extension-releasing.md (100%) rename docs/{developers/extensions => users/extension}/getting-started-extensions.md (97%) rename docs/{developers/extensions/extension.md => users/extension/introduction.md} (68%) diff --git a/docs/developers/_meta.ts b/docs/developers/_meta.ts index 154ce184899..a7a316f77da 100644 --- a/docs/developers/_meta.ts +++ b/docs/developers/_meta.ts @@ -19,9 +19,6 @@ export default { tools: 'Tools', - extensions: { - display: 'hidden', - }, examples: { display: 'hidden', }, diff --git a/docs/users/_meta.ts b/docs/users/_meta.ts index 2ec43d77306..a822e820124 100644 --- a/docs/users/_meta.ts +++ b/docs/users/_meta.ts @@ -20,6 +20,7 @@ export default { }, features: 'Features', configuration: 'Configuration', + extension: 'Extension', reference: 'Reference', support: 'Support', // need refine diff --git a/docs/users/extension/_meta.ts b/docs/users/extension/_meta.ts new file mode 100644 index 00000000000..386bb68fc22 --- /dev/null +++ b/docs/users/extension/_meta.ts @@ -0,0 +1,9 @@ +export default { + introduction: 'Introduction', + 'getting-start-extensions': { + display: 'hidden', + }, + 'extension-releasing': { + display: 'hidden', + }, +}; diff --git a/docs/developers/extensions/extension-releasing.md b/docs/users/extension/extension-releasing.md similarity index 100% rename from docs/developers/extensions/extension-releasing.md rename to docs/users/extension/extension-releasing.md diff --git a/docs/developers/extensions/getting-started-extensions.md b/docs/users/extension/getting-started-extensions.md similarity index 97% rename from docs/developers/extensions/getting-started-extensions.md rename to docs/users/extension/getting-started-extensions.md index 3ac0e74ecbe..a09f74c8e63 100644 --- a/docs/developers/extensions/getting-started-extensions.md +++ b/docs/users/extension/getting-started-extensions.md @@ -246,18 +246,6 @@ Subagents are specialized AI assistants for specific tasks. 5. Verify functionality is preserved ``` -3. Update your `qwen-extension.json` to include the new directories: - - ```json - { - "name": "my-first-extension", - "version": "1.0.0", - "skills": "skills", - "agents": "agents", - "mcpServers": { ... } - } - ``` - After restarting Qwen Code, your custom skills will be available via `/skills` and subagents via `/agents manage`. ## Step 6: Add a Custom `QWEN.md` diff --git a/docs/developers/extensions/extension.md b/docs/users/extension/introduction.md similarity index 68% rename from docs/developers/extensions/extension.md rename to docs/users/extension/introduction.md index ae29ef1aa37..64bc7bc7d0d 100644 --- a/docs/developers/extensions/extension.md +++ b/docs/users/extension/introduction.md @@ -2,6 +2,8 @@ Qwen Code extensions package prompts, MCP servers, and custom commands into a familiar and user-friendly format. With extensions, you can expand the capabilities of Qwen Code and share those capabilities with others. They are designed to be easily installable and shareable. +This cross-platform compatibility gives you access to a rich ecosystem of extensions and plugins, dramatically expanding Qwen Code's capabilities without requiring extension authors to maintain separate versions. + ## Extension management We offer a suite of extension management tools using both `qwen extensions` CLI commands and `/extensions` slash commands within the interactive CLI. @@ -10,15 +12,16 @@ We offer a suite of extension management tools using both `qwen extensions` CLI You can manage extensions at runtime within the interactive CLI using `/extensions` slash commands. These commands support hot-reloading, meaning changes take effect immediately without restarting the application. -| Command | Description | -| ------------------------------------------------------ | --------------------------------------------------------------- | -| `/extensions` or `/extensions list` | List all installed extensions with their status | -| `/extensions install ` | Install an extension from a git URL, local path, or marketplace | -| `/extensions uninstall ` | Uninstall an extension | -| `/extensions enable --scope ` | Enable an extension | -| `/extensions disable --scope ` | Disable an extension | -| `/extensions update ` | Update a specific extension | -| `/extensions update --all` | Update all extensions with available updates | +| Command | Description | +| ------------------------------------------------------ | ----------------------------------------------------------------- | +| `/extensions` or `/extensions list` | List all installed extensions with their status | +| `/extensions install ` | Install an extension from a git URL, local path, or marketplace | +| `/extensions uninstall ` | Uninstall an extension | +| `/extensions enable --scope ` | Enable an extension | +| `/extensions disable --scope ` | Disable an extension | +| `/extensions update ` | Update a specific extension | +| `/extensions update --all` | Update all extensions with available updates | +| `/extensions explore [source]` | Open extensions source page(Gemini or ClaudeCode) in your browser | ### CLI Extension Management @@ -26,15 +29,54 @@ You can also manage extensions using `qwen extensions` CLI commands. Note that c ### Installing an extension -You can install an extension using `qwen extensions install` with either a GitHub URL or a local path`. +You can install an extension using `qwen extensions install` from multiple sources: -Note that we create a copy of the installed extension, so you will need to run `qwen extensions update` to pull in changes from both locally-defined extensions and those on GitHub. +#### From Gemini CLI Extensions Marketplace + +Qwen Code fully supports extensions from the [Gemini CLI Extensions Marketplace](https://geminicli.com/extensions/). Simply install them using the git URL: + +```bash +qwen extensions install +``` + +Gemini extensions are automatically converted to Qwen Code format during installation: + +- `gemini-extension.json` is converted to `qwen-extension.json` +- TOML command files are automatically migrated to Markdown format +- MCP servers, context files, and settings are preserved + +#### From Claude Code Marketplace + +Qwen Code also supports plugins from the [Claude Code Marketplace](https://claudemarketplaces.com/). Install them using the marketplace URL format: + +```bash +qwen extensions install : +``` +Claude plugins are automatically converted to Qwen Code format during installation: + +- `claude-plugin.json` is converted to `qwen-extension.json` +- Agent configurations are converted to Qwen subagent format +- Skill configurations are converted to Qwen skill format +- Tool mappings are automatically handled + +> **Cross-Platform Compatibility**: This allows you to leverage the rich extension ecosystems from both Gemini CLI and Claude Code, dramatically expanding the available functionality for Qwen Code users. + +#### From Git Repository + +```bash +qwen extensions install https://github.com/github/github-mcp-server ``` -qwen extensions install https://github.com/qwen-cli-extensions/security + +This will install the github mcp server extension. + +#### From Local Path + +```bash +qwen extensions install /path/to/your/extension ``` -This will install the Qwen Code Security extension, which offers support for a `/security:analyze` command. +Note that we create a copy of the installed extension, so you will need to run `qwen extensions update` to pull in changes from both locally-defined extensions and those on GitHub. ### Uninstalling an extension @@ -66,29 +108,19 @@ You can update all extensions with: qwen extensions update --all ``` -## Extension creation - -We offer commands to make extension development easier. +### Exploring Extension Marketplaces -### Create a boilerplate extension +You can quickly browse available extensions from different marketplaces using the `/extensions explore` command: -We offer several example extensions `context`, `custom-commands`, `exclude-tools` and `mcp-server`. You can view these examples [here](https://github.com/QwenLM/qwen-code/tree/main/packages/cli/src/commands/extensions/examples). +```bash +# Open Gemini CLI Extensions marketplace +/extensions explore Gemini -To copy one of these examples into a development directory using the type of your choosing, run: - -``` -qwen extensions new path/to/directory custom-commands +# Open Claude Code marketplace +/extensions explore ClaudeCode ``` -### Link a local extension - -The `qwen extensions link` command will create a symbolic link from the extension installation directory to the development path. - -This is useful so you don't have to run `qwen extensions update` every time you make changes you'd like to test. - -``` -qwen extensions link path/to/directory -``` +This command opens the respective marketplace in your default browser, allowing you to discover new extensions to enhance your Qwen Code experience. ## How it works @@ -135,6 +167,46 @@ The `qwen-extension.json` file contains the configuration for the extension. The - `skills`: The directory containing custom skills (default: `skills`). Skills are discovered automatically and become available via the `/skills` command. - `agents`: The directory containing custom subagents (default: `agents`). Subagents are `.yaml` or `.md` files that define specialized AI assistants. - `settings`: An array of settings that the extension requires. When installing, users will be prompted to provide values for these settings. The values are stored securely and passed to MCP servers as environment variables. + - Each setting has the following properties: + - `name`: Display name for the setting + - `description`: A description of what this setting is used for + - `envVar`: The environment variable name that will be set + - `sensitive`: Boolean indicating if the value should be hidden (e.g., API keys, passwords) + +### Managing Extension Settings + +Extensions can require configuration through settings (such as API keys or credentials). These settings can be managed using the `qwen extensions settings` CLI command: + +**Set a setting value:** + +```bash +qwen extensions settings set [--scope user|workspace] +``` + +**List all settings for an extension:** + +```bash +qwen extensions settings list +``` + +**View current values (user and workspace):** + +```bash +qwen extensions settings show +``` + +**Remove a setting value:** + +```bash +qwen extensions settings unset [--scope user|workspace] +``` + +Settings can be configured at two levels: + +- **User level** (default): Settings apply across all projects (`~/.qwen/.env`) +- **Workspace level**: Settings apply only to the current project (`.qwen/.env`) + +Workspace settings take precedence over user settings. Sensitive settings are stored securely and never displayed in plain text. When Qwen Code starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence. From 9af348d6ad84f76cdd6a272c7732aa6fb0c9d175 Mon Sep 17 00:00:00 2001 From: LaZzyMan Date: Thu, 22 Jan 2026 11:56:35 +0800 Subject: [PATCH 30/30] fix ci test --- packages/cli/src/services/command-migration-tool.test.ts | 4 ++-- packages/cli/src/ui/commands/extensionsCommand.ts | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/services/command-migration-tool.test.ts b/packages/cli/src/services/command-migration-tool.test.ts index 8eae0b02185..618a38f946f 100644 --- a/packages/cli/src/services/command-migration-tool.test.ts +++ b/packages/cli/src/services/command-migration-tool.test.ts @@ -223,7 +223,7 @@ description = "Test description"`; const prompt = generateMigrationPrompt(files); - expect(prompt).toContain('Found 2 command files'); + expect(prompt).toContain('Found 2 command file(s)'); expect(prompt).toContain('cmd1.toml'); expect(prompt).toContain('cmd2.toml'); expect(prompt).toContain('qwen-code migrate-commands'); @@ -234,7 +234,7 @@ description = "Test description"`; const prompt = generateMigrationPrompt(files); - expect(prompt).toContain('Found 10 command files'); + expect(prompt).toContain('Found 10 command file(s)'); expect(prompt).toContain('... and 7 more'); }); diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index 2ae4b574fe6..c14365a7156 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -495,8 +495,10 @@ export async function completeExtensions( name.startsWith(partialArg), ); - if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) { - suggestions.unshift('--all'); + if (context.invocation?.name !== 'uninstall') { + if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) { + suggestions.unshift('--all'); + } } return suggestions;