diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index e94119a9318..f3d549543b1 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -703,6 +703,7 @@ export async function loadCliConfig( enabledExtensions: argv.extensions, extensionLoader: extensionManager, enableExtensionReloading: settings.experimental?.extensionReloading, + dynamicExtensionLoading: settings.experimental?.dynamicExtensionLoading, enableAgents: settings.experimental?.enableAgents, skillsSupport: settings.experimental?.skills, disabledSkills: settings.skills?.disabled, diff --git a/packages/cli/src/config/extension-manager.ts b/packages/cli/src/config/extension-manager.ts index 3c4ed226c85..101b72b271f 100644 --- a/packages/cli/src/config/extension-manager.ts +++ b/packages/cli/src/config/extension-manager.ts @@ -47,6 +47,7 @@ import { type HookEventName, type ResolvedExtensionSetting, coreEvents, + ExtensionScope, } from '@google/gemini-cli-core'; import { maybeRequestConsentOrFail } from './extensions/consent.js'; import { resolveEnvVarsInObject } from '../utils/envVarResolver.js'; @@ -565,6 +566,7 @@ Would you like to attempt to install via "git clone" instead?`, const extension: GeminiCLIExtension = { name: config.name, + description: config.description, version: config.version, path: effectiveExtensionPath, contextFiles, @@ -572,10 +574,14 @@ Would you like to attempt to install via "git clone" instead?`, mcpServers: config.mcpServers, excludeTools: config.excludeTools, hooks, - isActive: this.extensionEnablementManager.isEnabled( - config.name, - this.workspaceDir, - ), + isActive: + this.settings.experimental?.extensionReloading && + this.settings.experimental?.dynamicExtensionLoading + ? false + : this.extensionEnablementManager.isEnabled( + config.name, + this.workspaceDir, + ), id: getExtensionId(config, installMetadata), settings: config.settings, resolvedSettings, @@ -632,6 +638,7 @@ Would you like to attempt to install via "git clone" instead?`, ) as unknown as ExtensionConfig; validateName(config.name); + return config; } catch (e) { throw new Error( @@ -750,10 +757,12 @@ Would you like to attempt to install via "git clone" instead?`, return output; } - async disableExtension(name: string, scope: SettingScope) { + async disableExtension(name: string, scope: SettingScope | ExtensionScope) { if ( scope === SettingScope.System || - scope === SettingScope.SystemDefaults + scope === SettingScope.SystemDefaults || + scope === ExtensionScope.System || + scope === ExtensionScope.SystemDefaults ) { throw new Error('System and SystemDefaults scopes are not supported.'); } @@ -764,9 +773,11 @@ Would you like to attempt to install via "git clone" instead?`, throw new Error(`Extension with name ${name} does not exist.`); } - if (scope !== SettingScope.Session) { + if (scope !== SettingScope.Session && scope !== ExtensionScope.Session) { const scopePath = - scope === SettingScope.Workspace ? this.workspaceDir : homedir(); + scope === SettingScope.Workspace || scope === ExtensionScope.Workspace + ? this.workspaceDir + : homedir(); this.extensionEnablementManager.disable(name, true, scopePath); } await logExtensionDisable( @@ -785,10 +796,12 @@ Would you like to attempt to install via "git clone" instead?`, * Enables an existing extension for a given scope, and starts it if * appropriate. */ - async enableExtension(name: string, scope: SettingScope) { + async enableExtension(name: string, scope: SettingScope | ExtensionScope) { if ( scope === SettingScope.System || - scope === SettingScope.SystemDefaults + scope === SettingScope.SystemDefaults || + scope === ExtensionScope.System || + scope === ExtensionScope.SystemDefaults ) { throw new Error('System and SystemDefaults scopes are not supported.'); } @@ -799,9 +812,11 @@ Would you like to attempt to install via "git clone" instead?`, throw new Error(`Extension with name ${name} does not exist.`); } - if (scope !== SettingScope.Session) { + if (scope !== SettingScope.Session && scope !== ExtensionScope.Session) { const scopePath = - scope === SettingScope.Workspace ? this.workspaceDir : homedir(); + scope === SettingScope.Workspace || scope === ExtensionScope.Workspace + ? this.workspaceDir + : homedir(); this.extensionEnablementManager.enable(name, true, scopePath); } await logExtensionEnable( diff --git a/packages/cli/src/config/extension.ts b/packages/cli/src/config/extension.ts index bafaba59a8e..05ecda9a056 100644 --- a/packages/cli/src/config/extension.ts +++ b/packages/cli/src/config/extension.ts @@ -22,6 +22,7 @@ import type { ExtensionSetting } from './extensions/extensionSettings.js'; */ export interface ExtensionConfig { name: string; + description?: string; version: string; mcpServers?: Record; contextFileName?: string | string[]; diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index efe535e42eb..403e8d99510 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -1365,6 +1365,16 @@ const SETTINGS_SCHEMA = { 'Enables extension loading/unloading within the CLI session.', showInDialog: false, }, + dynamicExtensionLoading: { + type: 'boolean', + label: 'Dynamic Extension Loading', + category: 'Experimental', + requiresRestart: true, + default: false, + description: + 'Enables the model to dynamically activate extensions (requires extensionReloading).', + showInDialog: false, + }, jitContext: { type: 'boolean', label: 'JIT Context Loading', diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index cc9929f23c0..6b74823dd6f 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -25,6 +25,7 @@ import { GrepTool } from '../tools/grep.js'; import { canUseRipgrep, RipGrepTool } from '../tools/ripGrep.js'; import { GlobTool } from '../tools/glob.js'; import { ActivateSkillTool } from '../tools/activate-skill.js'; +import { ActivateExtensionTool } from '../tools/activate-extension.js'; import { EditTool } from '../tools/edit.js'; import { ShellTool } from '../tools/shell.js'; import { WriteFileTool } from '../tools/write-file.js'; @@ -163,6 +164,7 @@ export interface IntrospectionAgentSettings { */ export interface GeminiCLIExtension { name: string; + description?: string; version: string; isActive: boolean; path: string; @@ -303,6 +305,7 @@ export interface ConfigParameters { extensionLoader?: ExtensionLoader; enabledExtensions?: string[]; enableExtensionReloading?: boolean; + dynamicExtensionLoading?: boolean; allowedMcpServers?: string[]; blockedMcpServers?: string[]; allowedEnvironmentVariables?: string[]; @@ -430,6 +433,7 @@ export class Config { private readonly _extensionLoader: ExtensionLoader; private readonly _enabledExtensions: string[]; private readonly enableExtensionReloading: boolean; + private readonly dynamicExtensionLoading: boolean; fallbackModelHandler?: FallbackModelHandler; private quotaErrorOccurred: boolean = false; private readonly summarizeToolOutput: @@ -601,6 +605,8 @@ export class Config { this.truncateToolOutputLines = params.truncateToolOutputLines ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES; this.enableToolOutputTruncation = params.enableToolOutputTruncation ?? true; + this.enableExtensionReloading = params.enableExtensionReloading ?? false; + this.dynamicExtensionLoading = params.dynamicExtensionLoading ?? false; // // TODO(joshualitt): Re-evaluate the todo tool for 3 family. this.useWriteTodos = isPreviewModel(this.model) ? false @@ -631,6 +637,7 @@ export class Config { (params.shellToolInactivityTimeout ?? 300) * 1000; // 5 minutes this.extensionManagement = params.extensionManagement ?? true; this.enableExtensionReloading = params.enableExtensionReloading ?? false; + this.dynamicExtensionLoading = params.dynamicExtensionLoading ?? false; this.storage = new Storage(this.targetDir); this.fakeResponses = params.fakeResponses; this.recordResponses = params.recordResponses; @@ -742,6 +749,13 @@ export class Config { ]); initMcpHandle?.end(); + // Register ActivateExtensionTool + if (this.enableExtensionReloading && this.dynamicExtensionLoading) { + this.getToolRegistry().registerTool( + new ActivateExtensionTool(this, this.messageBus), + ); + } + // Discover skills if enabled if (this.skillsSupport) { await this.getSkillManager().discoverSkills( @@ -1412,6 +1426,10 @@ export class Config { return this.enableExtensionReloading; } + getDynamicExtensionLoading(): boolean { + return this.dynamicExtensionLoading; + } + isAgentsEnabled(): boolean { return this.enableAgents; } diff --git a/packages/core/src/core/__snapshots__/prompts.test.ts.snap b/packages/core/src/core/__snapshots__/prompts.test.ts.snap index 19df12b0932..fd556e90929 100644 --- a/packages/core/src/core/__snapshots__/prompts.test.ts.snap +++ b/packages/core/src/core/__snapshots__/prompts.test.ts.snap @@ -1,5 +1,103 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`Core System Prompt (prompts.ts) > should NOT include available_extensions when dynamicExtensionLoading is disabled 1`] = ` +"You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools. + +# Core Mandates + +- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first. +- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it. +- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project. +- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically. +- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments. +- **Proactiveness:** Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise. +- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it. +- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked. +- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes. + +Mock Agent Directory + +# Primary Workflows + +## Software Engineering Tasks +When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence: +1. **Understand:** Think about the user's request and the relevant codebase context. Use 'search_file_content' and 'glob' search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. +Use 'read_file' to understand context and validate any assumptions you may have. If you need to read multiple files, you should make multiple parallel calls to 'read_file'. +2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should use an iterative development process that includes writing unit tests to verify your changes. Use output logs or debug statements as part of this process to arrive at a solution. +3. **Implement:** Use the available tools (e.g., 'replace', 'write_file' 'run_shell_command' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates'). +4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands. +5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to. +6. **Finalize:** After all verification passes, consider the task complete. Do not remove or revert any changes or created files (like tests). Await the user's next instruction. + +## New Applications + +**Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are 'write_file', 'replace' and 'run_shell_command'. + +1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions. +2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner. + - When key technologies aren't specified, prefer the following: + - **Websites (Frontend):** React (JavaScript/TypeScript) or Angular with Bootstrap CSS, incorporating Material Design principles for UI/UX. + - **Back-End APIs:** Node.js with Express.js (JavaScript/TypeScript) or Python with FastAPI. + - **Full-stack:** Next.js (React/Node.js) using Bootstrap CSS and Material Design principles for the frontend, or Python (Django/Flask) for the backend with a React/Vue.js/Angular frontend styled with Bootstrap CSS and Material Design principles. + - **CLIs:** Python or Go. + - **Mobile App:** Compose Multiplatform (Kotlin Multiplatform) or Flutter (Dart) using Material Design libraries and principles, when sharing code between Android and iOS. Jetpack Compose (Kotlin JVM) with Material Design principles or SwiftUI (Swift) for native apps targeted at either Android or iOS, respectively. + - **3d Games:** HTML/CSS/JavaScript with Three.js. + - **2d Games:** HTML/CSS/JavaScript. +3. **User Approval:** Obtain user approval for the proposed plan. +4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using 'run_shell_command' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible. +5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors. +6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype. + +# Operational Guidelines + +## Shell tool output token efficiency: + +IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION. + +- Always prefer command flags that reduce output verbosity when using 'run_shell_command'. +- Aim to minimize tool output tokens while still capturing necessary information. +- If a command is expected to produce a lot of output, use quiet or silent flags where available and appropriate. +- Always consider the trade-off between output verbosity and the need for information. If a command's full output is essential for understanding the result, avoid overly aggressive quieting that might obscure important details. +- If a command does not have quiet/silent flags or for commands with potentially long output that may not be useful, redirect stdout and stderr to temp files in the project's temporary directory. For example: 'command > /out.log 2> /err.log'. +- After the command runs, inspect the temp files (e.g. '/out.log' and '/err.log') using commands like 'grep', 'tail', 'head', ... (or platform equivalents). Remove the temp files when done. + + +## Tone and Style (CLI Interaction) +- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment. +- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query. +- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous. +- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer. +- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace. +- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself. +- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate. + +## Security and Safety Rules +- **Explain Critical Commands:** Before executing commands with 'run_shell_command' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this). +- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information. + +## Tool Usage +- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase). +- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first. +- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user. +- **Interactive Commands:** Prefer non-interactive commands when it makes sense; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`ctrl + f\` to focus into the shell to provide input. +- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?" +- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward. + +## Interaction Details +- **Help Command:** The user can use '/help' to display help information. +- **Feedback:** To report a bug or provide feedback, please use the /bug command. + + +# Outside of Sandbox +You are running outside of a sandbox container, directly on the user's system. For critical commands that are particularly likely to modify the user's system outside of the project directory or system temp directory, as you explain the command to the user (per the Explain Critical Commands rule above), also remind the user to consider enabling sandboxing. + + + + +# Final Reminder +Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read_file' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved." +`; + exports[`Core System Prompt (prompts.ts) > should append userMemory with separator when provided 1`] = ` "You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools. @@ -503,6 +601,115 @@ You are running outside of a sandbox container, directly on the user's system. F - Never push changes to a remote repository without being asked explicitly by the user. +# Final Reminder +Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read_file' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved." +`; + +exports[`Core System Prompt (prompts.ts) > should include available_extensions when dynamicExtensionLoading is enabled 1`] = ` +"You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools. + +# Core Mandates + +- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first. +- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it. +- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project. +- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically. +- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments. +- **Proactiveness:** Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise. +- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it. +- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked. +- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes. + +Mock Agent Directory +# Available Extensions + +You have access to the following extensions which are currently disabled. specific tools or capabilities they provide are not currently available. To activate an extension and gain access to its tools, you can call the \`activate_extension\` tool with the extension's name. + + + + test-extension + A test extension description + + + + +# Primary Workflows + +## Software Engineering Tasks +When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence: +1. **Understand:** Think about the user's request and the relevant codebase context. Use 'search_file_content' and 'glob' search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. +Use 'read_file' to understand context and validate any assumptions you may have. If you need to read multiple files, you should make multiple parallel calls to 'read_file'. +2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should use an iterative development process that includes writing unit tests to verify your changes. Use output logs or debug statements as part of this process to arrive at a solution. +3. **Implement:** Use the available tools (e.g., 'replace', 'write_file' 'run_shell_command' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates'). +4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands. +5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to. +6. **Finalize:** After all verification passes, consider the task complete. Do not remove or revert any changes or created files (like tests). Await the user's next instruction. + +## New Applications + +**Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are 'write_file', 'replace' and 'run_shell_command'. + +1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions. +2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner. + - When key technologies aren't specified, prefer the following: + - **Websites (Frontend):** React (JavaScript/TypeScript) or Angular with Bootstrap CSS, incorporating Material Design principles for UI/UX. + - **Back-End APIs:** Node.js with Express.js (JavaScript/TypeScript) or Python with FastAPI. + - **Full-stack:** Next.js (React/Node.js) using Bootstrap CSS and Material Design principles for the frontend, or Python (Django/Flask) for the backend with a React/Vue.js/Angular frontend styled with Bootstrap CSS and Material Design principles. + - **CLIs:** Python or Go. + - **Mobile App:** Compose Multiplatform (Kotlin Multiplatform) or Flutter (Dart) using Material Design libraries and principles, when sharing code between Android and iOS. Jetpack Compose (Kotlin JVM) with Material Design principles or SwiftUI (Swift) for native apps targeted at either Android or iOS, respectively. + - **3d Games:** HTML/CSS/JavaScript with Three.js. + - **2d Games:** HTML/CSS/JavaScript. +3. **User Approval:** Obtain user approval for the proposed plan. +4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using 'run_shell_command' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible. +5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors. +6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype. + +# Operational Guidelines + +## Shell tool output token efficiency: + +IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION. + +- Always prefer command flags that reduce output verbosity when using 'run_shell_command'. +- Aim to minimize tool output tokens while still capturing necessary information. +- If a command is expected to produce a lot of output, use quiet or silent flags where available and appropriate. +- Always consider the trade-off between output verbosity and the need for information. If a command's full output is essential for understanding the result, avoid overly aggressive quieting that might obscure important details. +- If a command does not have quiet/silent flags or for commands with potentially long output that may not be useful, redirect stdout and stderr to temp files in the project's temporary directory. For example: 'command > /out.log 2> /err.log'. +- After the command runs, inspect the temp files (e.g. '/out.log' and '/err.log') using commands like 'grep', 'tail', 'head', ... (or platform equivalents). Remove the temp files when done. + + +## Tone and Style (CLI Interaction) +- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment. +- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query. +- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous. +- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer. +- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace. +- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself. +- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate. + +## Security and Safety Rules +- **Explain Critical Commands:** Before executing commands with 'run_shell_command' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this). +- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information. + +## Tool Usage +- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase). +- **Command Execution:** Use the 'run_shell_command' tool for running shell commands, remembering the safety rule to explain modifying commands first. +- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user. +- **Interactive Commands:** Prefer non-interactive commands when it makes sense; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`ctrl + f\` to focus into the shell to provide input. +- **Remembering Facts:** Use the 'save_memory' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?" +- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward. + +## Interaction Details +- **Help Command:** The user can use '/help' to display help information. +- **Feedback:** To report a bug or provide feedback, please use the /bug command. + + +# Outside of Sandbox +You are running outside of a sandbox container, directly on the user's system. For critical commands that are particularly likely to modify the user's system outside of the project directory or system temp directory, as you explain the command to the user (per the Explain Critical Commands rule above), also remind the user to consider enabling sandboxing. + + + + # Final Reminder Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read_file' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved." `; diff --git a/packages/core/src/core/prompts.test.ts b/packages/core/src/core/prompts.test.ts index ceb5019df87..76bb7d1bc8f 100644 --- a/packages/core/src/core/prompts.test.ts +++ b/packages/core/src/core/prompts.test.ts @@ -75,6 +75,10 @@ describe('Core System Prompt (prompts.ts)', () => { getSkillManager: vi.fn().mockReturnValue({ getSkills: vi.fn().mockReturnValue([]), }), + getExtensionLoader: vi.fn().mockReturnValue({ + getExtensions: vi.fn().mockReturnValue([]), + }), + getDynamicExtensionLoading: vi.fn().mockReturnValue(false), } as unknown as Config; }); @@ -109,6 +113,65 @@ describe('Core System Prompt (prompts.ts)', () => { expect(prompt).toMatchSnapshot(); }); + it('should include available_extensions when dynamicExtensionLoading is enabled', () => { + const extensions = [ + { + name: 'test-extension', + id: 'test-extension-id', + description: 'A test extension description', + path: '/path/to/test-extension', + isActive: false, + version: '1.0.0', + contextFiles: [], + installMetadata: { + type: 'local' as const, + source: '/path/to/test-extension', + }, + resolvedSettings: [], + skills: [], + }, + ]; + vi.mocked(mockConfig.getExtensionLoader().getExtensions).mockReturnValue( + extensions, + ); + vi.mocked(mockConfig.getDynamicExtensionLoading).mockReturnValue(true); + const prompt = getCoreSystemPrompt(mockConfig); + + expect(prompt).toContain('# Available Extensions'); + expect(prompt).toContain(''); + expect(prompt).toContain('test-extension'); + expect(prompt).toMatchSnapshot(); + }); + + it('should NOT include available_extensions when dynamicExtensionLoading is disabled', () => { + const extensions = [ + { + name: 'test-extension', + id: 'test-extension-id', + description: 'A test extension description', + path: '/path/to/test-extension', + isActive: false, + version: '1.0.0', + contextFiles: [], + installMetadata: { + type: 'local' as const, + source: '/path/to/test-extension', + }, + resolvedSettings: [], + skills: [], + }, + ]; + vi.mocked(mockConfig.getExtensionLoader().getExtensions).mockReturnValue( + extensions, + ); + vi.mocked(mockConfig.getDynamicExtensionLoading).mockReturnValue(false); + const prompt = getCoreSystemPrompt(mockConfig); + + expect(prompt).not.toContain('# Available Extensions'); + expect(prompt).not.toContain(''); + expect(prompt).toMatchSnapshot(); + }); + it('should NOT include skill guidance or available_skills when NO skills are provided', () => { vi.mocked(mockConfig.getSkillManager().getSkills).mockReturnValue([]); const prompt = getCoreSystemPrompt(mockConfig); @@ -223,6 +286,10 @@ describe('Core System Prompt (prompts.ts)', () => { getSkillManager: vi.fn().mockReturnValue({ getSkills: vi.fn().mockReturnValue([]), }), + getExtensionLoader: vi.fn().mockReturnValue({ + getExtensions: vi.fn().mockReturnValue([]), + }), + getDynamicExtensionLoading: vi.fn().mockReturnValue(false), } as unknown as Config; const prompt = getCoreSystemPrompt(testConfig); diff --git a/packages/core/src/core/prompts.ts b/packages/core/src/core/prompts.ts index 243582494f1..17b1885234f 100644 --- a/packages/core/src/core/prompts.ts +++ b/packages/core/src/core/prompts.ts @@ -17,6 +17,7 @@ import { WRITE_TODOS_TOOL_NAME, DELEGATE_TO_AGENT_TOOL_NAME, ACTIVATE_SKILL_TOOL_NAME, + ACTIVATE_EXTENSION_TOOL_NAME, } from '../tools/tool-names.js'; import process from 'node:process'; import { isGitRepository } from '../utils/gitUtils.js'; @@ -154,6 +155,30 @@ ${skillsXml} `; } + const extensionLoader = config.getExtensionLoader(); + const extensions = extensionLoader.getExtensions().filter((e) => !e.isActive); + let extensionsPrompt = ''; + if (config.getDynamicExtensionLoading() && extensions.length > 0) { + const extensionsXml = extensions + .map( + (ext) => ` + ${ext.name} + ${ext.description || 'No description provided.'} + `, + ) + .join('\n'); + + extensionsPrompt = ` +# Available Extensions + +You have access to the following extensions which are currently disabled. specific tools or capabilities they provide are not currently available. To activate an extension and gain access to its tools, you can call the \`${ACTIVATE_EXTENSION_TOOL_NAME}\` tool with the extension's name. + + +${extensionsXml} + +`; + } + let basePrompt: string; if (systemMdEnabled) { basePrompt = fs.readFileSync(systemMdPath, 'utf8'); @@ -183,7 +208,7 @@ ${skillsXml} : '' } -${config.getAgentRegistry().getDirectoryContext()}${skillsPrompt}`, +${config.getAgentRegistry().getDirectoryContext()}${skillsPrompt}${extensionsPrompt}`, primaryWorkflows_prefix: ` # Primary Workflows diff --git a/packages/core/src/telemetry/types.ts b/packages/core/src/telemetry/types.ts index 3ff143335fe..806060eb0b4 100644 --- a/packages/core/src/telemetry/types.ts +++ b/packages/core/src/telemetry/types.ts @@ -12,6 +12,7 @@ import type { } from '@google/genai'; import type { Config } from '../config/config.js'; import type { ApprovalMode } from '../policy/types.js'; +import type { ExtensionScope } from '../utils/extensionLoader.js'; import type { CompletedToolCall } from '../core/coreToolScheduler.js'; import { DiscoveredMCPTool } from '../tools/mcp-tool.js'; @@ -1424,7 +1425,7 @@ export class ExtensionEnableEvent implements BaseTelemetryEvent { extension_name: string, hashed_extension_name: string, extension_id: string, - settingScope: string, + settingScope: string | ExtensionScope, ) { this['event.name'] = 'extension_enable'; this['event.timestamp'] = new Date().toISOString(); @@ -1565,7 +1566,7 @@ export class ExtensionDisableEvent implements BaseTelemetryEvent { extension_name: string, hashed_extension_name: string, extension_id: string, - settingScope: string, + settingScope: string | ExtensionScope, ) { this['event.name'] = 'extension_disable'; this['event.timestamp'] = new Date().toISOString(); diff --git a/packages/core/src/tools/activate-extension.test.ts b/packages/core/src/tools/activate-extension.test.ts new file mode 100644 index 00000000000..e574d0f6688 --- /dev/null +++ b/packages/core/src/tools/activate-extension.test.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest'; +import { + ActivateExtensionTool, + type ActivateExtensionToolParams, +} from './activate-extension.js'; +import type { Config } from '../config/config.js'; +import type { MessageBus } from '../confirmation-bus/message-bus.js'; +import { createMockMessageBus } from '../test-utils/mock-message-bus.js'; +import { + ExtensionScope, + type ExtensionLoader, +} from '../utils/extensionLoader.js'; + +describe('ActivateExtensionTool', () => { + let mockConfig: Config; + let tool: ActivateExtensionTool; + let mockMessageBus: MessageBus; + let mockExtensionLoader: ExtensionLoader; + + beforeEach(() => { + mockMessageBus = createMockMessageBus(); + const extensions = [ + { + name: 'test-extension', + version: '1.0.0', + isActive: false, + path: '/path/to/test-extension', + contextFiles: [], + id: 'test-extension', + }, + { + name: 'active-extension', + version: '1.0.0', + isActive: true, + path: '/path/to/active-extension', + contextFiles: [], + id: 'active-extension', + }, + ]; + + mockExtensionLoader = { + getExtensions: vi.fn().mockReturnValue(extensions), + enableExtension: vi.fn(), + disableExtension: vi.fn(), + start: vi.fn(), + } as unknown as ExtensionLoader; + + mockConfig = { + getExtensionLoader: vi.fn().mockReturnValue(mockExtensionLoader), + } as unknown as Config; + + tool = new ActivateExtensionTool(mockConfig, mockMessageBus); + }); + + it('should build successfully with available disabled extensions', () => { + const params = { name: 'test-extension' }; + const invocation = tool.build(params); + expect(invocation).toBeDefined(); + expect(invocation.getDescription()).toBe( + 'Activate extension: test-extension', + ); + }); + + it('should throw error if extension is not in enum (including already active ones)', () => { + expect(() => + tool.build({ + name: 'active-extension', + } as unknown as ActivateExtensionToolParams), + ).toThrow(); + expect(() => + tool.build({ + name: 'non-existent', + } as unknown as ActivateExtensionToolParams), + ).toThrow(); + }); + + it('should activate a valid extension', async () => { + const params = { name: 'test-extension' }; + const invocation = tool.build(params); + const result = await invocation.execute(new AbortController().signal); + + expect(mockExtensionLoader.enableExtension).toHaveBeenCalledWith( + 'test-extension', + ExtensionScope.Session, + ); + expect(result.llmContent).toContain( + 'Extension "test-extension" activated successfully.', + ); + }); + + it('should handle activation error', async () => { + (mockExtensionLoader.enableExtension as unknown as Mock).mockRejectedValue( + new Error('Failed to enable'), + ); + + const params = { name: 'test-extension' }; + const invocation = tool.build(params); + const result = await invocation.execute(new AbortController().signal); + + expect(result.llmContent).toContain( + 'Error activating extension: Failed to enable', + ); + }); +}); diff --git a/packages/core/src/tools/activate-extension.ts b/packages/core/src/tools/activate-extension.ts new file mode 100644 index 00000000000..06ac4449349 --- /dev/null +++ b/packages/core/src/tools/activate-extension.ts @@ -0,0 +1,190 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { z } from 'zod'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +import type { MessageBus } from '../confirmation-bus/message-bus.js'; +import type { + ToolResult, + ToolCallConfirmationDetails, + ToolInvocation, + ToolConfirmationOutcome, +} from './tools.js'; +import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; +import type { Config } from '../config/config.js'; +import { ACTIVATE_EXTENSION_TOOL_NAME } from './tool-names.js'; +import { ToolErrorType } from './tool-error.js'; +import { ExtensionScope } from '../utils/extensionLoader.js'; + +/** + * Parameters for the ActivateExtension tool + */ +export interface ActivateExtensionToolParams { + /** + * The name of the extension to activate + */ + name: string; +} + +class ActivateExtensionToolInvocation extends BaseToolInvocation< + ActivateExtensionToolParams, + ToolResult +> { + constructor( + private config: Config, + params: ActivateExtensionToolParams, + messageBus: MessageBus, + _toolName?: string, + _toolDisplayName?: string, + ) { + super(params, messageBus, _toolName, _toolDisplayName); + } + + getDescription(): string { + return `Activate extension: ${this.params.name}`; + } + + protected override async getConfirmationDetails( + _abortSignal: AbortSignal, + ): Promise { + if (!this.messageBus) { + return false; + } + + const extensionName = this.params.name; + const extension = this.config + .getExtensionLoader() + .getExtensions() + .find((e) => e.name === extensionName); + + if (!extension) { + return false; + } + + const confirmationDetails: ToolCallConfirmationDetails = { + type: 'info', + title: `Activate Extension: ${extensionName}`, + prompt: `You are about to enable the extension **${extensionName}**.`, + onConfirm: async (outcome: ToolConfirmationOutcome) => { + await this.publishPolicyUpdate(outcome); + }, + }; + return confirmationDetails; + } + + async execute(_signal: AbortSignal): Promise { + const extensionName = this.params.name; + + const extensionLoader = this.config.getExtensionLoader(); + const extension = extensionLoader + .getExtensions() + .find((e) => e.name === extensionName); + + if (!extension) { + const extensions = extensionLoader + .getExtensions() + .filter((e) => !e.isActive); + const availableExtensions = extensions.map((s) => s.name).join(', '); + const errorMessage = `Extension "${extensionName}" not found. Available disabled extensions are: ${availableExtensions}`; + return { + llmContent: `Error: ${errorMessage}`, + returnDisplay: `Error: ${errorMessage}`, + error: { + message: errorMessage, + type: ToolErrorType.INVALID_TOOL_PARAMS, + }, + }; + } + + try { + // Use Session scope for dynamic activation so it doesn't persist beyond this session + await extensionLoader.enableExtension( + extensionName, + ExtensionScope.Session, + ); + + return { + llmContent: `Extension "${extensionName}" activated successfully.`, + returnDisplay: `Extension **${extensionName}** activated.`, + }; + } catch (e: unknown) { + const message = e instanceof Error ? e.message : String(e); + return { + llmContent: `Error activating extension: ${message}`, + returnDisplay: `Error activating extension: ${message}`, + error: { + message, + type: ToolErrorType.EXECUTION_FAILED, + }, + }; + } + } +} + +/** + * Implementation of the ActivateExtension tool logic + */ +export class ActivateExtensionTool extends BaseDeclarativeTool< + ActivateExtensionToolParams, + ToolResult +> { + static readonly Name = ACTIVATE_EXTENSION_TOOL_NAME; + + constructor( + private config: Config, + messageBus: MessageBus, + ) { + const extensions = config.getExtensionLoader().getExtensions(); + const disabledExtensions = extensions.filter((e) => !e.isActive); + const extensionNames = disabledExtensions.map((s) => s.name); + + let schema: z.ZodTypeAny; + if (extensionNames.length === 0) { + schema = z.object({ + name: z + .string() + .describe('No disabled extensions are currently available.'), + }); + } else { + schema = z.object({ + name: z + .enum(extensionNames as [string, ...string[]]) + .describe('The name of the extension to activate.'), + }); + } + + const availableExtensionsHint = + extensionNames.length > 0 + ? ` (Available: ${extensionNames.map((n) => `'${n}'`).join(', ')})` + : ''; + + super( + ActivateExtensionTool.Name, + 'Activate Extension', + `Activates a disabled extension by name${availableExtensionsHint}. Use this when you need functionality provided by an extension that is currently disabled (not in your active tools).`, + Kind.Other, + zodToJsonSchema(schema), + messageBus, + true, + false, + ); + } + + protected createInvocation( + params: ActivateExtensionToolParams, + messageBus: MessageBus, + _toolName?: string, + _toolDisplayName?: string, + ): ToolInvocation { + return new ActivateExtensionToolInvocation( + this.config, + params, + messageBus, + _toolName, + _toolDisplayName ?? 'Activate Extension', + ); + } +} diff --git a/packages/core/src/tools/tool-names.ts b/packages/core/src/tools/tool-names.ts index 41e4be8dec6..c61247f5625 100644 --- a/packages/core/src/tools/tool-names.ts +++ b/packages/core/src/tools/tool-names.ts @@ -22,6 +22,7 @@ export const LS_TOOL_NAME = 'list_directory'; export const MEMORY_TOOL_NAME = 'save_memory'; export const GET_INTERNAL_DOCS_TOOL_NAME = 'get_internal_docs'; export const ACTIVATE_SKILL_TOOL_NAME = 'activate_skill'; +export const ACTIVATE_EXTENSION_TOOL_NAME = 'activate_extension'; export const EDIT_TOOL_NAMES = new Set([EDIT_TOOL_NAME, WRITE_FILE_TOOL_NAME]); export const DELEGATE_TO_AGENT_TOOL_NAME = 'delegate_to_agent'; @@ -45,6 +46,7 @@ export const ALL_BUILTIN_TOOL_NAMES = [ LS_TOOL_NAME, MEMORY_TOOL_NAME, ACTIVATE_SKILL_TOOL_NAME, + ACTIVATE_EXTENSION_TOOL_NAME, DELEGATE_TO_AGENT_TOOL_NAME, ] as const; diff --git a/packages/core/src/utils/extensionLoader.ts b/packages/core/src/utils/extensionLoader.ts index 45ad37bfcc6..07475965e3d 100644 --- a/packages/core/src/utils/extensionLoader.ts +++ b/packages/core/src/utils/extensionLoader.ts @@ -29,6 +29,16 @@ export abstract class ExtensionLoader { */ abstract getExtensions(): GeminiCLIExtension[]; + /** + * Enables the extension with the given name for the specified scope. + */ + abstract enableExtension(name: string, scope: ExtensionScope): Promise; + + /** + * Disables the extension with the given name for the specified scope. + */ + abstract disableExtension(name: string, scope: ExtensionScope): Promise; + /** * Fully initializes all active extensions. * @@ -221,6 +231,18 @@ export interface ExtensionsStoppingEvent { completed: number; } +/** + * Represents the scope of an extension enablement/disablement. + * The string values must match `SettingScope` in the CLI package. + */ +export enum ExtensionScope { + User = 'User', + Workspace = 'Workspace', + System = 'System', + SystemDefaults = 'SystemDefaults', + Session = 'Session', +} + export class SimpleExtensionLoader extends ExtensionLoader { constructor( protected readonly extensions: GeminiCLIExtension[], @@ -233,6 +255,24 @@ export class SimpleExtensionLoader extends ExtensionLoader { return this.extensions; } + async enableExtension(_name: string, _scope: ExtensionScope): Promise { + const extension = this.extensions.find((e) => e.name === _name); + if (!extension) { + throw new Error(`Extension with name ${_name} does not exist.`); + } + extension.isActive = true; + await this.maybeStartExtension(extension); + } + + async disableExtension(_name: string, _scope: ExtensionScope): Promise { + const extension = this.extensions.find((e) => e.name === _name); + if (!extension) { + throw new Error(`Extension with name ${_name} does not exist.`); + } + extension.isActive = false; + await this.maybeStopExtension(extension); + } + /// Adds `extension` to the list of extensions and calls /// `maybeStartExtension`. /// diff --git a/schemas/settings.schema.json b/schemas/settings.schema.json index f7f134d2c99..20806527ce1 100644 --- a/schemas/settings.schema.json +++ b/schemas/settings.schema.json @@ -1359,6 +1359,13 @@ "default": false, "type": "boolean" }, + "dynamicExtensionLoading": { + "title": "Dynamic Extension Loading", + "description": "Enables the model to dynamically activate extensions (requires extensionReloading).", + "markdownDescription": "Enables the model to dynamically activate extensions (requires extensionReloading).\n\n- Category: `Experimental`\n- Requires restart: `yes`\n- Default: `false`", + "default": false, + "type": "boolean" + }, "jitContext": { "title": "JIT Context Loading", "description": "Enable Just-In-Time (JIT) context loading.",