From b351a8b92b4df5ffa36edbdd58cbd413177e77a4 Mon Sep 17 00:00:00 2001 From: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com> Date: Wed, 15 Oct 2025 22:10:08 -0700 Subject: [PATCH] feat: add banner to install Cline for CLI and experimental subagents feature (#6782) * feat: add banner to install Cline for CLI and experimental subagents feature * Update snapshots * Fix copy * Style fixes * A few small changes to cli detection, prompting, cleanup * Prompting tweaks and npm command update * Prompting, bug fix * Prompt changes around command syntax * Command parsing and flag substitution for easier subagent invocation * Added terminal output slider setting for subagents * Improved CLI subagent settings injection * Added max_consecutive_mistakes setting and cli flag * Terminal line limit added to enchanced terminal, prompting and settings tweaks * feat: Add OpenTelemetry settings schema and state infrastructure (1/5) (#6826) * feat: Add OpenTelemetry settings schema and state infrastructure (1/5) - Add 16 OpenTelemetry configuration fields to Settings interface - Add 17 OpenTelemetry fields to RemoteConfig schema - Add state persistence helpers for OpenTelemetry settings - Foundation for dynamic OpenTelemetry configuration Part 1 of 5 in the telemetry settings refactor series. * chore: add changeset for OpenTelemetry schema * fix: Address PR review feedback for OpenTelemetry settings - Remove | undefined from 8 OpenTelemetry fields with default values - Add default values in state-helpers.ts for all non-optional fields - Add OpenTelemetry field mappings to remote-config/utils.ts - Add comprehensive test coverage for OpenTelemetry fields in schema.test.ts - Update changeset terminology from 'Otel' to 'OpenTelemetry' Addresses feedback from: - sjf: Remote config transformation and test coverage - celestial-vault: Type cleanup and default values - Copilot: Terminology improvement * Prompting changes * Fixed system prompt empty sections issue, fixed rebase mistake * Added telemetry for CLI subagent use in IDEs * Platform aware banner, fixed settings layout issues * Post rebase fixes & changes to accomodate new terminal UI * Cline Icon SVG in ChatRow - WIP * Fixed outputLine limit issue * Fixed rebase merge conflict remnant * Rebase fix * Cleanup and changes to instructions for new CLI users * Added CLI documentation link * Small prompt adjustments * One more bullet point * Updated remaining npm install command * Updated subagent command format for CLI release spec * Added check to prevent subagents from getting subagent prompt * Added subagent slash command * Apply suggestion from @ellipsis-dev[bot] Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> * Remove workdir * Update src/core/prompts/system-prompt/variants/xs/overrides.ts Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> * removed logging * Updated expected version output * Removed checkCliInstallation check in getStateToPostToWebview * removed more logging * fix: force subagents to use terminal stuff --------- Co-authored-by: Kevin Bond Co-authored-by: Daniel Steigman <35793213+NightTrek@users.noreply.github.com> Co-authored-by: Andrei Eternal <206184+Garoth@users.noreply.github.com> Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com> Co-authored-by: Arafatkatze --- proto/cline/state.proto | 3 + proto/host/workspace.proto | 14 +- src/core/controller/index.ts | 6 + .../controller/state/checkCliInstallation.ts | 18 ++ src/core/controller/state/installClineCli.ts | 38 ++++ .../state/updateCliBannerVersion.ts | 18 ++ .../controller/state/updateSettings.test.ts | 173 ++++++++++++++ src/core/controller/state/updateSettings.ts | 9 + src/core/prompts/commands.ts | 9 + .../system-prompt/components/cli_subagents.ts | 60 +++++ .../prompts/system-prompt/components/index.ts | 5 + .../system-prompt/registry/PromptBuilder.ts | 5 + .../system-prompt/templates/placeholders.ts | 1 + src/core/prompts/system-prompt/types.ts | 2 + .../system-prompt/variants/config.template.ts | 2 + .../system-prompt/variants/generic/config.ts | 1 + .../variants/generic/template.ts | 4 + .../system-prompt/variants/gpt-5/config.ts | 1 + .../system-prompt/variants/gpt-5/template.ts | 4 + .../system-prompt/variants/next-gen/config.ts | 1 + .../variants/next-gen/template.ts | 4 + .../system-prompt/variants/xs/config.ts | 1 + .../system-prompt/variants/xs/overrides.ts | 15 ++ .../system-prompt/variants/xs/template.ts | 2 + src/core/slash-commands/index.ts | 4 +- src/core/storage/utils/state-helpers.ts | 3 + src/core/task/index.ts | 67 +++++- .../workspace/executeCommandInTerminal.ts | 40 ++++ .../cli-subagents/subagent_command.ts | 78 +++++++ src/shared/ExtensionMessage.ts | 1 + src/shared/storage/state-keys.ts | 1 + src/utils/cli-detector.ts | 51 +++++ webview-ui/src/components/chat/ChatRow.tsx | 96 +++++++- .../components/layout/WelcomeSection.tsx | 12 +- .../components/common/CliInstallBanner.tsx | 215 ++++++++++++++++++ .../SubagentOutputLineLimitSlider.tsx | 38 ++++ .../sections/FeatureSettingsSection.tsx | 131 ++++++++++- .../src/context/ExtensionStateContext.tsx | 2 + webview-ui/src/utils/slash-commands.ts | 5 + 39 files changed, 1125 insertions(+), 15 deletions(-) create mode 100644 src/core/controller/state/checkCliInstallation.ts create mode 100644 src/core/controller/state/installClineCli.ts create mode 100644 src/core/controller/state/updateCliBannerVersion.ts create mode 100644 src/core/controller/state/updateSettings.test.ts create mode 100644 src/core/prompts/system-prompt/components/cli_subagents.ts create mode 100644 src/hosts/vscode/hostbridge/workspace/executeCommandInTerminal.ts create mode 100644 src/integrations/cli-subagents/subagent_command.ts create mode 100644 src/utils/cli-detector.ts create mode 100644 webview-ui/src/components/common/CliInstallBanner.tsx create mode 100644 webview-ui/src/components/settings/SubagentOutputLineLimitSlider.tsx diff --git a/proto/cline/state.proto b/proto/cline/state.proto index bdc541af..c06f412d 100644 --- a/proto/cline/state.proto +++ b/proto/cline/state.proto @@ -24,6 +24,9 @@ service StateService { rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty); rpc updateInfoBannerVersion(Int64Request) returns (Empty); rpc updateModelBannerVersion(Int64Request) returns (Empty); + rpc updateCliBannerVersion(Int64Request) returns (Empty); + rpc installClineCli(EmptyRequest) returns (Empty); + rpc checkCliInstallation(EmptyRequest) returns (Boolean); rpc getProcessInfo(EmptyRequest) returns (ProcessInfo); } diff --git a/proto/host/workspace.proto b/proto/host/workspace.proto index d946b8e1..68bc0b95 100644 --- a/proto/host/workspace.proto +++ b/proto/host/workspace.proto @@ -31,6 +31,9 @@ service WorkspaceService { // Opens and focuses the terminal panel. rpc openTerminalPanel(OpenTerminalRequest) returns (OpenTerminalResponse); + + // Executes a command in a new terminal + rpc executeCommandInTerminal(ExecuteCommandInTerminalRequest) returns (ExecuteCommandInTerminalResponse); } message GetWorkspacePathsRequest { @@ -93,4 +96,13 @@ message OpenInFileExplorerPanelResponse {} message OpenClineSidebarPanelRequest {} message OpenClineSidebarPanelResponse {} message OpenTerminalRequest {} -message OpenTerminalResponse {} \ No newline at end of file +message OpenTerminalResponse {} + +// Execute a command in the terminal +message ExecuteCommandInTerminalRequest { + string command = 1; // The command to execute +} + +message ExecuteCommandInTerminalResponse { + bool success = 1; // Whether the command was successfully sent to the terminal +} diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 07c9d119..704c6556 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -49,6 +49,7 @@ import { PersistenceErrorEvent, StateManager } from "../storage/StateManager" import { Task } from "../task" import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" import { appendClineStealthModels } from "./models/refreshOpenRouterModels" +import { checkCliInstallation } from "./state/checkCliInstallation" import { sendStateUpdate } from "./state/subscribeToState" import { sendChatButtonClickedEvent } from "./ui/subscribeToChatButtonClicked" @@ -164,6 +165,9 @@ export class Controller { cleanupLegacyCheckpoints().catch((error) => { console.error("Failed to cleanup legacy checkpoints:", error) }) + + // Check CLI installation status once on startup + checkCliInstallation(this) } /* @@ -855,6 +859,7 @@ export class Controller { const favoritedModelIds = this.stateManager.getGlobalStateKey("favoritedModelIds") const lastDismissedInfoBannerVersion = this.stateManager.getGlobalStateKey("lastDismissedInfoBannerVersion") || 0 const lastDismissedModelBannerVersion = this.stateManager.getGlobalStateKey("lastDismissedModelBannerVersion") || 0 + const lastDismissedCliBannerVersion = this.stateManager.getGlobalStateKey("lastDismissedCliBannerVersion") || 0 const subagentsEnabled = this.stateManager.getGlobalSettingsKey("subagentsEnabled") const localClineRulesToggles = this.stateManager.getWorkspaceStateKey("localClineRulesToggles") @@ -949,6 +954,7 @@ export class Controller { lastDismissedInfoBannerVersion, lastDismissedModelBannerVersion, remoteConfigSettings: this.stateManager.getRemoteConfigSettings(), + lastDismissedCliBannerVersion, subagentsEnabled, } } diff --git a/src/core/controller/state/checkCliInstallation.ts b/src/core/controller/state/checkCliInstallation.ts new file mode 100644 index 00000000..bf7cd1df --- /dev/null +++ b/src/core/controller/state/checkCliInstallation.ts @@ -0,0 +1,18 @@ +import { Boolean } from "@shared/proto/cline/common" +import { isClineCliInstalled } from "@/utils/cli-detector" +import { Controller } from ".." + +/** + * Check if the Cline CLI is installed + * @param controller The controller instance + * @returns Boolean indicating if CLI is installed + */ +export async function checkCliInstallation(_controller: Controller): Promise { + try { + const isInstalled = await isClineCliInstalled() + return Boolean.create({ value: isInstalled }) + } catch (error) { + console.error("Failed to check CLI installation:", error) + return Boolean.create({ value: false }) + } +} diff --git a/src/core/controller/state/installClineCli.ts b/src/core/controller/state/installClineCli.ts new file mode 100644 index 00000000..db8c37a0 --- /dev/null +++ b/src/core/controller/state/installClineCli.ts @@ -0,0 +1,38 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { ShowMessageType } from "@shared/proto/host/window" +import { ExecuteCommandInTerminalRequest } from "@shared/proto/host/workspace" +import { HostProvider } from "@/hosts/host-provider" +import { Controller } from ".." + +/** + * Handles the installation of the Cline CLI tool + * @param controller The controller instance + * @param _request The empty request + * @returns Empty response + */ +export async function installClineCli(_controller: Controller, _request: EmptyRequest): Promise { + const installCommand = "npm install -g cline" + + try { + // Use the HostProvider to execute the command in a terminal + // This works across different platforms (VSCode, JetBrains, etc.) + const response = await HostProvider.workspace.executeCommandInTerminal( + ExecuteCommandInTerminalRequest.create({ + command: installCommand, + }), + ) + + if (!response.success) { + throw new Error("Failed to execute command in terminal") + } + } catch (error) { + console.error("Error executing CLI installation:", error) + await HostProvider.window.showMessage({ + type: ShowMessageType.ERROR, + message: `Failed to start CLI installation: ${error instanceof Error ? error.message : "Unknown error"}`, + options: { items: [] }, + }) + } + + return Empty.create() +} diff --git a/src/core/controller/state/updateCliBannerVersion.ts b/src/core/controller/state/updateCliBannerVersion.ts new file mode 100644 index 00000000..3af01873 --- /dev/null +++ b/src/core/controller/state/updateCliBannerVersion.ts @@ -0,0 +1,18 @@ +import { Empty, Int64Request } from "@shared/proto/cline/common" +import { Controller } from ".." + +/** + * Updates the CLI banner version to hide it + * @param controller The controller instance + * @param request The request containing the version number + * @returns Empty response + */ +export async function updateCliBannerVersion(controller: Controller, request: Int64Request): Promise { + // Save the banner version to global state to hide it + controller.stateManager.setGlobalState("lastDismissedCliBannerVersion", request.value ?? 1) + + // Update webview + await controller.postStateToWebview() + + return Empty.create() +} diff --git a/src/core/controller/state/updateSettings.test.ts b/src/core/controller/state/updateSettings.test.ts new file mode 100644 index 00000000..231d6844 --- /dev/null +++ b/src/core/controller/state/updateSettings.test.ts @@ -0,0 +1,173 @@ +import { UpdateSettingsRequest } from "@shared/proto/cline/state" +import * as assert from "assert" +import * as sinon from "sinon" +import { Controller } from ".." +import { updateSettings } from "./updateSettings" + +// Mock telemetryService +const telemetryServiceMock = { + captureSubagentToggle: sinon.stub(), +} + +describe("updateSettings platform validation", () => { + let mockController: Controller + let originalPlatform: NodeJS.Platform + + beforeEach(() => { + // Store original platform + originalPlatform = process.platform + + // Create mock controller + mockController = { + stateManager: { + getGlobalSettingsKey: sinon.stub(), + setGlobalState: sinon.stub(), + setApiConfiguration: sinon.stub(), + }, + postStateToWebview: sinon.stub().resolves({}), + task: undefined, + updateTelemetrySetting: sinon.stub(), + } as unknown as Controller + + // Clear telemetry service mock + telemetryServiceMock.captureSubagentToggle.reset() + }) + + afterEach(() => { + // Restore original platform + Object.defineProperty(process, "platform", { + value: originalPlatform, + writable: true, + configurable: true, + }) + sinon.restore() + }) + + it("should allow enabling subagents on macOS (darwin)", async () => { + // Set platform to macOS + Object.defineProperty(process, "platform", { value: "darwin" }) + + ;(mockController.stateManager.getGlobalSettingsKey as sinon.SinonStub).returns(false) + + const request = UpdateSettingsRequest.create({ + subagentsEnabled: true, + }) + + // Should not throw + await updateSettings(mockController, request) + + assert.ok( + (mockController.stateManager.setGlobalState as sinon.SinonStub).calledWith("subagentsEnabled", true), + "Should enable subagents on macOS", + ) + }) + + it("should throw error when trying to enable subagents on Windows", async () => { + // Set platform to Windows + Object.defineProperty(process, "platform", { value: "win32" }) + + ;(mockController.stateManager.getGlobalSettingsKey as sinon.SinonStub).returns(false) + + const request = UpdateSettingsRequest.create({ + subagentsEnabled: true, + }) + + try { + await updateSettings(mockController, request) + assert.fail("Should have thrown an error") + } catch (error) { + assert.strictEqual( + (error as Error).message, + "CLI subagents are only supported on macOS platforms", + "Should throw platform restriction error", + ) + } + + assert.ok( + !(mockController.stateManager.setGlobalState as sinon.SinonStub).called, + "Should not call setGlobalState when platform validation fails", + ) + }) + + it("should throw error when trying to enable subagents on Linux", async () => { + // Set platform to Linux + Object.defineProperty(process, "platform", { value: "linux" }) + + ;(mockController.stateManager.getGlobalSettingsKey as sinon.SinonStub).returns(false) + + const request = UpdateSettingsRequest.create({ + subagentsEnabled: true, + }) + + try { + await updateSettings(mockController, request) + assert.fail("Should have thrown an error") + } catch (error) { + assert.strictEqual( + (error as Error).message, + "CLI subagents are only supported on macOS platforms", + "Should throw platform restriction error", + ) + } + + assert.ok( + !(mockController.stateManager.setGlobalState as sinon.SinonStub).called, + "Should not call setGlobalState when platform validation fails", + ) + }) + + it("should allow disabling subagents on any platform", async () => { + // Test on Windows + Object.defineProperty(process, "platform", { value: "win32" }) + + ;(mockController.stateManager.getGlobalSettingsKey as sinon.SinonStub).returns(true) + + const request = UpdateSettingsRequest.create({ + subagentsEnabled: false, + }) + + // Should not throw + await updateSettings(mockController, request) + + assert.ok( + (mockController.stateManager.setGlobalState as sinon.SinonStub).calledWith("subagentsEnabled", false), + "Should allow disabling subagents on any platform", + ) + }) + + it("should allow keeping subagents disabled on non-macOS platforms", async () => { + // Test on Windows with subagents already disabled + Object.defineProperty(process, "platform", { value: "win32" }) + + ;(mockController.stateManager.getGlobalSettingsKey as sinon.SinonStub).returns(false) + + const request = UpdateSettingsRequest.create({ + subagentsEnabled: false, + }) + + // Should not throw + await updateSettings(mockController, request) + + assert.ok( + (mockController.stateManager.setGlobalState as sinon.SinonStub).calledWith("subagentsEnabled", false), + "Should allow keeping subagents disabled on non-macOS platforms", + ) + }) + + it("should not perform platform validation when subagentsEnabled is undefined", async () => { + // Test on Windows but don't try to change subagents setting + Object.defineProperty(process, "platform", { value: "win32" }) + + const request = UpdateSettingsRequest.create({ + strictPlanModeEnabled: true, // Some other setting + }) + + // Should not throw error since subagentsEnabled is not being changed + await updateSettings(mockController, request) + + assert.ok( + (mockController.postStateToWebview as sinon.SinonStub).called, + "Should complete successfully when subagentsEnabled is not being changed", + ) + }) +}) diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index 916944dd..22c77f89 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -159,6 +159,14 @@ export async function updateSettings(controller: Controller, request: UpdateSett ) } + // Update subagent terminal output line limit + if (request.subagentTerminalOutputLineLimit !== undefined) { + controller.stateManager.setGlobalState( + "subagentTerminalOutputLineLimit", + Number(request.subagentTerminalOutputLineLimit), + ) + } + // Update max consecutive mistakes if (request.maxConsecutiveMistakes !== undefined) { controller.stateManager.setGlobalState("maxConsecutiveMistakes", Number(request.maxConsecutiveMistakes)) @@ -331,6 +339,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett if (wasEnabled !== isEnabled) { telemetryService.captureSubagentToggle(isEnabled) } + controller.stateManager.setGlobalState("subagentsEnabled", !!request.subagentsEnabled) } // Post updated state to webview diff --git a/src/core/prompts/commands.ts b/src/core/prompts/commands.ts index 2582ce36..8280d47e 100644 --- a/src/core/prompts/commands.ts +++ b/src/core/prompts/commands.ts @@ -199,6 +199,15 @@ Below is the user's input when they indicated that they wanted to submit a Githu \n ` +export const subagentToolResponse = () => + ` +The user has requested to invoke a Cline CLI subagent with the context below. You should execute a subagent command to handle this request using the CLI subagents feature. + +Transform the user's request into a subagent command by executing: +cline "" +\n +` + export const deepPlanningToolResponse = (focusChainSettings?: { enabled: boolean }) => { const detectedShell = getShell() diff --git a/src/core/prompts/system-prompt/components/cli_subagents.ts b/src/core/prompts/system-prompt/components/cli_subagents.ts new file mode 100644 index 00000000..2bbd25d9 --- /dev/null +++ b/src/core/prompts/system-prompt/components/cli_subagents.ts @@ -0,0 +1,60 @@ +import { SystemPromptSection } from "../templates/placeholders" +import { TemplateEngine } from "../templates/TemplateEngine" +import type { PromptVariant, SystemPromptContext } from "../types" + +const getCliSubagentsTemplateText = (_context: SystemPromptContext) => `USING THE CLINE CLI TOOL + +The Cline CLI tool can be used to assign Cline AI agents with focused tasks. This can be used to keep you focused by delegating information-gathering and exploration to separate Cline instances. Use the Cline CLI tool to research large codebases, explore file structures, gather information from multiple files, analyze dependencies, or summarize code sections when the complete context may be too large or overwhelming. + +## Creating Cline AI agents + +Cline AI agents may be referred to as agents, subagents, or subtasks. Requests may not specifically invoke agents, but you may invoke them directly if warranted. Unless you are specifically asked to use this tool, only create agents when it seems likely you may be exploring across 10 or more files. If users specifically ask that you use this tool, you then must use this tool. Do not use subagents for editing code or executing commands- they should only be used for reading and research to help you better answer questions or build useful context for future coding tasks. If you are performing a search via search_files or the terminal (grep etc.), and the results are long and overwhleming, it is reccomended that you switch to use Cline CLI agents to perform this task. You may perform code edits directly using the write_to_file and replace_in_file tools, and commands using the execute_command tool. + +## Command Syntax + +You must use the following command syntax for creating Cline AI agents: + +\`\`\`bash +cline "your prompt here" +\`\`\` + +## Examples of how you might use this tool + +\`\`\`bash +# Find specific patterns +cline "find all React components that use the useState hook and list their names" + +# Analyze code structure +cline "analyze the authentication flow. Reverse trace through all relevant functions and methods, and provide a summary of how it works. Include file/class references in your summary." + +# Gather targeted information +cline "list all API endpoints and their HTTP methods" + +# Summarize directories +cline "summarize the purpose of all files in the src/services directory" + +# Research implementations +cline "find how error handling is implemented across the application" +\`\`\` + +## Tips +- Request brief, technically dense summaries over full file dumps. +- Be specific with your instructions to get focused results. +- Request summaries rather than full file contents. Encourage the agent to be brief, but specific and technically dense with their response. +- If files you want to read are large or complicated, use Cline CLI agents for exploration before instead of reading these files.` + +export async function getCliSubagentsSection(variant: PromptVariant, context: SystemPromptContext): Promise { + // If this is a CLI subagent, don't include CLI subagent instructions to prevent nesting/allignment concerns + if (context.isCliSubagent) { + return undefined + } + + // Only include this section if CLI is installed and subagents are enabled + if (!context.isSubagentsEnabledAndCliInstalled) { + return undefined + } + + const template = variant.componentOverrides?.[SystemPromptSection.CLI_SUBAGENTS]?.template || getCliSubagentsTemplateText + + return new TemplateEngine().resolve(template, context, {}) +} diff --git a/src/core/prompts/system-prompt/components/index.ts b/src/core/prompts/system-prompt/components/index.ts index b5073ca8..f9a0533f 100644 --- a/src/core/prompts/system-prompt/components/index.ts +++ b/src/core/prompts/system-prompt/components/index.ts @@ -3,6 +3,7 @@ import { getActVsPlanModeSection } from "./act_vs_plan_mode" import { getAgentRoleSection } from "./agent_role" import { getTodoListSection } from "./auto_todo" import { getCapabilitiesSection } from "./capabilities" +import { getCliSubagentsSection } from "./cli_subagents" import { getEditingFilesSection } from "./editing_files" import { getFeedbackSection } from "./feedback" import { getMcp } from "./mcp" @@ -43,6 +44,10 @@ export function getSystemPromptComponents() { id: SystemPromptSection.ACT_VS_PLAN, fn: getActVsPlanModeSection, }, + { + id: SystemPromptSection.CLI_SUBAGENTS, + fn: getCliSubagentsSection, + }, { id: SystemPromptSection.FEEDBACK, fn: getFeedbackSection, diff --git a/src/core/prompts/system-prompt/registry/PromptBuilder.ts b/src/core/prompts/system-prompt/registry/PromptBuilder.ts index 6ba72bb7..7cb99848 100644 --- a/src/core/prompts/system-prompt/registry/PromptBuilder.ts +++ b/src/core/prompts/system-prompt/registry/PromptBuilder.ts @@ -94,6 +94,9 @@ export class PromptBuilder { .trim() // Remove leading/trailing whitespace .replace(/====+\s*$/, "") // Remove trailing ==== after trim .replace(/\n====+\s*\n+\s*====+\n/g, "\n====\n") // Remove empty sections between separators + .replace(/====\s*\n\s*====\s*\n/g, "====\n") // Remove consecutive empty sections + .replace(/^##\s*$[\r\n]*/gm, "") // Remove empty section headers (## with no content) + .replace(/\n##\s*$[\r\n]*/gm, "") // Remove empty section headers that appear mid-document .replace(/====+\n(?!\n)([^\n])/g, (match, nextChar, offset, string) => { // Add extra newline after ====+ if not already followed by a newline // Exception: preserve single newlines when ====+ appears to be part of diff-like content @@ -111,6 +114,8 @@ export class PromptBuilder { const isDiffLike = /SEARCH|REPLACE|\+\+\+\+\+\+\+|-------/.test(beforeContext + afterContext) return isDiffLike ? match : prevChar + "\n\n" + match.substring(1).replace(/\n/, "") }) + .replace(/\n\s*\n\s*\n/g, "\n\n") // Clean up any multiple empty lines created by header removal + .trim() // Final trim to remove any whitespace added by regex operations } getBuildMetadata(): { diff --git a/src/core/prompts/system-prompt/templates/placeholders.ts b/src/core/prompts/system-prompt/templates/placeholders.ts index b7ed48af..c1ad14ca 100644 --- a/src/core/prompts/system-prompt/templates/placeholders.ts +++ b/src/core/prompts/system-prompt/templates/placeholders.ts @@ -5,6 +5,7 @@ export enum SystemPromptSection { MCP = "MCP_SECTION", EDITING_FILES = "EDITING_FILES_SECTION", ACT_VS_PLAN = "ACT_VS_PLAN_SECTION", + CLI_SUBAGENTS = "CLI_SUBAGENTS_SECTION", TODO = "TODO_SECTION", CAPABILITIES = "CAPABILITIES_SECTION", RULES = "RULES_SECTION", diff --git a/src/core/prompts/system-prompt/types.ts b/src/core/prompts/system-prompt/types.ts index 12c60924..5ba89285 100644 --- a/src/core/prompts/system-prompt/types.ts +++ b/src/core/prompts/system-prompt/types.ts @@ -108,6 +108,8 @@ export interface SystemPromptContext { readonly yoloModeToggled?: boolean readonly isMultiRootEnabled?: boolean readonly workspaceRoots?: Array<{ path: string; name: string; vcs?: string }> + readonly isSubagentsEnabledAndCliInstalled?: boolean + readonly isCliSubagent?: boolean } /** diff --git a/src/core/prompts/system-prompt/variants/config.template.ts b/src/core/prompts/system-prompt/variants/config.template.ts index e7379e4c..0b333f0c 100644 --- a/src/core/prompts/system-prompt/variants/config.template.ts +++ b/src/core/prompts/system-prompt/variants/config.template.ts @@ -35,6 +35,7 @@ export const config: Omit = createVariant(ModelFamily.GENER SystemPromptSection.MCP, SystemPromptSection.EDITING_FILES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.TODO, SystemPromptSection.CAPABILITIES, SystemPromptSection.RULES, @@ -121,6 +122,7 @@ export const createAdvancedVariant = (family: ModelFamily) => SystemPromptSection.MCP, SystemPromptSection.EDITING_FILES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.TODO, SystemPromptSection.CAPABILITIES, SystemPromptSection.FEEDBACK, diff --git a/src/core/prompts/system-prompt/variants/generic/config.ts b/src/core/prompts/system-prompt/variants/generic/config.ts index f279013b..ceeabec0 100644 --- a/src/core/prompts/system-prompt/variants/generic/config.ts +++ b/src/core/prompts/system-prompt/variants/generic/config.ts @@ -21,6 +21,7 @@ export const config = createVariant(ModelFamily.GENERIC) SystemPromptSection.MCP, SystemPromptSection.EDITING_FILES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.TODO, SystemPromptSection.CAPABILITIES, SystemPromptSection.RULES, diff --git a/src/core/prompts/system-prompt/variants/generic/template.ts b/src/core/prompts/system-prompt/variants/generic/template.ts index 2c1504fd..e38f4d7e 100644 --- a/src/core/prompts/system-prompt/variants/generic/template.ts +++ b/src/core/prompts/system-prompt/variants/generic/template.ts @@ -22,6 +22,10 @@ export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} ==== +{{${SystemPromptSection.CLI_SUBAGENTS}}} + +==== + {{${SystemPromptSection.TASK_PROGRESS}}} ==== diff --git a/src/core/prompts/system-prompt/variants/gpt-5/config.ts b/src/core/prompts/system-prompt/variants/gpt-5/config.ts index bce9b9e2..fa8b10b6 100644 --- a/src/core/prompts/system-prompt/variants/gpt-5/config.ts +++ b/src/core/prompts/system-prompt/variants/gpt-5/config.ts @@ -23,6 +23,7 @@ export const config = createVariant(ModelFamily.GPT_5) SystemPromptSection.MCP, SystemPromptSection.EDITING_FILES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.TASK_PROGRESS, SystemPromptSection.CAPABILITIES, SystemPromptSection.FEEDBACK, diff --git a/src/core/prompts/system-prompt/variants/gpt-5/template.ts b/src/core/prompts/system-prompt/variants/gpt-5/template.ts index bc882b72..1b9ab7a1 100644 --- a/src/core/prompts/system-prompt/variants/gpt-5/template.ts +++ b/src/core/prompts/system-prompt/variants/gpt-5/template.ts @@ -23,6 +23,10 @@ export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} ==== +{{${SystemPromptSection.CLI_SUBAGENTS}}} + +==== + {{${SystemPromptSection.TASK_PROGRESS}}} ==== diff --git a/src/core/prompts/system-prompt/variants/next-gen/config.ts b/src/core/prompts/system-prompt/variants/next-gen/config.ts index 552782ef..f445a856 100644 --- a/src/core/prompts/system-prompt/variants/next-gen/config.ts +++ b/src/core/prompts/system-prompt/variants/next-gen/config.ts @@ -23,6 +23,7 @@ export const config = createVariant(ModelFamily.NEXT_GEN) SystemPromptSection.MCP, SystemPromptSection.EDITING_FILES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.TASK_PROGRESS, SystemPromptSection.CAPABILITIES, SystemPromptSection.FEEDBACK, diff --git a/src/core/prompts/system-prompt/variants/next-gen/template.ts b/src/core/prompts/system-prompt/variants/next-gen/template.ts index bc882b72..1b9ab7a1 100644 --- a/src/core/prompts/system-prompt/variants/next-gen/template.ts +++ b/src/core/prompts/system-prompt/variants/next-gen/template.ts @@ -23,6 +23,10 @@ export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} ==== +{{${SystemPromptSection.CLI_SUBAGENTS}}} + +==== + {{${SystemPromptSection.TASK_PROGRESS}}} ==== diff --git a/src/core/prompts/system-prompt/variants/xs/config.ts b/src/core/prompts/system-prompt/variants/xs/config.ts index 24fa10ea..1a913c7e 100644 --- a/src/core/prompts/system-prompt/variants/xs/config.ts +++ b/src/core/prompts/system-prompt/variants/xs/config.ts @@ -21,6 +21,7 @@ export const config = createVariant(ModelFamily.XS) SystemPromptSection.AGENT_ROLE, SystemPromptSection.RULES, SystemPromptSection.ACT_VS_PLAN, + SystemPromptSection.CLI_SUBAGENTS, SystemPromptSection.CAPABILITIES, SystemPromptSection.EDITING_FILES, SystemPromptSection.OBJECTIVE, diff --git a/src/core/prompts/system-prompt/variants/xs/overrides.ts b/src/core/prompts/system-prompt/variants/xs/overrides.ts index 9ff1691d..924320aa 100644 --- a/src/core/prompts/system-prompt/variants/xs/overrides.ts +++ b/src/core/prompts/system-prompt/variants/xs/overrides.ts @@ -40,6 +40,18 @@ const XS_OBJECTIVES = `EXECUTION FLOW - Prefer replace_in_file; respect final formatted state. - When all steps succeed and are confirmed, call attempt_completion (optional demo command).` +const XS_CLI_SUBAGENTS = `USING THE CLINE CLI TOOL + +The Cline CLI tool is installed and available for you to use to handle focused tasks without polluting your main context window. This can be done using +\`\`\`bash +cline t o "your prompt here" + +This must only be used for searching and exploring code. It cannot be used to edit files or execute commands. +Example: + # Find specific patterns + cline t o "find all React components that use the useState hook and list their names" +\`\`\`` + export const xsComponentOverrides: PromptVariant["componentOverrides"] = { [SystemPromptSection.AGENT_ROLE]: { template: @@ -60,6 +72,9 @@ export const xsComponentOverrides: PromptVariant["componentOverrides"] = { [SystemPromptSection.RULES]: { template: XS_RULES, }, + [SystemPromptSection.CLI_SUBAGENTS]: { + template: XS_CLI_SUBAGENTS, + }, [SystemPromptSection.ACT_VS_PLAN]: { template: XS_ACT_PLAN_MODE, }, diff --git a/src/core/prompts/system-prompt/variants/xs/template.ts b/src/core/prompts/system-prompt/variants/xs/template.ts index 5597792d..5be24016 100644 --- a/src/core/prompts/system-prompt/variants/xs/template.ts +++ b/src/core/prompts/system-prompt/variants/xs/template.ts @@ -6,6 +6,8 @@ export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} ## {{${SystemPromptSection.ACT_VS_PLAN}}} +## {{${SystemPromptSection.CLI_SUBAGENTS}}} + ## {{${SystemPromptSection.CAPABILITIES}}} ## {{${SystemPromptSection.EDITING_FILES}}} diff --git a/src/core/slash-commands/index.ts b/src/core/slash-commands/index.ts index 8d180683..c72e5782 100644 --- a/src/core/slash-commands/index.ts +++ b/src/core/slash-commands/index.ts @@ -7,6 +7,7 @@ import { newRuleToolResponse, newTaskToolResponse, reportBugToolResponse, + subagentToolResponse, } from "../prompts/commands" /** @@ -20,7 +21,7 @@ export async function parseSlashCommands( ulid: string, focusChainSettings?: { enabled: boolean }, ): Promise<{ processedText: string; needsClinerulesFileCheck: boolean }> { - const SUPPORTED_DEFAULT_COMMANDS = ["newtask", "smol", "compact", "newrule", "reportbug", "deep-planning"] + const SUPPORTED_DEFAULT_COMMANDS = ["newtask", "smol", "compact", "newrule", "reportbug", "deep-planning", "subagent"] const commandReplacements: Record = { newtask: newTaskToolResponse(), @@ -29,6 +30,7 @@ export async function parseSlashCommands( newrule: newRuleToolResponse(), reportbug: reportBugToolResponse(), "deep-planning": deepPlanningToolResponse(focusChainSettings), + subagent: subagentToolResponse(), } // this currently allows matching prepended whitespace prior to /slash-command diff --git a/src/core/storage/utils/state-helpers.ts b/src/core/storage/utils/state-helpers.ts index c179a613..b7963958 100644 --- a/src/core/storage/utils/state-helpers.ts +++ b/src/core/storage/utils/state-helpers.ts @@ -251,6 +251,8 @@ export async function readGlobalStateFromDisk(context: ExtensionContext): Promis const lastDismissedModelBannerVersion = context.globalState.get< GlobalStateAndSettings["lastDismissedModelBannerVersion"] >("lastDismissedModelBannerVersion") + const lastDismissedCliBannerVersion = + context.globalState.get("lastDismissedCliBannerVersion") const qwenCodeOauthPath = context.globalState.get("qwenCodeOauthPath") const customPrompt = context.globalState.get("customPrompt") const autoCondenseThreshold = @@ -614,6 +616,7 @@ export async function readGlobalStateFromDisk(context: ExtensionContext): Promis subagentsEnabled: subagentsEnabled ?? false, lastDismissedInfoBannerVersion: lastDismissedInfoBannerVersion ?? 0, lastDismissedModelBannerVersion: lastDismissedModelBannerVersion ?? 0, + lastDismissedCliBannerVersion: lastDismissedCliBannerVersion ?? 0, // Multi-root workspace support workspaceRoots, primaryRootIndex: primaryRootIndex ?? 0, diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 1855d718..635333cf 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -78,9 +78,11 @@ import * as vscode from "vscode" import type { SystemPromptContext } from "@/core/prompts/system-prompt" import { getSystemPrompt } from "@/core/prompts/system-prompt" import { HostProvider } from "@/hosts/host-provider" +import { isSubagentCommand, transformClineCommand } from "@/integrations/cli-subagents/subagent_command" import { ClineError, ClineErrorType, ErrorService } from "@/services/error" import { TerminalHangStage, TerminalUserInterventionAction, telemetryService } from "@/services/telemetry" import { ShowMessageType } from "@/shared/proto/index.host" +import { isClineCliInstalled, isCliSubagentContext } from "@/utils/cli-detector" import { isInTestMode } from "../../services/test/TestMode" import { ensureLocalClineDirExists } from "../context/instructions/user-instructions/rule-helpers" import { refreshWorkflowToggles } from "../context/instructions/user-instructions/workflows" @@ -1150,6 +1152,15 @@ export class Task { } async executeCommandTool(command: string, timeoutSeconds: number | undefined): Promise<[boolean, ToolResponse]> { + // For Cline CLI subagents, we want to parse and process the command to ensure flags are correct + const isSubagent = isSubagentCommand(command) + + if (transformClineCommand(command) !== command && isSubagent) { + command = transformClineCommand(command) + } + + const subAgentStartTime = isSubagent ? performance.now() : 0 + Logger.info("IS_TEST: " + isInTestMode()) // Check if we're in test mode @@ -1158,11 +1169,33 @@ export class Task { Logger.info("Executing command in Node: " + command) return this.executeCommandInNode(command) } + + // CRITICAL: CLI subagent commands MUST use VSCode terminal mode (not backgroundExec) + // Reason: Creates a three-way deadlock when using backgroundExec: + // 1. Extension blocks in 'await process' waiting for CLI to exit + // 2. CLI blocks waiting for gRPC messages from its child gRPC server + // 3. gRPC server (child of CLI) needs extension to process tasks + // Solution: Always use VSCode terminal for CLI commands + const useVscodeTerminal = isSubagent + Logger.info("Executing command in terminal: " + command) - const terminalInfo = await this.terminalManager.getOrCreateTerminal(this.cwd) + let terminalManager: TerminalManager + if (useVscodeTerminal) { + // Create a VSCode TerminalManager for CLI subagents + terminalManager = new TerminalManager() + terminalManager.setShellIntegrationTimeout(this.terminalManager["shellIntegrationTimeout"] || 4000) + terminalManager.setTerminalReuseEnabled(this.terminalManager["terminalReuseEnabled"] ?? true) + terminalManager.setTerminalOutputLineLimit(this.terminalManager["terminalOutputLineLimit"] || 500) + terminalManager.setSubagentTerminalOutputLineLimit(this.terminalManager["subagentTerminalOutputLineLimit"] || 2000) + } else { + // Use the configured terminal manager for regular commands + terminalManager = this.terminalManager + } + + const terminalInfo = await terminalManager.getOrCreateTerminal(this.cwd) terminalInfo.terminal.show() // weird visual bug when creating new terminals (even manually) where there's an empty space at the top. - const process = this.terminalManager.runCommand(terminalInfo, command) + const process = terminalManager.runCommand(terminalInfo, command) // Track command execution for both terminal modes this.controller.updateBackgroundCommandState(true, this.taskId) @@ -1377,7 +1410,7 @@ export class Task { // Process any output we captured before timeout await setTimeoutPromise(50) - const result = this.terminalManager.processOutput(outputLines) + const result = this.terminalManager.processOutput(outputLines, undefined, false) if (error.message === "COMMAND_TIMEOUT") { return [ @@ -1409,7 +1442,11 @@ export class Task { await setTimeoutPromise(50) } - const result = this.terminalManager.processOutput(outputLines) + const result = terminalManager.processOutput( + outputLines, + isSubagent ? terminalManager["subagentTerminalOutputLineLimit"] : undefined, + isSubagent, + ) if (didCancelViaUi) { return [ @@ -1420,6 +1457,12 @@ export class Task { ] } + // Capture subagent telemetry if this was a subagent command + if (isSubagent && subAgentStartTime > 0) { + const durationMs = Math.round(performance.now() - subAgentStartTime) + telemetryService.captureSubagentExecution(this.ulid, durationMs, outputLines.length, completed) + } + if (userFeedback) { await this.say("user_feedback", userFeedback.text, userFeedback.images, userFeedback.files) @@ -1553,6 +1596,14 @@ export class Task { ? `# Preferred Language\n\nSpeak in ${preferredLanguage}.` : "" + // Check CLI installation status only if subagents are enabled + const subagentsEnabled = this.stateManager.getGlobalSettingsKey("subagentsEnabled") + let isSubagentsEnabledAndCliInstalled = false + if (subagentsEnabled) { + const clineCliInstalled = await isClineCliInstalled() + isSubagentsEnabledAndCliInstalled = subagentsEnabled && clineCliInstalled + } + const { globalToggles, localToggles } = await refreshClineRulesToggles(this.controller, this.cwd) const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.controller, this.cwd) @@ -1583,6 +1634,12 @@ export class Task { })) } + // Detect if this is a CLI subagent to prevent nested subagent creation + const isCliSubagent = isCliSubagentContext({ + yoloModeToggled: this.stateManager.getGlobalSettingsKey("yoloModeToggled"), + maxConsecutiveMistakes: this.stateManager.getGlobalSettingsKey("maxConsecutiveMistakes"), + }) + const promptContext: SystemPromptContext = { cwd: this.cwd, ide, @@ -1601,6 +1658,8 @@ export class Task { yoloModeToggled: this.stateManager.getGlobalSettingsKey("yoloModeToggled"), isMultiRootEnabled: multiRootEnabled, workspaceRoots, + isSubagentsEnabledAndCliInstalled, + isCliSubagent, } const systemPrompt = await getSystemPrompt(promptContext) diff --git a/src/hosts/vscode/hostbridge/workspace/executeCommandInTerminal.ts b/src/hosts/vscode/hostbridge/workspace/executeCommandInTerminal.ts new file mode 100644 index 00000000..2e044c5f --- /dev/null +++ b/src/hosts/vscode/hostbridge/workspace/executeCommandInTerminal.ts @@ -0,0 +1,40 @@ +import { ExecuteCommandInTerminalRequest, ExecuteCommandInTerminalResponse } from "@shared/proto/host/workspace" +import * as vscode from "vscode" + +/** + * Executes a command in a new terminal + * @param request The request containing the command to execute + * @returns Response indicating success + */ +export async function executeCommandInTerminal( + request: ExecuteCommandInTerminalRequest, +): Promise { + try { + // Create terminal with fixed options + const terminalOptions: vscode.TerminalOptions = { + name: "Cline", + iconPath: new vscode.ThemeIcon("robot"), + env: { + CLINE_ACTIVE: "true", + }, + } + + // Create a new terminal + const terminal = vscode.window.createTerminal(terminalOptions) + + // Show the terminal to the user + terminal.show() + + // Send the command to the terminal + terminal.sendText(request.command, true) + + return ExecuteCommandInTerminalResponse.create({ + success: true, + }) + } catch (error) { + console.error("Error executing command in terminal:", error) + return ExecuteCommandInTerminalResponse.create({ + success: false, + }) + } +} diff --git a/src/integrations/cli-subagents/subagent_command.ts b/src/integrations/cli-subagents/subagent_command.ts new file mode 100644 index 00000000..7f1b708e --- /dev/null +++ b/src/integrations/cli-subagents/subagent_command.ts @@ -0,0 +1,78 @@ +/** + * Pattern to match simplified Cline CLI syntax: cline "prompt" or cline 'prompt' + * with optional additional flags after the closing quote + */ +const CLINE_COMMAND_PATTERN = /^cline\s+(['"])(.+?)\1(\s+.*)?$/ + +/** + * Detects if a command is a Cline CLI subagent command. + * + * Matches the simplified syntax: cline "prompt" or cline 'prompt' + * This allows the system to apply subagent-specific settings like autonomous execution. + * + * @param command - The command string to check + * @returns True if the command is a Cline CLI subagent command, false otherwise + */ +export function isSubagentCommand(command: string): boolean { + // Match simplified syntaxes + // cline "prompt" + // cline 'prompt' + return CLINE_COMMAND_PATTERN.test(command) +} + +/** + * Transforms simplified Cline CLI command syntax with subagent settings. + * + * Converts: cline "prompt" or cline 'prompt' + * To: cline "prompt" -s yolo_mode_toggled=true -s max_consecutive_mistakes=6 -F plain -y --oneshot + * + * Preserves additional flags like --workdir: + * cline "prompt" --workdir ./path → cline "prompt" -s ... -F plain -y --oneshot --workdir ./path + * + * This enables autonomous subagent execution with proper CLI flags for automation. + * + * @param command - The command string to potentially transform + * @returns The transformed command if it matches the pattern, otherwise the original command + */ +export function transformClineCommand(command: string): string { + if (!isSubagentCommand(command)) { + return command + } + + // Inject subagent-specific command structure and settings + const commandWithSettings = injectSubagentSettings(command) + + return commandWithSettings +} + +/** + * Injects subagent-specific command structure and settings into Cline CLI commands. + * + * @param command - The Cline CLI command (simplified or full syntax) + * @returns The command with injected flags and settings + */ +function injectSubagentSettings(command: string): string { + // No pre-prompt flags needed - use standard "cline 'prompt'" syntax + const prePromptFlags: string[] = [] + + // Flags/settings to insert after the prompt + const postPromptFlags = ["-s yolo_mode_toggled=true", "-s max_consecutive_mistakes=6", "-F plain", "-y", "--oneshot"] + + const match = command.match(CLINE_COMMAND_PATTERN) + + if (match) { + const quote = match[1] + const prompt = match[2] + const additionalFlags = match[3] || "" + const prePromptPart = prePromptFlags.length > 0 ? prePromptFlags.join(" ") + " " : "" + return `cline ${prePromptPart}${quote}${prompt}${quote} ${postPromptFlags.join(" ")}${additionalFlags}` + } + + // Already full format: just inject settings after prompt + const parts = command.split(" ") + const promptEndIndex = parts.findIndex((p) => p.endsWith('"') || p.endsWith("'")) + if (promptEndIndex !== -1) { + parts.splice(promptEndIndex + 1, 0, ...postPromptFlags) + } + return parts.join(" ") +} diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 2dd20720..3d442d5f 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -93,6 +93,7 @@ export interface ExtensionState { multiRootSetting: ClineFeatureSetting lastDismissedInfoBannerVersion: number lastDismissedModelBannerVersion: number + lastDismissedCliBannerVersion: number hooksEnabled?: ClineFeatureSetting remoteConfigSettings?: Partial subagentsEnabled?: boolean diff --git a/src/shared/storage/state-keys.ts b/src/shared/storage/state-keys.ts index 3447aa72..16e6bb83 100644 --- a/src/shared/storage/state-keys.ts +++ b/src/shared/storage/state-keys.ts @@ -42,6 +42,7 @@ export interface GlobalState { hooksEnabled: boolean lastDismissedInfoBannerVersion: number lastDismissedModelBannerVersion: number + lastDismissedCliBannerVersion: number } export interface Settings { diff --git a/src/utils/cli-detector.ts b/src/utils/cli-detector.ts new file mode 100644 index 00000000..10b24076 --- /dev/null +++ b/src/utils/cli-detector.ts @@ -0,0 +1,51 @@ +import { exec } from "child_process" +import { promisify } from "util" + +const execAsync = promisify(exec) + +/** + * Parameters used to detect CLI subagent context + */ +interface CliSubagentDetectionParams { + yoloModeToggled: boolean + maxConsecutiveMistakes: number + isOneshot?: boolean + outputFormat?: string +} + +/** + * Check if the Cline CLI tool is installed on the system + * @returns true if CLI is installed, false otherwise + */ +export async function isClineCliInstalled(): Promise { + try { + // Try to get the version of the cline CLI tool + // This will fail if the tool is not installed + const { stdout } = await execAsync("cline version", { + timeout: 5000, // 5 second timeout + }) + + // If we get here, the CLI is installed + // We could also validate the version if needed + return stdout.includes("Cline CLI Version") || stdout.includes("Cline Core Version") + } catch (error) { + // Command failed, which likely means CLI is not installed + // or not in PATH + return false + } +} + +/** + * Detect if the current Cline instance is running as a CLI subagent. + * CLI subagents are identified by specific parameter patterns set by the transformClineCommand function. + * TODO - For now we are relying on the maxConsecutiveMistakes value, which will only ever be "3" + * unless users pass in "-s max_consecutive_mistakes=6" via Cline CLI. Would like better detection. + * @param params The current task parameters to analyze + * @returns true if this appears to be a CLI subagent context + */ +export function isCliSubagentContext(params: CliSubagentDetectionParams): boolean { + const hasYoloMode = params.yoloModeToggled === true + const hasHighMistakeLimit = params.maxConsecutiveMistakes === 6 + + return hasYoloMode && hasHighMistakeLimit +} diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index a7ea375c..d869d95c 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -926,10 +926,56 @@ export const ChatRowContent = memo( const showCancelButton = isCommandExecuting && typeof onCancelCommand === "function" && vscodeTerminalExecutionMode === "backgroundExec" + // Check if this is a Cline subagent command + const isSubagentCommand = command.trim().startsWith("cline ") + let subagentPrompt: string | undefined + + if (isSubagentCommand) { + // Parse the cline command to extract prompt + // Format: cline "prompt" + const clineCommandRegex = /^cline\s+"([^"]+)"(?:\s+--no-interactive)?/ + const match = command.match(clineCommandRegex) + + if (match) { + subagentPrompt = match[1] + } + } + + // Compact Cline SVG icon component + const ClineIcon = () => ( + + + + + + + + + ) + + // Customize icon and title for subagent commands + const displayIcon = isSubagentCommand ? ( + isCommandExecuting ? ( + + ) : ( + + + + ) + ) : ( + icon + ) + + const displayTitle = isSubagentCommand ? ( + Cline wants to use a subagent: + ) : ( + title + ) + const commandHeader = (
- {icon} - {title} + {displayIcon} + {displayTitle}
) @@ -983,6 +1029,20 @@ export const ChatRowContent = memo( }}> {isCommandExecuting ? "Running" : "Completed"} + ) : isSubagentCommand && subagentPrompt ? ( + + {subagentPrompt} + ) : ( )} - {isExpanded && ( + {isSubagentCommand && subagentPrompt && isExpanded && ( +
+
+ Prompt:{" "} + + {subagentPrompt} + +
+
+ )} + {output.length > 0 && ( +
+
+ + + {isSubagentCommand ? "Subagent Output" : "Command Output"} + +
+
+ )} + {isExpanded && !isSubagentCommand && (
diff --git a/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx b/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx index 8669546e..d74d7f69 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx @@ -1,7 +1,7 @@ import React from "react" import Announcement from "@/components/chat/Announcement" +import CliInstallBanner, { CURRENT_CLI_BANNER_VERSION } from "@/components/common/CliInstallBanner" import InfoBanner, { CURRENT_INFO_BANNER_VERSION } from "@/components/common/InfoBanner" -import NewModelBanner, { CURRENT_MODEL_BANNER_VERSION } from "@/components/common/NewModelBanner" import HistoryPreview from "@/components/history/HistoryPreview" import HomeHeader from "@/components/welcome/HomeHeader" import { SuggestedTasks } from "@/components/welcome/SuggestedTasks" @@ -21,17 +21,21 @@ export const WelcomeSection: React.FC = ({ taskHistory, shouldShowQuickWins, }) => { - const { lastDismissedInfoBannerVersion, lastDismissedModelBannerVersion } = useExtensionState() + const { lastDismissedInfoBannerVersion, lastDismissedCliBannerVersion } = useExtensionState() const shouldShowInfoBanner = lastDismissedInfoBannerVersion < CURRENT_INFO_BANNER_VERSION - const shouldShowNewModelBanner = lastDismissedModelBannerVersion < CURRENT_MODEL_BANNER_VERSION + // const shouldShowNewModelBanner = lastDismissedModelBannerVersion < CURRENT_MODEL_BANNER_VERSION + + // Show CLI banner if not dismissed + const shouldShowCliBanner = lastDismissedCliBannerVersion < CURRENT_CLI_BANNER_VERSION return (
{shouldShowInfoBanner && } {showAnnouncement && } - {shouldShowNewModelBanner && } + {/* {shouldShowNewModelBanner && } */} + {shouldShowCliBanner && } {!shouldShowQuickWins && taskHistory.length > 0 && }
diff --git a/webview-ui/src/components/common/CliInstallBanner.tsx b/webview-ui/src/components/common/CliInstallBanner.tsx new file mode 100644 index 00000000..da5842e8 --- /dev/null +++ b/webview-ui/src/components/common/CliInstallBanner.tsx @@ -0,0 +1,215 @@ +import { StringRequest } from "@shared/proto/cline/common" +import { EmptyRequest, Int64Request } from "@shared/proto/index.cline" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import { Terminal } from "lucide-react" +import { useCallback, useEffect, useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { StateServiceClient, UiServiceClient } from "@/services/grpc-client" +import { getAsVar, VSC_INACTIVE_SELECTION_BACKGROUND } from "@/utils/vscStyles" + +export const CURRENT_CLI_BANNER_VERSION = 1 + +export const CliInstallBanner: React.FC = () => { + const { navigateToSettings, subagentsEnabled, platform } = useExtensionState() + const [isCopied, setIsCopied] = useState(false) + const [isClineCliInstalled, setIsClineCliInstalled] = useState(false) + + const isMacOS = platform === "darwin" + + // Poll for CLI installation status while the component is mounted + useEffect(() => { + const checkInstallation = async () => { + try { + const result = await StateServiceClient.checkCliInstallation(EmptyRequest.create()) + setIsClineCliInstalled(result.value) + } catch (error) { + console.error("Failed to check CLI installation:", error) + } + } + + // Check immediately when component mounts + checkInstallation() + + // Set up polling interval (every 1.5 seconds) + const pollInterval = setInterval(checkInstallation, 1500) + + // Clean up interval when component unmounts + return () => { + clearInterval(pollInterval) + } + }, []) + + const handleClose = useCallback((e?: React.MouseEvent) => { + e?.preventDefault() + e?.stopPropagation() + + // Update state to hide banner + StateServiceClient.updateCliBannerVersion(Int64Request.create({ value: CURRENT_CLI_BANNER_VERSION })).catch(console.error) + }, []) + + const handleInstallClick = async () => { + if (!isClineCliInstalled) { + try { + // Call the backend to initiate CLI installation + await StateServiceClient.installClineCli(EmptyRequest.create()) + // Banner will automatically close after successful installation + // setTimeout(() => { + // handleClose() + // }, 500) + } catch (error) { + console.error("Failed to initiate CLI installation:", error) + } + } + } + + const handleEnableSubagents = async () => { + if (!subagentsEnabled) { + // Navigate to settings and enable subagents + navigateToSettings() + // Scroll to features section after a brief delay to ensure settings is rendered + setTimeout(async () => { + try { + await UiServiceClient.scrollToSettings(StringRequest.create({ value: "features" })) + } catch (error) { + console.error("Error scrolling to features settings:", error) + } + }, 300) + } + } + + const handleCopyCommand = async (e: React.MouseEvent) => { + e.preventDefault() + e.stopPropagation() + + // Copy the install command to clipboard + await navigator.clipboard.writeText("npm install -g @cline") + + // Show feedback by changing the icon + setIsCopied(true) + setTimeout(() => { + setIsCopied(false) + }, 1500) + } + + return ( +
+

+ + {isMacOS ? "Cline for CLI is here!" : "Cline CLI Information"} +

+

+ {isMacOS ? ( + <> + Install to use Cline directly in your terminal and enable subagent capabilities. Cline can spawn{" "} + cline commands to handle focused tasks like exploring large codebases for information. This + keeps your main context window clean by running these operations in separate subprocesses.{" "} + + Learn more + + + ) : ( + <> + Cline CLI is available for Mac OS users now! coming soon to other platforms.{" "} + + Learn more + + + )} +

+
+
+ npm install -g cline + + + +
+ {isMacOS ? ( +
+ + {isClineCliInstalled ? ( + <> + + Installed + + ) : ( + "Install" + )} + + + Enable Subagents + +
+ ) : ( +
+ + {isClineCliInstalled ? ( + <> + + Installed + + ) : ( + "Install CLI" + )} + + + Subagents (macOS only) + +
+ )} +
+ + {/* Close button */} + + + +
+ ) +} + +export default CliInstallBanner diff --git a/webview-ui/src/components/settings/SubagentOutputLineLimitSlider.tsx b/webview-ui/src/components/settings/SubagentOutputLineLimitSlider.tsx new file mode 100644 index 00000000..da099831 --- /dev/null +++ b/webview-ui/src/components/settings/SubagentOutputLineLimitSlider.tsx @@ -0,0 +1,38 @@ +import React from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { updateSetting } from "./utils/settingsHandlers" + +const SubagentOutputLineLimitSlider: React.FC = () => { + const { subagentTerminalOutputLineLimit } = useExtensionState() + + const handleSliderChange = (event: React.ChangeEvent) => { + const value = parseInt(event.target.value, 10) + updateSetting("subagentTerminalOutputLineLimit", value) + } + + return ( +
+ +
+ + {subagentTerminalOutputLineLimit ?? 2000} +
+

+ Maximum number of lines to include in output from CLI subagents. +

+
+ ) +} + +export default SubagentOutputLineLimitSlider diff --git a/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx index 4a3430b3..49b8df42 100644 --- a/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx @@ -1,12 +1,15 @@ import { SUPPORTED_DICTATION_LANGUAGES } from "@shared/DictationSettings" import { McpDisplayMode } from "@shared/McpDisplayMode" +import { EmptyRequest } from "@shared/proto/index.cline" import { OpenaiReasoningEffort } from "@shared/storage/types" -import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" -import { memo } from "react" +import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { memo, useEffect, useState } from "react" import HeroTooltip from "@/components/common/HeroTooltip" import McpDisplayModeDropdown from "@/components/mcp/chat-display/McpDisplayModeDropdown" import { useExtensionState } from "@/context/ExtensionStateContext" +import { StateServiceClient } from "@/services/grpc-client" import Section from "../Section" +import SubagentOutputLineLimitSlider from "../SubagentOutputLineLimitSlider" import { updateSetting } from "../utils/settingsHandlers" interface FeatureSettingsSectionProps { @@ -28,17 +31,141 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP multiRootSetting, hooksEnabled, remoteConfigSettings, + subagentsEnabled, + platform, } = useExtensionState() + const isMacOS = platform === "darwin" + + const [isClineCliInstalled, setIsClineCliInstalled] = useState(false) + const handleReasoningEffortChange = (newValue: OpenaiReasoningEffort) => { updateSetting("openaiReasoningEffort", newValue) } + // Poll for CLI installation status while the component is mounted + useEffect(() => { + const checkInstallation = async () => { + try { + const result = await StateServiceClient.checkCliInstallation(EmptyRequest.create()) + setIsClineCliInstalled(result.value) + } catch (error) { + console.error("Failed to check CLI installation:", error) + } + } + + checkInstallation() + + // Poll ever 1.5 seconds to see if CLI is installed (only when form is open) + const pollInterval = setInterval(checkInstallation, 1500) + + return () => { + clearInterval(pollInterval) + } + }, []) + return (
{renderSectionHeader("features")}
+ {/* Subagents - Only show on macOS (for now) */} + {isMacOS && ( +
+
+ NEW +
+ {!isClineCliInstalled && ( +
+

+ + + Cline for CLI is required for subagents. Install it with: + + npm install -g cline + + , then run + + cline auth + + To authenticate with Cline or configure an API provider. + +

+ { + try { + await StateServiceClient.installClineCli(EmptyRequest.create()) + } catch (error) { + console.error("Failed to initiate CLI installation:", error) + } + }} + style={{ + transform: "scale(0.85)", + transformOrigin: "left center", + marginLeft: "-2px", + }}> + Install Now + +
+ )} + { + const checked = e.target.checked === true + updateSetting("subagentsEnabled", checked) + }}> + + {subagentsEnabled ? "Subagents Enabled" : "Enable Subagents"} + + +

+ Experimental: {" "} + + Allows Cline to spawn subprocesses to handle focused tasks like exploring large codebases, + keeping your main context clean. + +

+ {subagentsEnabled && ( +
+ +
+ )} +
+ )} +