From 5fde21dffd7fe3f2375ce5fa46256a78138a7ecd Mon Sep 17 00:00:00 2001
From: Bee <68532117+abeatrix@users.noreply.github.com>
Date: Tue, 28 Oct 2025 17:49:19 -0700
Subject: [PATCH] native tool calling (#6921)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* (WIP)feat(api): add tool calling support to openai API handlers
Add ChatCompletionTool parameter to createMessage interface and implement tool calling functionality across API providers. Includes new StreamingToolCallHandler for processing tool call deltas and utility functions for converting tool specifications to OpenAI format.
* Replace path with absolutePath
* Simplify tool spec
* Parse stream and use variant matcher
* Simplify StreamingToolCallHandler
* Add CLINE_NEXT_GEN
* Enable parallel_tool_calls
* ApplyPatchHandler
* Simplify ApplyPatchHandler
* store tool use chunk
* feat(anthropic): add streaming tool use support with OpenAI-compatible format
Add comprehensive support for streaming tool use blocks from Anthropic API:
- Add tool_use case handler in AnthropicHandler to convert streaming tool
calls to OpenAI-compatible format during content block start events
- Implement ToolUseHandler class to accumulate and parse streaming tool use
deltas with incremental JSON parsing support
- Add proper handling for undefined tool message content in openai-format
converter to prevent errors
- Integrate ToolUseHandler into TaskState for managing streaming tool calls
across the request lifecycle
This enables real-time processing of tool calls as they stream from Anthropic's
API while maintaining compatibility with OpenAI's tool calling format.
* feat(anthropic): add tool support with OpenAI tool conversion
Add support for passing tools to Anthropic API with automatic conversion from OpenAI tool format. Implements tool_choice configuration to force tool usage when tools are provided.
Changes:
- Add tools parameter to createMessage method in AnthropicHandler
- Implement openAIToolToAnthropic converter to transform OpenAI ChatCompletionTool format to Anthropic Tool format
- Set tool_choice to "any" when tools are provided to ensure Claude uses one of the available tools
- Fix tool result handling to avoid invalid tool_use_id "cline" by converting to text blocks for backward compatibility
- Add documentation for tool_choice options (none, auto, any)
This enables proper tool calling functionality with Anthropic models while maintaining compatibility with the existing OpenAI tool definitions.
* oops
* fix: remove .mjs extensions from import paths
Remove `.mjs` file extensions from OpenAI and Anthropic SDK import paths to ensure compatibility with current module resolution. This updates imports across multiple files:
- openai/resources/chat/completions.mjs → openai/resources/chat/completions
- @anthropic-ai/sdk/resources/index.mjs → @anthropic-ai/sdk/resources/index
* revert styles.css change from merge main
* Update config and fix tests
* gpt-5 variant for cline provider only
* Fix GPT-5 web fetch tool
* Add native next gen for supported openai providers
* add native tool calling support to more openai comp providers
* list supported providers for gpt-5
* clean up
* Update ApplyPatchHandler
* clean up
* Update ask_followup_question
* Add system prompt test for cline claude 4.5 sonnet
* noToolsUsed
* Add support to gemini api provider
* add native tool calling to more providers
* Skip XML parsing
* clean up
* add back TASK_PROGRESS_PARAMETER to native tools
* feature flag NATIVE_TOOL_CALLS_NEXT_GEN_MODELS
* add allowNativeToolCalls to system prompt context
* add grok-code
* feat(context): ensure tool_result blocks follow tool_use blocks
Add validation to ensure every tool_use block in assistant messages has a corresponding tool_result in the following user message. When tool_result blocks are missing, they are automatically added with "result missing" content to maintain proper message pairing required by the Anthropic API.
This prevents API errors caused by orphaned tool_use blocks and ensures conversation history integrity after context management operations.
* feat(task): refactor ApplyPatchHandler to use FileEditProvider with revert support
Refactor the ApplyPatchHandler to use FileEditProvider and DiffViewProvider
for file operations instead of direct filesystem access. This change adds:
- State tracking for applied commits to enable rollback functionality
- Automatic revert of changes when user denies approval or errors occur
- Enhanced response format that includes full file contents after patching
- Consistent file reading through DiffViewProvider for better editor integration
- Proper cleanup of applied state after successful operations
This improves the patch application workflow by ensuring changes can be
safely reverted and provides better visibility into the applied changes.
The refactoring also aligns file operations with the existing editor
integration patterns used elsewhere in the codebase.
* Finalizing...
* MCP tools converter
* remove ClineDefaultTool.MCP_USE
* Update snapshot
* comments
* use diffViewProvider
* Fix MCP tool use with images
* fix mcp tool converter with reserved keys
* Fix apply patch streaming issue
* add vercel-ai-gateway to supported provider & clean up
* simplfy apply patch handler
* Turn off thinking when native tools are enabled for anthropic provider
* clean up ToolUseHandler
* anthropic tool_choice logic
* improve tool result ordering
- Extract anthropic message mapping logic into a separate variable for better readability
- Add MessageParam import from Anthropic SDK
- Update ensureToolResultsFollowToolUse to maintain tool_result order matching tool_use blocks
- Improve documentation to clarify tool result ordering requirements
This refactoring improves code maintainability by separating the message transformation logic and ensures tool results are properly ordered to match their corresponding tool use blocks in the conversation flow.
200000
* refactor tool result validation for improved efficiency
Simplify ensureToolResultsFollowToolUse method by streamlining the logic
for validating and reordering tool_result blocks. Changes include:
- Use early returns to reduce nesting and improve readability
- Process tool results and other blocks in a single pass instead of multiple iterations
- Eliminate unnecessary deep cloning by mutating content array directly
- Add flag-based update detection to avoid unnecessary array rebuilding
- Simplify the reordering logic while maintaining the same validation rules
This refactoring maintains the same functional behavior (ensuring tool_result
blocks follow their corresponding tool_use blocks) while reducing complexity
and improving performance through more efficient array operations.
200000
* attempt_completion
* use helper function
* remove FreeModelIDs from merge conflicts
* clean up
* Add NATIVE_GPT_5 & exclude gpt-5-chat
* shouldAutoApproveToolWithPath for apply patch
* add openai-native to supported provider
* add lightweight incremental chunk extraction
* update apply patch handler
* revert version regex
* Fix browser action
---
package.json | 2 +-
src/core/api/index.ts | 3 +-
src/core/api/providers/anthropic.ts | 117 +-
src/core/api/providers/cline.ts | 14 +-
src/core/api/providers/deepseek.ts | 11 +-
src/core/api/providers/gemini.ts | 40 +-
src/core/api/providers/groq.ts | 10 +-
src/core/api/providers/huawei-cloud-maas.ts | 11 +-
src/core/api/providers/huggingface.ts | 10 +-
src/core/api/providers/lmstudio.ts | 13 +-
src/core/api/providers/minimax.ts | 15 +-
src/core/api/providers/mistral.ts | 21 +-
src/core/api/providers/moonshot.ts | 12 +-
src/core/api/providers/nebius.ts | 10 +-
src/core/api/providers/oca.ts | 11 +-
src/core/api/providers/openai-native.ts | 30 +-
src/core/api/providers/openai.ts | 23 +-
src/core/api/providers/openrouter.ts | 10 +-
src/core/api/providers/qwen-code.ts | 10 +-
src/core/api/providers/qwen.ts | 15 +-
src/core/api/providers/sambanova.ts | 10 +-
src/core/api/providers/together.ts | 10 +-
src/core/api/providers/vercel-ai-gateway.ts | 18 +-
src/core/api/providers/vertex.ts | 48 +-
src/core/api/providers/xai.ts | 11 +-
src/core/api/providers/zai.ts | 11 +-
src/core/api/transform/anthropic-format.ts | 19 +
src/core/api/transform/gemini-format.ts | 16 +
src/core/api/transform/openai-format.ts | 72 +-
src/core/api/transform/openrouter-stream.ts | 4 +
src/core/api/transform/stream.ts | 16 +
src/core/api/transform/tool-call-processor.ts | 87 ++
src/core/api/transform/tool-use-handler.ts | 189 +++
.../api/transform/vercel-ai-gateway-stream.ts | 4 +
src/core/assistant-message/index.ts | 2 +
.../context-management/ContextManager.ts | 118 ++
src/core/prompts/responses.ts | 11 +-
src/core/prompts/system-prompt/README.md | 4 +-
.../__tests__/PromptBuilder.test.ts | 4 +
.../__tests__/PromptRegistry.test.ts | 21 +-
.../cline_claude_4_5_sonnet-basic.snap | 98 ++
.../cline_claude_4_5_sonnet-no-browser.snap | 96 ++
...line_claude_4_5_sonnet-no-focus-chain.snap | 79 ++
.../cline_claude_4_5_sonnet-no-mcp.snap | 98 ++
.../__snapshots__/openai_gpt_5-basic.snap | 101 +-
.../openai_gpt_5-no-browser.snap | 101 +-
.../openai_gpt_5-no-focus-chain.snap | 99 +-
.../__snapshots__/openai_gpt_5-no-mcp.snap | 101 +-
.../__tests__/integration.test.ts | 61 +-
.../system-prompt/__tests__/matcher-test.ts | 128 ++
.../components/tool_use/index.ts | 2 +-
src/core/prompts/system-prompt/index.ts | 31 +-
.../system-prompt/registry/ClineToolSet.ts | 115 +-
.../system-prompt/registry/PromptBuilder.ts | 15 +-
.../system-prompt/registry/PromptRegistry.ts | 39 +-
src/core/prompts/system-prompt/spec.ts | 315 ++++-
.../system-prompt/tools/apply_patch.ts | 96 ++
.../tools/ask_followup_question.ts | 32 +-
.../system-prompt/tools/attempt_completion.ts | 36 +-
.../system-prompt/tools/browser_action.ts | 50 +-
.../system-prompt/tools/execute_command.ts | 37 +-
.../system-prompt/tools/focus_chain.ts | 6 +-
src/core/prompts/system-prompt/tools/index.ts | 1 +
src/core/prompts/system-prompt/tools/init.ts | 2 +
.../tools/list_code_definition_names.ts | 23 +-
.../prompts/system-prompt/tools/list_files.ts | 30 +-
.../system-prompt/tools/plan_mode_respond.ts | 29 +-
.../prompts/system-prompt/tools/read_file.ts | 26 +-
.../system-prompt/tools/replace_in_file.ts | 48 +-
.../system-prompt/tools/search_files.ts | 37 +-
.../system-prompt/tools/use_mcp_tool.ts | 6 +-
.../prompts/system-prompt/tools/web_fetch.ts | 22 +-
.../system-prompt/tools/write_to_file.ts | 26 +-
src/core/prompts/system-prompt/types.ts | 4 +
.../system-prompt/variants/generic/config.ts | 18 +
.../system-prompt/variants/glm/config.ts | 6 +-
.../system-prompt/variants/gpt-5/config.ts | 25 +-
.../system-prompt/variants/gpt-5/template.ts | 13 +-
.../prompts/system-prompt/variants/index.ts | 26 +-
.../variants/native-gpt-5/config.ts | 96 ++
.../variants/native-gpt-5/template.ts | 101 ++
.../variants/native-next-gen/config.ts | 97 ++
.../variants/native-next-gen/template.ts | 95 ++
.../system-prompt/variants/next-gen/config.ts | 17 +-
.../system-prompt/variants/variant-builder.ts | 17 +-
.../system-prompt/variants/xs/config.ts | 8 +-
src/core/task/TaskState.ts | 4 +-
src/core/task/ToolExecutor.ts | 9 +-
src/core/task/focus-chain/index.ts | 105 +-
src/core/task/focus-chain/prompts.ts | 112 ++
src/core/task/index.ts | 159 ++-
.../task/tools/ToolExecutorCoordinator.ts | 5 +
.../task/tools/handlers/ApplyPatchHandler.ts | 1201 +++++++++++++++++
.../tools/handlers/WriteToFileToolHandler.ts | 18 +-
src/core/task/tools/utils/ToolResultUtils.ts | 60 +-
src/integrations/editor/DiffViewProvider.ts | 6 +-
src/integrations/editor/FileEditProvider.ts | 116 ++
.../feature-flags/FeatureFlagsService.ts | 8 +-
src/shared/mcp.ts | 1 +
src/shared/prompts.ts | 2 +
.../services/feature-flags/feature-flags.ts | 3 +
src/shared/tools.ts | 7 +
src/utils/model-utils.ts | 38 +-
103 files changed, 4822 insertions(+), 604 deletions(-)
create mode 100644 src/core/api/transform/anthropic-format.ts
create mode 100644 src/core/api/transform/tool-call-processor.ts
create mode 100644 src/core/api/transform/tool-use-handler.ts
create mode 100644 src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-basic.snap
create mode 100644 src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-browser.snap
create mode 100644 src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-focus-chain.snap
create mode 100644 src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-mcp.snap
create mode 100644 src/core/prompts/system-prompt/__tests__/matcher-test.ts
create mode 100644 src/core/prompts/system-prompt/tools/apply_patch.ts
create mode 100644 src/core/prompts/system-prompt/variants/native-gpt-5/config.ts
create mode 100644 src/core/prompts/system-prompt/variants/native-gpt-5/template.ts
create mode 100644 src/core/prompts/system-prompt/variants/native-next-gen/config.ts
create mode 100644 src/core/prompts/system-prompt/variants/native-next-gen/template.ts
create mode 100644 src/core/task/focus-chain/prompts.ts
create mode 100644 src/core/task/tools/handlers/ApplyPatchHandler.ts
create mode 100644 src/integrations/editor/FileEditProvider.ts
diff --git a/package.json b/package.json
index 86f16e3f..2655b25f 100644
--- a/package.json
+++ b/package.json
@@ -330,7 +330,7 @@
"pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint",
"test": "npm-run-all test:unit test:integration",
"test:integration": "vscode-test",
- "test:unit": "cross-env TS_NODE_PROJECT=./tsconfig.unit-test.json mocha # Use `npm run test:unit --update-snapshots` to rebuild prompt snapshots",
+ "test:unit": "cross-env TS_NODE_PROJECT=./tsconfig.unit-test.json mocha",
"test:coverage": "vscode-test --coverage",
"test:sca-server": "npx tsx watch scripts/test-standalone-core-api-server.ts",
"test:tp-orchestrator": "npx tsx scripts/testing-platform-orchestrator.ts",
diff --git a/src/core/api/index.ts b/src/core/api/index.ts
index 6caab7f9..f92f3340 100644
--- a/src/core/api/index.ts
+++ b/src/core/api/index.ts
@@ -1,6 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ApiConfiguration, ModelInfo, QwenApiRegions } from "@shared/api"
import { Mode } from "@shared/storage/types"
+import { ClineTool } from "@/shared/tools"
import { AnthropicHandler } from "./providers/anthropic"
import { AskSageHandler } from "./providers/asksage"
import { BasetenHandler } from "./providers/baseten"
@@ -45,7 +46,7 @@ export type CommonApiHandlerOptions = {
}
export interface ApiHandler {
- createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
+ createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream
getModel(): ApiHandlerModel
getApiStreamUsage?(): Promise
}
diff --git a/src/core/api/providers/anthropic.ts b/src/core/api/providers/anthropic.ts
index c3638572..df54b425 100644
--- a/src/core/api/providers/anthropic.ts
+++ b/src/core/api/providers/anthropic.ts
@@ -1,6 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
+import { Tool as AnthropicTool, MessageParam } from "@anthropic-ai/sdk/resources/index"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
+import { ClineTool } from "@/shared/tools"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
@@ -38,7 +40,7 @@ export class AnthropicHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -48,6 +50,9 @@ export class AnthropicHandler implements ApiHandler {
const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_1M_SUFFIX)
const budget_tokens = this.options.thinkingBudgetTokens || 0
+
+ // Tools are available only when native tools are enabled.
+ const nativeToolsOn = tools?.length && tools?.length > 0
const reasoningOn = !!(
(modelId.includes("3-7") || modelId.includes("4-") || modelId.includes("4-5")) &&
budget_tokens !== 0
@@ -68,12 +73,45 @@ export class AnthropicHandler implements ApiHandler {
/*
The latest message will be the new user message, one before will be the assistant message from a previous request, and the user message before that will be a previously cached user message. So we need to mark the latest user message as ephemeral to cache it for the next request, and mark the second to last user message as ephemeral to let the server know the last message to retrieve from the cache for the current request..
*/
- const userMsgIndices = messages.reduce(
- (acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc),
- [] as number[],
- )
+ const userMsgIndices = messages.reduce((acc, msg, index) => {
+ if (msg.role === "user") {
+ acc.push(index)
+ }
+ return acc
+ }, [] as number[])
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
+
+ const anthropicMessages: Array = messages.map((message, index) => {
+ if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
+ return {
+ ...message,
+ content:
+ typeof message.content === "string"
+ ? [
+ {
+ type: "text",
+ text: message.content,
+ cache_control: {
+ type: "ephemeral",
+ },
+ },
+ ]
+ : message.content.map((content, contentIndex) =>
+ contentIndex === message.content.length - 1
+ ? {
+ ...content,
+ cache_control: {
+ type: "ephemeral",
+ },
+ }
+ : content,
+ ),
+ }
+ }
+ return message
+ })
+
stream = await client.messages.create(
{
model: modelId,
@@ -89,39 +127,16 @@ export class AnthropicHandler implements ApiHandler {
cache_control: { type: "ephemeral" },
},
], // setting cache breakpoint for system prompt so new tasks can reuse it
- messages: messages.map((message, index) => {
- if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
- return {
- ...message,
- content:
- typeof message.content === "string"
- ? [
- {
- type: "text",
- text: message.content,
- cache_control: {
- type: "ephemeral",
- },
- },
- ]
- : message.content.map((content, contentIndex) =>
- contentIndex === message.content.length - 1
- ? {
- ...content,
- cache_control: {
- type: "ephemeral",
- },
- }
- : content,
- ),
- }
- }
- return message
- }),
+ messages: anthropicMessages,
// tools, // cache breakpoints go from tools > system > messages, and since tools dont change, we can just set the breakpoint at the end of system (this avoids having to set a breakpoint at the end of tools which by itself does not meet min requirements for haiku caching)
- // tool_choice: { type: "auto" },
- // tools: tools,
stream: true,
+ tools: nativeToolsOn ? (tools as AnthropicTool[]) : undefined,
+ // tool_choice options:
+ // - none: disables tool use, even if tools are provided. Claude will not call any tools.
+ // - auto: allows Claude to decide whether to call any provided tools or not. This is the default value when tools are provided.
+ // - any: tells Claude that it must use one of the provided tools, but doesn’t force a particular tool.
+ // NOTE: Forcing tool use when tools are provided will result in error when thinking is also enabled.
+ tool_choice: nativeToolsOn && !reasoningOn ? { type: "any" } : undefined,
},
(() => {
// 1m context window beta header
@@ -154,6 +169,7 @@ export class AnthropicHandler implements ApiHandler {
}
let thinkingDeltaAccumulator = ""
+ const lastStartedToolCall = { id: "", name: "", arguments: "" }
for await (const chunk of stream) {
switch (chunk?.type) {
@@ -208,6 +224,14 @@ export class AnthropicHandler implements ApiHandler {
data: chunk.content_block.data,
}
break
+ case "tool_use":
+ if (chunk.content_block.id && chunk.content_block.name) {
+ // Convert Anthropic tool_use to OpenAI-compatible format
+ lastStartedToolCall.id = chunk.content_block.id
+ lastStartedToolCall.name = chunk.content_block.name
+ lastStartedToolCall.arguments = ""
+ }
+ break
case "text":
// we may receive multiple text blocks, in which case just insert a line break between them
if (chunk.index > 0) {
@@ -250,9 +274,30 @@ export class AnthropicHandler implements ApiHandler {
text: chunk.delta.text,
}
break
+ case "input_json_delta":
+ if (lastStartedToolCall.id && lastStartedToolCall.name && chunk.delta.partial_json) {
+ // // Convert Anthropic tool_use to OpenAI-compatible format
+ yield {
+ type: "tool_calls",
+ tool_call: {
+ ...lastStartedToolCall,
+ function: {
+ ...lastStartedToolCall,
+ id: lastStartedToolCall.id,
+ name: lastStartedToolCall.name,
+ arguments: chunk.delta.partial_json,
+ },
+ },
+ }
+ }
+ break
}
break
+
case "content_block_stop":
+ lastStartedToolCall.id = ""
+ lastStartedToolCall.name = ""
+ lastStartedToolCall.arguments = ""
break
}
}
diff --git a/src/core/api/providers/cline.ts b/src/core/api/providers/cline.ts
index edecaf34..cdb8661f 100644
--- a/src/core/api/providers/cline.ts
+++ b/src/core/api/providers/cline.ts
@@ -3,6 +3,7 @@ import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import axios from "axios"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineEnv } from "@/config"
import { ClineAccountService } from "@/services/account/ClineAccountService"
import { AuthService } from "@/services/auth/AuthService"
@@ -12,6 +13,7 @@ import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { createOpenRouterStream } from "../transform/openrouter-stream"
import { ApiStream, ApiStreamUsageChunk } from "../transform/stream"
+import { ToolCallProcessor } from "../transform/tool-call-processor"
import { OpenRouterErrorResponse } from "./types"
interface ClineHandlerOptions extends CommonApiHandlerOptions {
@@ -93,7 +95,7 @@ export class ClineHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
try {
const client = await this.ensureClient()
@@ -110,8 +112,11 @@ export class ClineHandler implements ApiHandler {
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
+ tools,
)
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
// openrouter returns an error object instead of the openai sdk throwing an error
if ("error" in chunk) {
@@ -150,6 +155,10 @@ export class ClineHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Reasoning tokens are returned separately from the content
// Skip reasoning content for Grok 4 models since it only displays "thinking" without providing useful information
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) {
@@ -194,8 +203,7 @@ export class ClineHandler implements ApiHandler {
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
outputTokens: chunk.usage.completion_tokens || 0,
- // @ts-ignore-next-line
- totalCost: totalCost,
+ totalCost,
}
didOutputUsage = true
}
diff --git a/src/core/api/providers/deepseek.ts b/src/core/api/providers/deepseek.ts
index f005e4bd..aed12730 100644
--- a/src/core/api/providers/deepseek.ts
+++ b/src/core/api/providers/deepseek.ts
@@ -2,11 +2,13 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { DeepSeekModelId, deepSeekDefaultModelId, deepSeekModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface DeepSeekHandlerOptions extends CommonApiHandlerOptions {
deepSeekApiKey?: string
@@ -71,7 +73,7 @@ export class DeepSeekHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -94,8 +96,11 @@ export class DeepSeekHandler implements ApiHandler {
stream_options: { include_usage: true },
// Only set temperature for non-reasoner models
...(model.id === "deepseek-reasoner" ? {} : { temperature: 0 }),
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -105,6 +110,10 @@ export class DeepSeekHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
diff --git a/src/core/api/providers/gemini.ts b/src/core/api/providers/gemini.ts
index e3b67b96..3f691080 100644
--- a/src/core/api/providers/gemini.ts
+++ b/src/core/api/providers/gemini.ts
@@ -1,6 +1,14 @@
import type { Anthropic } from "@anthropic-ai/sdk"
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
-import { ApiError, type GenerateContentConfig, type GenerateContentResponseUsageMetadata, GoogleGenAI, Part } from "@google/genai"
+import {
+ ApiError,
+ FunctionCallingConfigMode,
+ type GenerateContentConfig,
+ type GenerateContentResponseUsageMetadata,
+ GoogleGenAI,
+ FunctionDeclaration as GoogleTool,
+ Part,
+} from "@google/genai"
import { GeminiModelId, geminiDefaultModelId, geminiModels, ModelInfo } from "@shared/api"
import { telemetryService } from "@/services/telemetry"
import { ApiHandler, CommonApiHandlerOptions } from "../"
@@ -102,7 +110,7 @@ export class GeminiHandler implements ApiHandler {
baseDelay: 2000,
maxDelay: 15000,
})
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: GoogleTool[]): ApiStream {
const client = this.ensureClient()
const { id: modelId, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
@@ -140,6 +148,16 @@ export class GeminiHandler implements ApiHandler {
let thoughtsTokenCount = 0 // Initialize thought token counts
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
+ if (tools?.length) {
+ requestConfig.tools = [{ functionDeclarations: tools }]
+ requestConfig.toolConfig = {
+ // Force the model to call 'any' function.
+ functionCallingConfig: {
+ mode: FunctionCallingConfigMode.ANY,
+ },
+ }
+ }
+
try {
const result = await client.models.generateContentStream({
model: modelId,
@@ -189,6 +207,24 @@ export class GeminiHandler implements ApiHandler {
}
}
+ if (tools && chunk.functionCalls && chunk.functionCalls?.length > 0) {
+ for (const functionCall of chunk.functionCalls) {
+ if (functionCall.args) {
+ console.log("[GeminiHandler] tool call received:", functionCall)
+ yield {
+ type: "tool_calls",
+ tool_call: {
+ function: {
+ id: functionCall.id || functionCall.name,
+ name: functionCall.name,
+ arguments: JSON.stringify(functionCall.args),
+ },
+ },
+ }
+ }
+ }
+ }
+
if (chunk.usageMetadata) {
lastUsageMetadata = chunk.usageMetadata
promptTokens = lastUsageMetadata.promptTokenCount ?? promptTokens
diff --git a/src/core/api/providers/groq.ts b/src/core/api/providers/groq.ts
index 22cc2255..60dd34c8 100644
--- a/src/core/api/providers/groq.ts
+++ b/src/core/api/providers/groq.ts
@@ -2,10 +2,12 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { GroqModelId, groqDefaultModelId, groqModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface GroqHandlerOptions extends CommonApiHandlerOptions {
groqApiKey?: string
@@ -188,7 +190,7 @@ export class GroqHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const modelFamily = this.detectModelFamily(model.id)
@@ -213,6 +215,7 @@ export class GroqHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
temperature,
+ ...getOpenAIToolParams(tools),
}
// Add any special parameters for specific model families
@@ -220,6 +223,7 @@ export class GroqHandler implements ApiHandler {
Object.assign(requestParams, modelFamily.specialParams)
}
+ const toolCallProcessor = new ToolCallProcessor()
const stream = await client.chat.completions.create(requestParams)
for await (const chunk of stream) {
@@ -235,6 +239,10 @@ export class GroqHandler implements ApiHandler {
continue
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Handle content field - trust the parsed output from Groq
if (delta?.content) {
yield {
diff --git a/src/core/api/providers/huawei-cloud-maas.ts b/src/core/api/providers/huawei-cloud-maas.ts
index 0ac11f1c..ae14f1fd 100644
--- a/src/core/api/providers/huawei-cloud-maas.ts
+++ b/src/core/api/providers/huawei-cloud-maas.ts
@@ -1,10 +1,12 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { HuaweiCloudMaasModelId, huaweiCloudMaasDefaultModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface HuaweiCloudMaaSHandlerOptions extends CommonApiHandlerOptions {
huaweiCloudMaasApiKey?: string
@@ -58,7 +60,7 @@ export class HuaweiCloudMaaSHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -72,12 +74,15 @@ export class HuaweiCloudMaaSHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
temperature: 0,
+ ...getOpenAIToolParams(tools),
})
let reasoning: string | null = null
let didOutputUsage: boolean = false
let finalUsage: any = null
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
@@ -93,6 +98,10 @@ export class HuaweiCloudMaaSHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Handle reasoning output
if (reasoning || (delta && "reasoning_content" in delta && delta.reasoning_content)) {
const reasoningContent = delta?.content || ((delta as any)?.reasoning_content as string | undefined) || ""
diff --git a/src/core/api/providers/huggingface.ts b/src/core/api/providers/huggingface.ts
index efff5e3a..78f9b098 100644
--- a/src/core/api/providers/huggingface.ts
+++ b/src/core/api/providers/huggingface.ts
@@ -2,10 +2,12 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { HuggingFaceModelId, huggingFaceDefaultModelId, huggingFaceModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface HuggingFaceHandlerOptions extends CommonApiHandlerOptions {
huggingFaceApiKey?: string
@@ -65,7 +67,7 @@ export class HuggingFaceHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
try {
const client = this.ensureClient()
const model = this.getModel()
@@ -82,8 +84,10 @@ export class HuggingFaceHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
temperature: 0,
+ ...getOpenAIToolParams(tools),
}
+ const toolCallProcessor = new ToolCallProcessor()
const stream = (await client.chat.completions.create(requestParams)) as any
let _chunkCount = 0
@@ -101,6 +105,10 @@ export class HuggingFaceHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield* this.yieldUsage(model.info, chunk.usage)
}
diff --git a/src/core/api/providers/lmstudio.ts b/src/core/api/providers/lmstudio.ts
index 52a1a98d..7cb47100 100644
--- a/src/core/api/providers/lmstudio.ts
+++ b/src/core/api/providers/lmstudio.ts
@@ -1,10 +1,12 @@
import type { Anthropic } from "@anthropic-ai/sdk"
import { type ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import type { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import type { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface LmStudioHandlerOptions extends CommonApiHandlerOptions {
lmStudioBaseUrl?: string
@@ -36,7 +38,7 @@ export class LmStudioHandler implements ApiHandler {
}
@withRetry({ retryAllErrors: true })
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
@@ -50,7 +52,11 @@ export class LmStudioHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
max_completion_tokens: this.options.lmStudioMaxTokens ? Number(this.options.lmStudioMaxTokens) : undefined,
+ ...getOpenAIToolParams(tools),
})
+
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const choice = chunk.choices[0]
const delta = choice?.delta
@@ -66,6 +72,11 @@ export class LmStudioHandler implements ApiHandler {
reasoning: (delta.reasoning_content as string | undefined) || "",
}
}
+
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield {
type: "usage",
diff --git a/src/core/api/providers/minimax.ts b/src/core/api/providers/minimax.ts
index 756eea52..82f4b98d 100644
--- a/src/core/api/providers/minimax.ts
+++ b/src/core/api/providers/minimax.ts
@@ -1,10 +1,12 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
+import type { ChatCompletionTool } from "openai/resources/chat/completions"
import { MinimaxModelId, ModelInfo, minimaxDefaultModelId, minimaxModels } from "@/shared/api"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface MinimaxHandlerOptions extends CommonApiHandlerOptions {
minimaxApiKey?: string
@@ -36,7 +38,11 @@ export class MinimaxHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(
+ systemPrompt: string,
+ messages: Anthropic.Messages.MessageParam[],
+ tools?: ChatCompletionTool[],
+ ): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -51,8 +57,11 @@ export class MinimaxHandler implements ApiHandler {
max_tokens: model.info.maxTokens,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -69,6 +78,10 @@ export class MinimaxHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield {
type: "usage",
diff --git a/src/core/api/providers/mistral.ts b/src/core/api/providers/mistral.ts
index 264c9604..319f34c4 100644
--- a/src/core/api/providers/mistral.ts
+++ b/src/core/api/providers/mistral.ts
@@ -1,6 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Mistral } from "@mistralai/mistralai"
+import { Tool as MistralTool } from "@mistralai/mistralai/models/components/tool"
import { MistralModelId, ModelInfo, mistralDefaultModelId, mistralModels } from "@shared/api"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToMistralMessages } from "../transform/mistral-format"
@@ -36,7 +38,7 @@ export class MistralHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const stream = await client.chat
.stream({
@@ -45,6 +47,8 @@ export class MistralHandler implements ApiHandler {
temperature: 0,
messages: [{ role: "system", content: systemPrompt }, ...convertToMistralMessages(messages)],
stream: true,
+ tools: tools?.length ? (tools as MistralTool[]) : undefined,
+ toolChoice: tools?.length ? "any" : undefined,
})
.catch((err) => {
// The Mistal SDK uses statusCode instead of status
@@ -58,7 +62,20 @@ export class MistralHandler implements ApiHandler {
for await (const chunk of stream) {
const delta = chunk.data.choices[0]?.delta
- if (delta?.content) {
+ if (delta.toolCalls) {
+ for (const toolCall of delta.toolCalls) {
+ yield {
+ type: "tool_calls",
+ tool_call: {
+ function: {
+ id: toolCall.id,
+ name: toolCall.function.name,
+ arguments: JSON.stringify(toolCall.function.arguments),
+ },
+ },
+ }
+ }
+ } else if (delta?.content) {
let content: string = ""
if (typeof delta.content === "string") {
content = delta.content
diff --git a/src/core/api/providers/moonshot.ts b/src/core/api/providers/moonshot.ts
index 1c1fbebb..858c7a10 100644
--- a/src/core/api/providers/moonshot.ts
+++ b/src/core/api/providers/moonshot.ts
@@ -1,10 +1,12 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ModelInfo, MoonshotModelId, moonshotDefaultModelId, moonshotModels } from "@/shared/api"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface MoonshotHandlerOptions extends CommonApiHandlerOptions {
moonshotApiKey?: string
@@ -36,7 +38,7 @@ export class MoonshotHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -52,7 +54,11 @@ export class MoonshotHandler implements ApiHandler {
max_tokens: model.info.maxTokens,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -62,6 +68,10 @@ export class MoonshotHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
diff --git a/src/core/api/providers/nebius.ts b/src/core/api/providers/nebius.ts
index c3dfafa7..fb708fe3 100644
--- a/src/core/api/providers/nebius.ts
+++ b/src/core/api/providers/nebius.ts
@@ -1,11 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { type ModelInfo, type NebiusModelId, nebiusDefaultModelId, nebiusModels } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface NebiusHandlerOptions extends CommonApiHandlerOptions {
nebiusApiKey?: string
@@ -35,7 +37,7 @@ export class NebiusHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -49,7 +51,9 @@ export class NebiusHandler implements ApiHandler {
temperature: 0,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -59,6 +63,10 @@ export class NebiusHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
diff --git a/src/core/api/providers/oca.ts b/src/core/api/providers/oca.ts
index 4c21ac15..4e271faa 100644
--- a/src/core/api/providers/oca.ts
+++ b/src/core/api/providers/oca.ts
@@ -2,6 +2,7 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI, { APIError, OpenAIError } from "openai"
import type { FinalRequestOptions, Headers as OpenAIHeaders } from "openai/core"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { OcaAuthService } from "@/services/auth/oca/OcaAuthService"
import {
DEFAULT_EXTERNAL_OCA_BASE_URL,
@@ -14,6 +15,7 @@ import { ApiHandler, type CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
export interface OcaHandlerOptions extends CommonApiHandlerOptions {
ocaBaseUrl?: string
@@ -135,7 +137,7 @@ export class OcaHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
@@ -187,6 +189,8 @@ export class OcaHandler implements ApiHandler {
return message
})
+ const toolCallProcessor = new ToolCallProcessor()
+
const stream = await client.chat.completions.create({
model: this.options.ocaModelId || liteLlmDefaultModelId,
messages: [enhancedSystemMessage, ...enhancedMessages],
@@ -198,6 +202,7 @@ export class OcaHandler implements ApiHandler {
...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable
...(this.options.taskId && {
litellm_session_id: `cline-${this.options.taskId}`,
+ ...getOpenAIToolParams(tools),
}), // Add session ID for LiteLLM tracking
})
@@ -228,6 +233,10 @@ export class OcaHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Handle token usage information
if (chunk.usage) {
const totalCost =
diff --git a/src/core/api/providers/openai-native.ts b/src/core/api/providers/openai-native.ts
index b9009d55..bf681a77 100644
--- a/src/core/api/providers/openai-native.ts
+++ b/src/core/api/providers/openai-native.ts
@@ -2,11 +2,12 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, OpenAiNativeModelId, openAiNativeDefaultModelId, openAiNativeModels } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
-import type { ChatCompletionReasoningEffort } from "openai/resources/chat/completions"
+import type { ChatCompletionReasoningEffort, ChatCompletionTool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface OpenAiNativeHandlerOptions extends CommonApiHandlerOptions {
openAiNativeApiKey?: string
@@ -56,9 +57,14 @@ export class OpenAiNativeHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(
+ systemPrompt: string,
+ messages: Anthropic.Messages.MessageParam[],
+ tools?: ChatCompletionTool[],
+ ): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+ const toolCallProcessor = new ToolCallProcessor()
switch (model.id) {
case "o1":
@@ -114,6 +120,7 @@ export class OpenAiNativeHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
reasoning_effort: (this.options.reasoningEffort as ChatCompletionReasoningEffort) || "medium",
+ ...getOpenAIToolParams(tools),
})
for await (const chunk of stream) {
@@ -124,8 +131,17 @@ export class OpenAiNativeHandler implements ApiHandler {
text: delta.content,
}
}
+
+ if (delta?.tool_calls) {
+ try {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ } catch (error) {
+ console.error("Error processing tool call delta:", error, delta.tool_calls)
+ }
+ }
+
if (chunk.usage) {
- // Only last chunk contains usage
+ // Only last chunk contains usage - stream is ending
yield* this.yieldUsage(model.info, chunk.usage)
}
}
@@ -138,6 +154,7 @@ export class OpenAiNativeHandler implements ApiHandler {
messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
for await (const chunk of stream) {
@@ -148,8 +165,13 @@ export class OpenAiNativeHandler implements ApiHandler {
text: delta.content,
}
}
+
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
- // Only last chunk contains usage
+ // Only last chunk contains usage - stream is ending
yield* this.yieldUsage(model.info, chunk.usage)
}
}
diff --git a/src/core/api/providers/openai.ts b/src/core/api/providers/openai.ts
index 56e8a559..79c77c5f 100644
--- a/src/core/api/providers/openai.ts
+++ b/src/core/api/providers/openai.ts
@@ -1,12 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { azureOpenAiDefaultApiVersion, ModelInfo, OpenAiCompatibleModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI, { AzureOpenAI } from "openai"
-import type { ChatCompletionReasoningEffort } from "openai/resources/chat/completions"
+import type { ChatCompletionReasoningEffort, ChatCompletionTool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface OpenAiHandlerOptions extends CommonApiHandlerOptions {
openAiApiKey?: string
@@ -61,16 +62,17 @@ export class OpenAiHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(
+ systemPrompt: string,
+ messages: Anthropic.Messages.MessageParam[],
+ tools?: ChatCompletionTool[],
+ ): ApiStream {
const client = this.ensureClient()
const modelId = this.options.openAiModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
const isR1FormatRequired = this.options.openAiModelInfo?.isR1FormatRequired ?? false
const isReasoningModelFamily =
- modelId.includes("o1") ||
- modelId.includes("o3") ||
- modelId.includes("o4") ||
- (modelId.includes("gpt-5") && !modelId.includes("chat"))
+ ["o1", "o3", "o4", "gpt-5"].some((prefix) => modelId.includes(prefix)) && !modelId.includes("chat")
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
@@ -104,7 +106,11 @@ export class OpenAiHandler implements ApiHandler {
reasoning_effort: reasoningEffort,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -121,12 +127,15 @@ export class OpenAiHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
- // @ts-ignore-next-line
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
// @ts-ignore-next-line
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
diff --git a/src/core/api/providers/openrouter.ts b/src/core/api/providers/openrouter.ts
index 6340c72b..73a2a821 100644
--- a/src/core/api/providers/openrouter.ts
+++ b/src/core/api/providers/openrouter.ts
@@ -4,10 +4,12 @@ import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import axios from "axios"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { createOpenRouterStream } from "../transform/openrouter-stream"
import { ApiStream, ApiStreamUsageChunk } from "../transform/stream"
+import { ToolCallProcessor } from "../transform/tool-call-processor"
import { OpenRouterErrorResponse } from "./types"
interface OpenRouterHandlerOptions extends CommonApiHandlerOptions {
@@ -50,7 +52,7 @@ export class OpenRouterHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
this.lastGenerationId = undefined
@@ -62,9 +64,11 @@ export class OpenRouterHandler implements ApiHandler {
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
+ tools,
)
let didOutputUsage: boolean = false
+ const toolCallProcessor = new ToolCallProcessor()
for await (const chunk of stream) {
// openrouter returns an error object instead of the openai sdk throwing an error
@@ -112,6 +116,10 @@ export class OpenRouterHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Reasoning tokens are returned separately from the content
// Skip reasoning content for Grok 4 models since it only displays "thinking" without providing useful information
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) {
diff --git a/src/core/api/providers/qwen-code.ts b/src/core/api/providers/qwen-code.ts
index ff64b51c..ee927641 100644
--- a/src/core/api/providers/qwen-code.ts
+++ b/src/core/api/providers/qwen-code.ts
@@ -2,12 +2,14 @@ import { promises as fs } from "node:fs"
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, QwenCodeModelId, qwenCodeDefaultModelId, qwenCodeModels } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import * as os from "os"
import * as path from "path"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
// --- Constants for Qwen OAuth2 ---
const QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai"
@@ -174,7 +176,7 @@ export class QwenCodeHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
await this.ensureAuthenticated()
const client = this.ensureClient()
const model = this.getModel()
@@ -193,10 +195,12 @@ export class QwenCodeHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
max_completion_tokens: model.info.maxTokens,
+ ...getOpenAIToolParams(tools),
}
const stream = await this.callApiWithRetry(() => client.chat.completions.create(requestOptions))
+ const toolCallProcessor = new ToolCallProcessor()
let fullContent = ""
for await (const apiChunk of stream) {
@@ -240,6 +244,10 @@ export class QwenCodeHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
// Handle reasoning content (o1-style)
if ("reasoning_content" in delta && delta.reasoning_content) {
yield {
diff --git a/src/core/api/providers/qwen.ts b/src/core/api/providers/qwen.ts
index 063dc9ff..23bb3f21 100644
--- a/src/core/api/providers/qwen.ts
+++ b/src/core/api/providers/qwen.ts
@@ -10,11 +10,13 @@ import {
QwenApiRegions,
} from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface QwenHandlerOptions extends CommonApiHandlerOptions {
qwenApiKey?: string
@@ -77,7 +79,7 @@ export class QwenHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const isDeepseekReasoner = model.id.includes("deepseek-r1")
@@ -112,8 +114,11 @@ export class QwenHandler implements ApiHandler {
stream_options: { include_usage: true },
temperature,
...thinkingArgs,
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -123,6 +128,14 @@ export class QwenHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ try {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ } catch (error) {
+ console.error("Error processing tool call delta:", error, delta.tool_calls)
+ }
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
diff --git a/src/core/api/providers/sambanova.ts b/src/core/api/providers/sambanova.ts
index 4c49a426..8626774f 100644
--- a/src/core/api/providers/sambanova.ts
+++ b/src/core/api/providers/sambanova.ts
@@ -1,11 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, SambanovaModelId, sambanovaDefaultModelId, sambanovaModels } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface SambanovaHandlerOptions extends CommonApiHandlerOptions {
sambanovaApiKey?: string
@@ -38,7 +40,7 @@ export class SambanovaHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -53,12 +55,14 @@ export class SambanovaHandler implements ApiHandler {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
+ const toolCallProcessor = new ToolCallProcessor()
const stream = await client.chat.completions.create({
model: this.getModel().id,
messages: openAiMessages,
temperature: 0,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
for await (const chunk of stream) {
@@ -70,6 +74,10 @@ export class SambanovaHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield {
type: "usage",
diff --git a/src/core/api/providers/together.ts b/src/core/api/providers/together.ts
index 017403d5..0e6106a1 100644
--- a/src/core/api/providers/together.ts
+++ b/src/core/api/providers/together.ts
@@ -1,11 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface TogetherHandlerOptions extends CommonApiHandlerOptions {
togetherApiKey?: string
@@ -38,7 +40,7 @@ export class TogetherHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.togetherModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
@@ -58,7 +60,9 @@ export class TogetherHandler implements ApiHandler {
temperature: 0,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -68,6 +72,10 @@ export class TogetherHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
diff --git a/src/core/api/providers/vercel-ai-gateway.ts b/src/core/api/providers/vercel-ai-gateway.ts
index 6375a824..f08c5736 100644
--- a/src/core/api/providers/vercel-ai-gateway.ts
+++ b/src/core/api/providers/vercel-ai-gateway.ts
@@ -1,9 +1,11 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, vercelAiGatewayDefaultModelId, vercelAiGatewayDefaultModelInfo } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
+import { ToolCallProcessor } from "../transform/tool-call-processor"
import { createVercelAIGatewayStream } from "../transform/vercel-ai-gateway-stream"
interface VercelAIGatewayHandlerOptions extends CommonApiHandlerOptions {
@@ -42,15 +44,23 @@ export class VercelAIGatewayHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.getModel().id
const modelInfo = this.getModel().info
try {
- const stream = await createVercelAIGatewayStream(client, systemPrompt, messages, { id: modelId, info: modelInfo })
+ const stream = await createVercelAIGatewayStream(
+ client,
+ systemPrompt,
+ messages,
+ { id: modelId, info: modelInfo },
+ tools,
+ )
let didOutputUsage: boolean = false
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -60,6 +70,10 @@ export class VercelAIGatewayHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (!didOutputUsage && chunk.usage) {
const inputTokens = chunk.usage.prompt_tokens || 0
const outputTokens =
diff --git a/src/core/api/providers/vertex.ts b/src/core/api/providers/vertex.ts
index e8ed7706..1232966e 100644
--- a/src/core/api/providers/vertex.ts
+++ b/src/core/api/providers/vertex.ts
@@ -1,6 +1,9 @@
import { Anthropic } from "@anthropic-ai/sdk"
+import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"
+import { FunctionDeclaration as GoogleTool } from "@google/genai"
import { ModelInfo, VertexModelId, vertexDefaultModelId, vertexModels } from "@shared/api"
+import { ClineTool } from "@/shared/tools"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
@@ -63,14 +66,14 @@ export class VertexHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream {
const model = this.getModel()
const modelId = model.id
// For Gemini models, use the GeminiHandler
if (!modelId.includes("claude")) {
const geminiHandler = this.ensureGeminiHandler()
- yield* geminiHandler.createMessage(systemPrompt, messages)
+ yield* geminiHandler.createMessage(systemPrompt, messages, tools as GoogleTool[])
return
}
@@ -160,6 +163,12 @@ export class VertexHandler implements ApiHandler {
}
}),
stream: true,
+ tools: tools?.length ? (tools as AnthropicTool[]) : undefined,
+ // tool_choice options:
+ // - none: disables tool use, even if tools are provided. Claude will not call any tools.
+ // - auto: allows Claude to decide whether to call any provided tools or not. This is the default value when tools are provided.
+ // - any: tells Claude that it must use one of the provided tools, but doesn’t force a particular tool.
+ tool_choice: tools ? { type: "any" } : undefined,
},
{
headers: {},
@@ -191,11 +200,19 @@ export class VertexHandler implements ApiHandler {
: message.content,
})),
stream: true,
+ tools: tools?.length ? (tools as AnthropicTool[]) : undefined,
+ // tool_choice options:
+ // - none: disables tool use, even if tools are provided. Claude will not call any tools.
+ // - auto: allows Claude to decide whether to call any provided tools or not. This is the default value when tools are provided.
+ // - any: tells Claude that it must use one of the provided tools, but doesn’t force a particular tool.
+ tool_choice: tools ? { type: "any" } : undefined,
})
break
}
}
+ const lastStartedToolCall = { id: "", name: "", arguments: "" }
+
for await (const chunk of stream) {
switch (chunk?.type) {
case "message_start":
@@ -233,6 +250,14 @@ export class VertexHandler implements ApiHandler {
reasoning: "[Redacted thinking block]",
}
break
+ case "tool_use":
+ if (chunk.content_block.id && chunk.content_block.name) {
+ // Convert Anthropic tool_use to OpenAI-compatible format
+ lastStartedToolCall.id = chunk.content_block.id
+ lastStartedToolCall.name = chunk.content_block.name
+ lastStartedToolCall.arguments = ""
+ }
+ break
case "text":
if (chunk.index > 0) {
yield {
@@ -255,6 +280,22 @@ export class VertexHandler implements ApiHandler {
reasoning: chunk.delta.thinking,
}
break
+ case "input_json_delta":
+ if (lastStartedToolCall.id && lastStartedToolCall.name && chunk.delta.partial_json) {
+ // // Convert Anthropic tool_use to OpenAI-compatible format
+ yield {
+ type: "tool_calls",
+ tool_call: {
+ ...lastStartedToolCall,
+ function: {
+ id: lastStartedToolCall.id,
+ name: lastStartedToolCall.name,
+ arguments: chunk.delta.partial_json,
+ },
+ },
+ }
+ }
+ break
case "text_delta":
yield {
type: "text",
@@ -264,6 +305,9 @@ export class VertexHandler implements ApiHandler {
}
break
case "content_block_stop":
+ lastStartedToolCall.id = ""
+ lastStartedToolCall.name = ""
+ lastStartedToolCall.arguments = ""
break
}
}
diff --git a/src/core/api/providers/xai.ts b/src/core/api/providers/xai.ts
index 013572b1..7b10b4ad 100644
--- a/src/core/api/providers/xai.ts
+++ b/src/core/api/providers/xai.ts
@@ -2,11 +2,13 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, XAIModelId, xaiDefaultModelId, xaiModels } from "@shared/api"
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ChatCompletionReasoningEffort } from "openai/resources/chat/completions"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface XAIHandlerOptions extends CommonApiHandlerOptions {
xaiApiKey?: string
@@ -40,7 +42,7 @@ export class XAIHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.getModel().id
// ensure reasoning effort is either "low" or "high" for grok-3-mini
@@ -59,8 +61,11 @@ export class XAIHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
reasoning_effort: reasoningEffort,
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -70,6 +75,10 @@ export class XAIHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
// Skip reasoning content for Grok 4 models since it only displays "thinking" without providing useful information
if (!shouldSkipReasoningForModel(modelId)) {
diff --git a/src/core/api/providers/zai.ts b/src/core/api/providers/zai.ts
index cf251c43..6da50264 100644
--- a/src/core/api/providers/zai.ts
+++ b/src/core/api/providers/zai.ts
@@ -9,11 +9,13 @@ import {
mainlandZAiModels,
} from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { version as extensionVersion } from "../../../../package.json"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
+import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
interface ZAiHandlerOptions extends CommonApiHandlerOptions {
zaiApiLine?: string
@@ -72,7 +74,7 @@ export class ZAiHandler implements ApiHandler {
}
@withRetry()
- async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+ async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -85,8 +87,11 @@ export class ZAiHandler implements ApiHandler {
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
+ ...getOpenAIToolParams(tools),
})
+ const toolCallProcessor = new ToolCallProcessor()
+
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
@@ -96,6 +101,10 @@ export class ZAiHandler implements ApiHandler {
}
}
+ if (delta?.tool_calls) {
+ yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
+ }
+
if (chunk.usage) {
yield {
type: "usage",
diff --git a/src/core/api/transform/anthropic-format.ts b/src/core/api/transform/anthropic-format.ts
new file mode 100644
index 00000000..3b73c557
--- /dev/null
+++ b/src/core/api/transform/anthropic-format.ts
@@ -0,0 +1,19 @@
+import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
+import { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
+
+/**
+ * Converts an OpenAI ChatCompletionTool into an Anthropic Tool definition
+ */
+export function openAIToolToAnthropic(openAITool: OpenAITool): AnthropicTool {
+ const func = openAITool.function
+
+ return {
+ name: func.name,
+ description: func.description || "",
+ input_schema: {
+ type: "object",
+ properties: func.parameters?.properties || {},
+ required: func.parameters?.required || [],
+ },
+ }
+}
diff --git a/src/core/api/transform/gemini-format.ts b/src/core/api/transform/gemini-format.ts
index f69935c6..f81a4c38 100644
--- a/src/core/api/transform/gemini-format.ts
+++ b/src/core/api/transform/gemini-format.ts
@@ -19,6 +19,22 @@ export function convertAnthropicContentToGemini(content: string | Anthropic.Cont
mimeType: block.source.media_type,
},
}
+ case "tool_use":
+ return {
+ functionCall: {
+ name: block.name,
+ args: block.input as Record,
+ },
+ }
+ case "tool_result":
+ return {
+ functionResponse: {
+ name: block.tool_use_id,
+ response: {
+ result: block.content,
+ },
+ },
+ }
default:
throw new Error(`Unsupported content block type: ${block.type}`)
}
diff --git a/src/core/api/transform/openai-format.ts b/src/core/api/transform/openai-format.ts
index e7cd684f..f5a6a63a 100644
--- a/src/core/api/transform/openai-format.ts
+++ b/src/core/api/transform/openai-format.ts
@@ -45,7 +45,7 @@ export function convertToOpenAiMessages(
if (typeof toolMessage.content === "string") {
content = toolMessage.content
- } else {
+ } else if (Array.isArray(toolMessage.content)) {
content =
toolMessage.content
?.map((part) => {
@@ -56,6 +56,9 @@ export function convertToOpenAiMessages(
return part.text
})
.join("\n") ?? ""
+ } else {
+ // Handle undefined content
+ content = ""
}
openAiMessages.push({
role: "tool",
@@ -70,15 +73,15 @@ export function convertToOpenAiMessages(
// Therefore we need to send these images after the tool result messages
// NOTE: it's actually okay to have multiple user messages in a row, the model will treat them as a continuation of the same input (this way works better than combining them into one message, since the tool result specifically mentions (see following user message for image)
// UPDATE v2.0: we don't use tools anymore, but if we did it's important to note that the openrouter prompt caching mechanism requires one user message at a time, so we would need to add these images to the user content array instead.
- // if (toolResultImages.length > 0) {
- // openAiMessages.push({
- // role: "user",
- // content: toolResultImages.map((part) => ({
- // type: "image_url",
- // image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
- // })),
- // })
- // }
+ if (toolResultImages.length > 0) {
+ openAiMessages.push({
+ role: "user",
+ content: toolResultImages.map((part) => ({
+ type: "image_url",
+ image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
+ })),
+ })
+ }
// Process non-tool messages
if (nonToolMessages.length > 0) {
@@ -157,7 +160,7 @@ export function convertToOpenAiMessages(
role: "assistant",
content,
// Cannot be an empty array. API expects an array with minimum length 1, and will respond with an error if it's empty
- tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
+ tool_calls: tool_calls?.length > 0 ? tool_calls : undefined,
// @ts-ignore-next-line
reasoning_details: reasoningDetails.length > 0 ? consolidateReasoningDetails(reasoningDetails) : undefined,
})
@@ -272,6 +275,9 @@ function consolidateReasoningDetails(reasoningDetails: ReasoningDetail[]): Reaso
return consolidated
}
+// Unique name to use to filter out tool call that cannot be parsed correctly
+const UNIQUE_ERROR_TOOL_NAME = "_cline_error_unknown_function_"
+
// Convert OpenAI response to Anthropic format
export function convertToAnthropicMessage(completion: OpenAI.Chat.Completions.ChatCompletion): Anthropic.Messages.Message {
const openAiMessage = completion.choices[0].message
@@ -308,24 +314,32 @@ export function convertToAnthropicMessage(completion: OpenAI.Chat.Completions.Ch
cache_read_input_tokens: null,
},
}
-
- if (openAiMessage.tool_calls && openAiMessage.tool_calls.length > 0) {
- anthropicMessage.content.push(
- ...openAiMessage.tool_calls.map((toolCall): Anthropic.ToolUseBlock => {
- let parsedInput = {}
- try {
- parsedInput = JSON.parse(toolCall.function.arguments || "{}")
- } catch (error) {
- console.error("Failed to parse tool arguments:", error)
- }
- return {
- type: "tool_use",
- id: toolCall.id,
- name: toolCall.function.name,
- input: parsedInput,
- }
- }),
- )
+ try {
+ if (openAiMessage?.tool_calls?.length) {
+ anthropicMessage.content.push(
+ ...openAiMessage.tool_calls
+ .map((toolCall): Anthropic.ToolUseBlock => {
+ const parsedName = toolCall.type === "function" && toolCall.function.name
+ let parsedInput = toolCall.function.arguments
+ try {
+ parsedInput = JSON.parse(toolCall.function.arguments || "{}")
+ } catch (error) {
+ console.error("Failed to parse tool arguments:", error)
+ }
+ return {
+ type: "tool_use",
+ id: toolCall.id,
+ name: parsedName || UNIQUE_ERROR_TOOL_NAME,
+ input: parsedInput,
+ }
+ })
+ // Filter out any tool uses with the UNIQUE_ERROR_TOOL_NAME, which indicates a parsing error
+ .filter((toolUse) => toolUse.name !== UNIQUE_ERROR_TOOL_NAME),
+ )
+ }
+ } catch (error) {
+ console.error("Failed to process tool calls:", error)
}
+
return anthropicMessage
}
diff --git a/src/core/api/transform/openrouter-stream.ts b/src/core/api/transform/openrouter-stream.ts
index 2628317c..2fe649a4 100644
--- a/src/core/api/transform/openrouter-stream.ts
+++ b/src/core/api/transform/openrouter-stream.ts
@@ -7,8 +7,10 @@ import {
openRouterClaudeSonnet451mModelId,
} from "@shared/api"
import OpenAI from "openai"
+import { ChatCompletionTool } from "openai/resources/chat/completions"
import { convertToOpenAiMessages } from "./openai-format"
import { convertToR1Format } from "./r1-format"
+import { getOpenAIToolParams } from "./tool-call-processor"
export async function createOpenRouterStream(
client: OpenAI,
@@ -18,6 +20,7 @@ export async function createOpenRouterStream(
reasoningEffort?: string,
thinkingBudgetTokens?: number,
openRouterProviderSorting?: string,
+ tools?: Array,
) {
// Convert Anthropic messages to OpenAI format
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -185,6 +188,7 @@ export async function createOpenRouterStream(
...(openRouterProviderSorting && !providerPreferences ? { provider: { sort: openRouterProviderSorting } } : {}),
...(providerPreferences ? { provider: providerPreferences } : {}),
...(isClaudeSonnet1m ? { provider: { order: ["anthropic", "google-vertex/global"], allow_fallbacks: false } } : {}),
+ ...getOpenAIToolParams(tools),
})
return stream
diff --git a/src/core/api/transform/stream.ts b/src/core/api/transform/stream.ts
index 6fae3fc2..ab546075 100644
--- a/src/core/api/transform/stream.ts
+++ b/src/core/api/transform/stream.ts
@@ -6,6 +6,7 @@ export type ApiStreamChunk =
| ApiStreamAnthropicThinkingChunk
| ApiStreamAnthropicRedactedThinkingChunk
| ApiStreamUsageChunk
+ | ApiStreamToolCallsChunk
export interface ApiStreamTextChunk {
type: "text"
@@ -42,3 +43,18 @@ export interface ApiStreamUsageChunk {
thoughtsTokenCount?: number // openrouter
totalCost?: number // openrouter
}
+
+export interface ApiStreamToolCallsChunk {
+ type: "tool_calls"
+ tool_call: ApiStreamToolCall
+}
+
+export interface ApiStreamToolCall {
+ call_id?: string // The call / request ID associated with this tool call
+ // Information about the tool being called
+ function: {
+ id?: string // The tool call ID
+ name?: string
+ arguments?: any
+ }
+}
diff --git a/src/core/api/transform/tool-call-processor.ts b/src/core/api/transform/tool-call-processor.ts
new file mode 100644
index 00000000..4f8a8aae
--- /dev/null
+++ b/src/core/api/transform/tool-call-processor.ts
@@ -0,0 +1,87 @@
+import type {
+ ChatCompletionChunk,
+ ChatCompletionToolChoiceOption,
+ ChatCompletionTool as OpenAITool,
+} from "openai/resources/chat/completions"
+import { Logger } from "@/services/logging/Logger"
+import type { ApiStreamToolCallsChunk } from "./stream"
+
+/**
+ * Helper class to process tool call deltas from OpenAI-compatible streaming responses.
+ * Handles accumulating tool call ID and name across multiple delta chunks,
+ * and yields properly formatted tool call chunks when arguments are received.
+ */
+export class ToolCallProcessor {
+ private lastToolCall: { id: string; name: string }
+
+ constructor() {
+ this.lastToolCall = { id: "", name: "" }
+ }
+
+ /**
+ * Process tool call deltas from a chunk and yield formatted tool call chunks.
+ * @param toolCallDeltas - Array of tool call deltas from the chunk
+ * @yields Formatted tool call chunks ready to be yielded in the API stream
+ */
+ *processToolCallDeltas(
+ toolCallDeltas: ChatCompletionChunk.Choice.Delta.ToolCall[] | undefined,
+ ): Generator {
+ if (!toolCallDeltas) {
+ return
+ }
+
+ for (const toolCallDelta of toolCallDeltas) {
+ // Accumulate the tool call ID if present
+ if (toolCallDelta.id) {
+ this.lastToolCall.id = toolCallDelta.id
+ }
+
+ // Accumulate the function name if present
+ if (toolCallDelta.function?.name) {
+ Logger.debug(`[ToolCallProcessor] Native Tool Called: ${toolCallDelta.function.name}`)
+ this.lastToolCall.name = toolCallDelta.function.name
+ }
+
+ // Only yield when we have all required fields: id, name, and arguments
+ if (this.lastToolCall.id && this.lastToolCall.name && toolCallDelta.function?.arguments) {
+ yield {
+ type: "tool_calls",
+ tool_call: {
+ ...toolCallDelta,
+ function: {
+ ...toolCallDelta.function,
+ id: this.lastToolCall.id,
+ name: this.lastToolCall.name,
+ },
+ },
+ }
+ }
+ }
+ }
+
+ /**
+ * Reset the internal state. Call this when starting a new message.
+ */
+ reset(): void {
+ this.lastToolCall = { id: "", name: "" }
+ }
+
+ /**
+ * Get the current accumulated tool call state (useful for debugging).
+ */
+ getState(): { id: string; name: string } {
+ return { ...this.lastToolCall }
+ }
+}
+
+export function getOpenAIToolParams(tools?: OpenAITool[]) {
+ return tools?.length
+ ? {
+ tools,
+ tool_choice: tools ? ("auto" as ChatCompletionToolChoiceOption) : undefined,
+ parallel_tool_calls: tools ? true : undefined,
+ }
+ : {
+ tools: undefined,
+ }
+}
diff --git a/src/core/api/transform/tool-use-handler.ts b/src/core/api/transform/tool-use-handler.ts
new file mode 100644
index 00000000..9047e404
--- /dev/null
+++ b/src/core/api/transform/tool-use-handler.ts
@@ -0,0 +1,189 @@
+import { Anthropic } from "@anthropic-ai/sdk"
+import type { ToolUse } from "@core/assistant-message"
+import { JSONParser } from "@streamparser/json"
+import { CLINE_MCP_TOOL_IDENTIFIER } from "@/shared/mcp"
+import { ClineDefaultTool } from "@/shared/tools"
+
+export interface PendingToolUse {
+ id: string
+ name: string
+ input: string
+ parsedInput?: unknown
+ jsonParser?: JSONParser
+ call_id?: string
+}
+
+interface ToolUseDeltaBlock {
+ id?: string
+ type?: string
+ name?: string
+ input?: string
+}
+
+const ESCAPE_MAP: Record = {
+ "\\n": "\n",
+ "\\t": "\t",
+ "\\r": "\r",
+ '\\"': '"',
+ "\\\\": "\\",
+}
+
+const ESCAPE_PATTERN = /\\[ntr"\\]/g
+
+/**
+ * Handles streaming tool use blocks and converts them to Anthropic.ToolUseBlockParam format
+ */
+export class ToolUseHandler {
+ private pendingToolUses = new Map()
+
+ processToolUseDelta(delta: ToolUseDeltaBlock, call_id?: string): void {
+ if (delta.type !== "tool_use" || !delta.id) {
+ return
+ }
+
+ let pending = this.pendingToolUses.get(delta.id)
+ if (!pending) {
+ pending = this.createPendingToolUse(delta.id, delta.name || "", call_id)
+ }
+
+ if (delta.name) {
+ pending.name = delta.name
+ }
+ if (delta.input) {
+ pending.input += delta.input
+ try {
+ pending.jsonParser?.write(delta.input)
+ } catch {
+ // Expected during streaming
+ }
+ }
+ }
+
+ getFinalizedToolUse(id: string): Anthropic.ToolUseBlockParam | undefined {
+ const pending = this.pendingToolUses.get(id)
+ if (!pending?.name) {
+ return undefined
+ }
+
+ let input: unknown = {}
+ if (pending.parsedInput != null) {
+ input = pending.parsedInput
+ } else if (pending.input) {
+ try {
+ input = JSON.parse(pending.input)
+ } catch {
+ input = this.extractPartialJsonFields(pending.input)
+ }
+ }
+
+ return {
+ type: "tool_use",
+ id: pending.id,
+ name: pending.name,
+ input,
+ }
+ }
+
+ getAllFinalizedToolUses(): Anthropic.ToolUseBlockParam[] {
+ const results: Anthropic.ToolUseBlockParam[] = []
+ for (const id of this.pendingToolUses.keys()) {
+ const toolUse = this.getFinalizedToolUse(id)
+ if (toolUse) {
+ results.push(toolUse)
+ }
+ }
+ return results
+ }
+
+ hasToolUse(id: string): boolean {
+ return this.pendingToolUses.has(id)
+ }
+
+ getPartialToolUsesAsContent(): ToolUse[] {
+ const results: ToolUse[] = []
+
+ for (const pending of this.pendingToolUses.values()) {
+ if (!pending.name) {
+ continue
+ }
+
+ let input: any = {}
+ if (pending.parsedInput != null) {
+ input = pending.parsedInput
+ } else if (pending.input) {
+ try {
+ input = JSON.parse(pending.input)
+ } catch {
+ input = this.extractPartialJsonFields(pending.input)
+ }
+ }
+
+ if (pending.name.includes(CLINE_MCP_TOOL_IDENTIFIER)) {
+ const [serverName, toolName] = pending.name.split(CLINE_MCP_TOOL_IDENTIFIER)
+ results.push({
+ type: "tool_use",
+ name: ClineDefaultTool.MCP_USE,
+ params: {
+ server_name: serverName,
+ tool_name: toolName,
+ arguments: JSON.stringify(input),
+ },
+ partial: true,
+ })
+ } else {
+ const params: Record = {}
+ if (typeof input === "object") {
+ for (const [key, value] of Object.entries(input)) {
+ params[key] = typeof value === "string" ? value : JSON.stringify(value)
+ }
+ }
+ results.push({
+ type: "tool_use",
+ name: pending.name as ClineDefaultTool,
+ params: params as any,
+ partial: true,
+ })
+ }
+ }
+
+ return results
+ }
+
+ reset(): void {
+ this.pendingToolUses.clear()
+ }
+
+ private createPendingToolUse(id: string, name: string, call_id?: string): PendingToolUse {
+ const jsonParser = new JSONParser()
+ const pending: PendingToolUse = {
+ id,
+ name,
+ input: "",
+ parsedInput: undefined,
+ jsonParser,
+ call_id,
+ }
+
+ jsonParser.onValue = (info: any) => {
+ if (info.stack.length === 0 && info.value && typeof info.value === "object") {
+ pending.parsedInput = info.value
+ }
+ }
+
+ jsonParser.onError = () => {}
+
+ this.pendingToolUses.set(id, pending)
+ return pending
+ }
+
+ private extractPartialJsonFields(partialJson: string): Record {
+ const result: Record = {}
+ const pattern = /"(\w+)":\s*"((?:[^"\\]|\\.)*)(?:")?/g
+
+ for (const match of partialJson.matchAll(pattern)) {
+ result[match[1]] = match[2].replace(ESCAPE_PATTERN, (m) => ESCAPE_MAP[m])
+ }
+
+ return result
+ }
+}
diff --git a/src/core/api/transform/vercel-ai-gateway-stream.ts b/src/core/api/transform/vercel-ai-gateway-stream.ts
index fdbf1691..1a0c108e 100644
--- a/src/core/api/transform/vercel-ai-gateway-stream.ts
+++ b/src/core/api/transform/vercel-ai-gateway-stream.ts
@@ -1,13 +1,16 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "@shared/api"
import OpenAI from "openai"
+import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { convertToOpenAiMessages } from "../transform/openai-format"
+import { getOpenAIToolParams } from "./tool-call-processor"
export async function createVercelAIGatewayStream(
client: OpenAI,
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
model: { id: string; info: ModelInfo },
+ tools?: OpenAITool[],
) {
// Convert Anthropic messages to OpenAI format
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -49,6 +52,7 @@ export async function createVercelAIGatewayStream(
temperature: 0.7,
messages: openAiMessages,
stream: true,
+ ...getOpenAIToolParams(tools),
})
return stream
diff --git a/src/core/assistant-message/index.ts b/src/core/assistant-message/index.ts
index a121a0c6..20cc2a28 100644
--- a/src/core/assistant-message/index.ts
+++ b/src/core/assistant-message/index.ts
@@ -13,6 +13,7 @@ export const toolParamNames = [
"command",
"requires_approval",
"path",
+ "absolutePath",
"content",
"diff",
"regex",
@@ -39,6 +40,7 @@ export const toolParamNames = [
"needs_more_exploration",
"task_progress",
"timeout",
+ "input",
] as const
export type ToolParamName = (typeof toolParamNames)[number]
diff --git a/src/core/context/context-management/ContextManager.ts b/src/core/context/context-management/ContextManager.ts
index b7e6caff..fbe2b4dd 100644
--- a/src/core/context/context-management/ContextManager.ts
+++ b/src/core/context/context-management/ContextManager.ts
@@ -329,10 +329,128 @@ export class ContextManager {
const updatedMessages = this.applyContextHistoryUpdates(messages, deletedRange ? deletedRange[1] + 1 : 2)
+ // Validate and fix tool_use/tool_result pairing
+ this.ensureToolResultsFollowToolUse(updatedMessages)
+
// OLD NOTE: if you try to console log these, don't forget that logging a reference to an array may not provide the same result as logging a slice() snapshot of that array at that exact moment. The following DOES in fact include the latest assistant message.
return updatedMessages
}
+ /**
+ * Ensures that every tool_use block in assistant messages has a corresponding tool_result in the next user message,
+ * and that tool_result blocks immediately follow their corresponding tool_use blocks
+ */
+ private ensureToolResultsFollowToolUse(messages: Anthropic.Messages.MessageParam[]): void {
+ for (let i = 0; i < messages.length - 1; i++) {
+ const message = messages[i]
+
+ // Only process assistant messages with content
+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
+ continue
+ }
+
+ // Extract tool_use IDs in order
+ const toolUseIds: string[] = []
+ for (const block of message.content) {
+ if (block.type === "tool_use" && block.id) {
+ toolUseIds.push(block.id)
+ }
+ }
+
+ // Skip if no tool_use blocks found
+ if (toolUseIds.length === 0) {
+ continue
+ }
+
+ const nextMessage = messages[i + 1]
+
+ // Skip if next message is not a user message
+ if (nextMessage.role !== "user") {
+ continue
+ }
+
+ // Ensure content is an array
+ if (!Array.isArray(nextMessage.content)) {
+ nextMessage.content = []
+ }
+
+ // Separate tool_results from other blocks in a single pass
+ const toolResultMap = new Map()
+ const otherBlocks: Anthropic.Messages.ContentBlockParam[] = []
+ let needsUpdate = false
+
+ for (const block of nextMessage.content) {
+ if (block.type === "tool_result" && block.tool_use_id) {
+ toolResultMap.set(block.tool_use_id, block)
+ } else {
+ otherBlocks.push(block)
+ }
+ }
+
+ // Check if reordering is needed (tool_results not at start in correct order)
+ if (toolResultMap.size > 0) {
+ let expectedIndex = 0
+ for (let j = 0; j < nextMessage.content.length && expectedIndex < toolUseIds.length; j++) {
+ const block = nextMessage.content[j]
+ if (block.type === "tool_result" && block.tool_use_id === toolUseIds[expectedIndex]) {
+ expectedIndex++
+ } else if (block.type === "tool_result" || expectedIndex < toolUseIds.length) {
+ needsUpdate = true
+ break
+ }
+ }
+ if (!needsUpdate && expectedIndex < toolResultMap.size) {
+ needsUpdate = true
+ }
+ }
+
+ // Add missing tool_results
+ for (const toolUseId of toolUseIds) {
+ if (!toolResultMap.has(toolUseId)) {
+ toolResultMap.set(toolUseId, {
+ type: "tool_result",
+ tool_use_id: toolUseId,
+ content: "result missing",
+ })
+ needsUpdate = true
+ }
+ }
+
+ // Only modify if changes are needed
+ if (!needsUpdate) {
+ continue
+ }
+
+ // Build new content: tool_results first (in toolUseIds order), then other blocks
+ const newContent: Anthropic.Messages.ContentBlockParam[] = []
+
+ // Add tool_results in the order of toolUseIds
+ const processedToolResults = new Set()
+ for (const toolUseId of toolUseIds) {
+ const toolResult = toolResultMap.get(toolUseId)
+ if (toolResult) {
+ newContent.push(toolResult)
+ processedToolResults.add(toolUseId)
+ }
+ }
+
+ // Add any orphaned tool_results not in toolUseIds (shouldn't happen, but be safe)
+ for (const [toolUseId, toolResult] of toolResultMap) {
+ if (!processedToolResults.has(toolUseId)) {
+ newContent.push(toolResult)
+ }
+ }
+
+ // Add all other blocks
+ newContent.push(...otherBlocks)
+
+ // Clone and update the message
+ const clonedMessage = cloneDeep(nextMessage)
+ clonedMessage.content = newContent
+ messages[i + 1] = clonedMessage
+ }
+ }
+
/**
* applies deletedRange truncation and other alterations based on changes in this.contextHistoryUpdates
*/
diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts
index 328e9894..00c012bb 100644
--- a/src/core/prompts/responses.ts
+++ b/src/core/prompts/responses.ts
@@ -25,8 +25,10 @@ export const formatResponse = {
clineIgnoreError: (path: string) =>
`Access to ${path} is blocked by the .clineignore file settings. You must try to continue in the task without using this file, or ask the user to update the .clineignore file.`,
- noToolsUsed: () =>
- `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
+ noToolsUsed: (usingNativeToolCalls: boolean) =>
+ usingNativeToolCalls
+ ? "[ERROR] You did not use a tool in your previous response! Please retry with a tool use."
+ : `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
${toolUseInstructionsReminder}
@@ -284,21 +286,16 @@ const formatImagesIntoBlocks = (images?: string[]): Anthropic.ImageBlockParam[]
}
const toolUseInstructionsReminder = `# Reminder: Instructions for Tool Use
-
Tool uses are formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
-
value1value2
...
-
For example:
-
I have completed the task...
-
Always adhere to this format for all tool uses to ensure proper parsing and execution.`
diff --git a/src/core/prompts/system-prompt/README.md b/src/core/prompts/system-prompt/README.md
index 25ffa2eb..9aeccc44 100644
--- a/src/core/prompts/system-prompt/README.md
+++ b/src/core/prompts/system-prompt/README.md
@@ -97,7 +97,7 @@ class PromptRegistry {
await this.load()
// Try model family fallback (e.g., "claude-4" -> "claude")
- const modelFamily = getModelFamily(context.providerInfo)
+ const modelFamily = this.getModelFamily(context.providerInfo)
const variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC)
if (!variant) {
@@ -225,7 +225,7 @@ class PromptBuilder {
// Add standard system placeholders
placeholders[STANDARD_PLACEHOLDERS.CWD] = this.context.cwd || process.cwd();
placeholders[STANDARD_PLACEHOLDERS.SUPPORTS_BROWSER] = this.context.supportsBrowserUse || false;
- placeholders[STANDARD_PLACEHOLDERS.MODEL_FAMILY] = getModelFamily(this.variant.id);
+ placeholders[STANDARD_PLACEHOLDERS.MODEL_FAMILY] = this.variant.family;
placeholders[STANDARD_PLACEHOLDERS.CURRENT_DATE] = new Date().toISOString().split("T")[0];
// Add all component sections
diff --git a/src/core/prompts/system-prompt/__tests__/PromptBuilder.test.ts b/src/core/prompts/system-prompt/__tests__/PromptBuilder.test.ts
index 40966bb1..e7df788b 100644
--- a/src/core/prompts/system-prompt/__tests__/PromptBuilder.test.ts
+++ b/src/core/prompts/system-prompt/__tests__/PromptBuilder.test.ts
@@ -44,6 +44,7 @@ describe("PromptBuilder", () => {
const baseVariant: PromptVariant = {
id: "test-model",
family: ModelFamily.GENERIC,
+ matcher: () => true,
version: 1,
description: "A test model",
tags: ["test"],
@@ -259,6 +260,7 @@ describe("PromptBuilder", () => {
SystemPromptSection.CAPABILITIES,
SystemPromptSection.RULES,
)
+ .matcher(() => true)
.build()
// Should have auto-generated a baseTemplate
@@ -295,6 +297,7 @@ describe("PromptBuilder", () => {
.description("Test variant with explicit template")
.version(1)
.template(customTemplate)
+ .matcher(() => true)
.components(SystemPromptSection.AGENT_ROLE, SystemPromptSection.TOOL_USE)
.build()
@@ -307,6 +310,7 @@ describe("PromptBuilder", () => {
createVariant(ModelFamily.GENERIC)
.description("Test variant with empty components")
.version(1)
+ .matcher(() => true)
.components() // Empty components
.build()
}).to.throw("Component order is required")
diff --git a/src/core/prompts/system-prompt/__tests__/PromptRegistry.test.ts b/src/core/prompts/system-prompt/__tests__/PromptRegistry.test.ts
index 97f0a6d5..e6734b2f 100644
--- a/src/core/prompts/system-prompt/__tests__/PromptRegistry.test.ts
+++ b/src/core/prompts/system-prompt/__tests__/PromptRegistry.test.ts
@@ -1,7 +1,6 @@
import { expect } from "chai"
import type { McpHub } from "@/services/mcp/McpHub"
import { ModelFamily } from "@/shared/prompts"
-import { getModelFamily } from ".."
import { PromptRegistry } from "../registry/PromptRegistry"
import type { SystemPromptContext } from "../types"
import { mockProviderInfo } from "./integration.test"
@@ -49,7 +48,9 @@ describe("PromptRegistry", () => {
})
describe("getModelFamily", () => {
- it("should extract correct model families", () => {
+ it("should extract correct model families", async () => {
+ const registry = PromptRegistry.getInstance()
+ await registry.load()
const testCases = [
{ id: "claude-3-5-sonnet", expected: ModelFamily.GENERIC },
{ id: "gpt-4-turbo", expected: ModelFamily.GENERIC },
@@ -59,17 +60,23 @@ describe("PromptRegistry", () => {
{ id: "openai/gpt-4", expected: ModelFamily.GENERIC },
{ id: "google/gemini", expected: ModelFamily.GENERIC },
{ id: "claude-sonnet-4", expected: ModelFamily.NEXT_GEN },
- { id: "gpt-5", expected: ModelFamily.GPT_5 },
- { id: "openai/gpt-5", expected: ModelFamily.GPT_5 },
+ { id: "gpt-5", provider: "cline", expected: ModelFamily.NATIVE_GPT_5, useNativeTools: true },
+ { id: "gpt-5", provider: "openai-native", expected: ModelFamily.NATIVE_GPT_5, useNativeTools: true },
+ { id: "gpt-5", provider: "cline", expected: ModelFamily.GPT_5, useNativeTools: false },
+ { id: "openai/gpt-5", expected: ModelFamily.NEXT_GEN },
{ id: "unknown-model", expected: ModelFamily.GENERIC },
]
- for (const { id, expected, provider } of testCases) {
+ for (const { id, expected, provider, useNativeTools } of testCases) {
const providerId = provider ?? "random"
const customPrompt = provider === "lmstudio" ? "compact" : undefined
const providerInfo = { ...mockProviderInfo, providerId, model: { ...mockProviderInfo.model, id }, customPrompt }
- const result = getModelFamily(providerInfo)
- expect(result).to.equal(expected)
+ const result = registry.getModelFamily({
+ ...mockContext,
+ providerInfo,
+ enableNativeToolCalls: useNativeTools ?? false,
+ })
+ expect(result).to.equal(expected, `Failed for model ${id} with provider ${providerId}`)
}
})
})
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-basic.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-basic.snap
new file mode 100644
index 00000000..44729f98
--- /dev/null
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-basic.snap
@@ -0,0 +1,98 @@
+You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
+
+TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
+
+====
+
+AUTOMATIC TODO LIST MANAGEMENT
+
+The system automatically manages todo lists to help track task progress:
+
+- Every 10th API request, you will be prompted to review and update the current todo list if one exists
+- When switching from PLAN MODE to ACT MODE, you should create a comprehensive todo list for the task
+- Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
+- Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
+- The system will automatically include todo list context in your prompts when appropriate
+- Focus on creating actionable, meaningful steps rather than granular technical details
+
+====
+
+ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task.
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
+
+====
+
+CAPABILITIES
+
+- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, use the browser, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
+- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/project') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
+- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
+- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
+ - For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
+- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.
+- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.
+ - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser.
+- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
+
+====
+
+FEEDBACK
+
+When user is providing you with feedback on how you could improve, you can let the user know to report new issue using the '/reportbug' slash command.
+
+====
+
+RULES
+
+- The current working directory is `/test/project` - this is the directory where all the tools will be executed from.
+
+====
+
+SYSTEM INFORMATION
+
+Operating System: macOS
+IDE: TestIde
+Default Shell: /bin/zsh
+Home Directory: /Users/tester
+Current Working Directory: /Users/tester/dev/project
+
+====
+
+OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. `open index.html` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.
+
+====
+
+USER'S CUSTOM INSTRUCTIONS
+
+The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
+
+Prefer TypeScript
+
+Follow global rules
+
+Follow local rules
\ No newline at end of file
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-browser.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-browser.snap
new file mode 100644
index 00000000..c04d8039
--- /dev/null
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-browser.snap
@@ -0,0 +1,96 @@
+You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
+
+TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
+
+====
+
+AUTOMATIC TODO LIST MANAGEMENT
+
+The system automatically manages todo lists to help track task progress:
+
+- Every 10th API request, you will be prompted to review and update the current todo list if one exists
+- When switching from PLAN MODE to ACT MODE, you should create a comprehensive todo list for the task
+- Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
+- Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
+- The system will automatically include todo list context in your prompts when appropriate
+- Focus on creating actionable, meaningful steps rather than granular technical details
+
+====
+
+ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task.
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
+
+====
+
+CAPABILITIES
+
+- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
+- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/project') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
+- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
+- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
+ - For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
+- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.
+- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
+
+====
+
+FEEDBACK
+
+When user is providing you with feedback on how you could improve, you can let the user know to report new issue using the '/reportbug' slash command.
+
+====
+
+RULES
+
+- The current working directory is `/test/project` - this is the directory where all the tools will be executed from.
+
+====
+
+SYSTEM INFORMATION
+
+Operating System: macOS
+IDE: TestIde
+Default Shell: /bin/zsh
+Home Directory: /Users/tester
+Current Working Directory: /Users/tester/dev/project
+
+====
+
+OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. `open index.html` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.
+
+====
+
+USER'S CUSTOM INSTRUCTIONS
+
+The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
+
+Prefer TypeScript
+
+Follow global rules
+
+Follow local rules
\ No newline at end of file
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-focus-chain.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-focus-chain.snap
new file mode 100644
index 00000000..07049eef
--- /dev/null
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-focus-chain.snap
@@ -0,0 +1,79 @@
+You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
+
+TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
+
+====
+
+ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task.
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
+
+====
+
+CAPABILITIES
+
+- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, use the browser, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
+- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/project') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
+- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
+- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
+ - For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
+- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.
+- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.
+ - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser.
+- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
+
+====
+
+RULES
+
+- The current working directory is `/test/project` - this is the directory where all the tools will be executed from.
+
+====
+
+SYSTEM INFORMATION
+
+Operating System: macOS
+IDE: TestIde
+Default Shell: /bin/zsh
+Home Directory: /Users/tester
+Current Working Directory: /Users/tester/dev/project
+
+====
+
+OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. `open index.html` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.
+
+====
+
+USER'S CUSTOM INSTRUCTIONS
+
+The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
+
+Prefer TypeScript
+
+Follow global rules
+
+Follow local rules
\ No newline at end of file
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-mcp.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-mcp.snap
new file mode 100644
index 00000000..44729f98
--- /dev/null
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/cline_claude_4_5_sonnet-no-mcp.snap
@@ -0,0 +1,98 @@
+You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
+
+TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
+
+====
+
+AUTOMATIC TODO LIST MANAGEMENT
+
+The system automatically manages todo lists to help track task progress:
+
+- Every 10th API request, you will be prompted to review and update the current todo list if one exists
+- When switching from PLAN MODE to ACT MODE, you should create a comprehensive todo list for the task
+- Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
+- Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
+- The system will automatically include todo list context in your prompts when appropriate
+- Focus on creating actionable, meaningful steps rather than granular technical details
+
+====
+
+ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task.
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
+
+====
+
+CAPABILITIES
+
+- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, use the browser, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
+- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/project') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
+- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
+- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
+ - For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
+- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.
+- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.
+ - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser.
+- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
+
+====
+
+FEEDBACK
+
+When user is providing you with feedback on how you could improve, you can let the user know to report new issue using the '/reportbug' slash command.
+
+====
+
+RULES
+
+- The current working directory is `/test/project` - this is the directory where all the tools will be executed from.
+
+====
+
+SYSTEM INFORMATION
+
+Operating System: macOS
+IDE: TestIde
+Default Shell: /bin/zsh
+Home Directory: /Users/tester
+Current Working Directory: /Users/tester/dev/project
+
+====
+
+OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. `open index.html` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.
+
+====
+
+USER'S CUSTOM INSTRUCTIONS
+
+The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
+
+Prefer TypeScript
+
+Follow global rules
+
+Follow local rules
\ No newline at end of file
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-basic.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-basic.snap
index c436d3db..1583261b 100644
--- a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-basic.snap
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-basic.snap
@@ -49,54 +49,69 @@ Usage:
Checklist here (optional)
-## write_to_file
-Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
-Parameters:
-- path: (required) The path of the file to write to (relative to the current working directory /test/project)
-- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
-- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
-Usage:
-
-File path here
-Your file content here
-Checklist here (optional)
-
+## apply_patch
+Description: This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
-## replace_in_file
-Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+[YOUR_PATCH]
+*** End Patch
+EOF
+
+Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
+
+*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
+For each snippet of code that needs to be changed, repeat the following:
+[context_before] -> See below for further instructions on context.
+- [old_code] -> Precede the old code with a minus sign.
++ [new_code] -> Precede the new, replacement code with a plus sign.
+[context_after] -> See below for further instructions on context.
+
+For instructions on [context_before] and [context_after]:
+- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
+- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
+@@ class BaseClass
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
+
+@@ class BaseClass
+@@ def method():
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/binary_search.py
+@@ class BaseClass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+@@ class Subclass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+*** End Patch
+EOF
Parameters:
-- path: (required) The path of the file to modify (relative to the current working directory /test/project)
-- diff: (required) One or more SEARCH/REPLACE blocks following this exact format:
- ```
- ------- SEARCH
- [exact content to find]
- =======
- [new content to replace with]
- +++++++ REPLACE
- ```
- Critical rules:
- 1. SEARCH content must match the associated file section to find EXACTLY:
- * Match character-for-character including whitespace, indentation, line endings
- * Include all comments, docstrings, etc.
- 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
- * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
- * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
- * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
- 3. Keep SEARCH/REPLACE blocks concise:
- * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
- * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
- * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
- * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
- 4. Special operations:
- * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
- * To delete code: Use empty REPLACE section
+- input: (required) The apply_patch command that you wish to execute.
- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
Usage:
-
-File path here
-Search and replace blocks here
+
+
Checklist here (optional)
-
+
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-browser.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-browser.snap
index f0f91ff3..272ed0c7 100644
--- a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-browser.snap
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-browser.snap
@@ -49,54 +49,69 @@ Usage:
Checklist here (optional)
-## write_to_file
-Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
-Parameters:
-- path: (required) The path of the file to write to (relative to the current working directory /test/project)
-- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
-- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
-Usage:
-
-File path here
-Your file content here
-Checklist here (optional)
-
+## apply_patch
+Description: This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
-## replace_in_file
-Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+[YOUR_PATCH]
+*** End Patch
+EOF
+
+Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
+
+*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
+For each snippet of code that needs to be changed, repeat the following:
+[context_before] -> See below for further instructions on context.
+- [old_code] -> Precede the old code with a minus sign.
++ [new_code] -> Precede the new, replacement code with a plus sign.
+[context_after] -> See below for further instructions on context.
+
+For instructions on [context_before] and [context_after]:
+- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
+- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
+@@ class BaseClass
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
+
+@@ class BaseClass
+@@ def method():
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/binary_search.py
+@@ class BaseClass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+@@ class Subclass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+*** End Patch
+EOF
Parameters:
-- path: (required) The path of the file to modify (relative to the current working directory /test/project)
-- diff: (required) One or more SEARCH/REPLACE blocks following this exact format:
- ```
- ------- SEARCH
- [exact content to find]
- =======
- [new content to replace with]
- +++++++ REPLACE
- ```
- Critical rules:
- 1. SEARCH content must match the associated file section to find EXACTLY:
- * Match character-for-character including whitespace, indentation, line endings
- * Include all comments, docstrings, etc.
- 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
- * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
- * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
- * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
- 3. Keep SEARCH/REPLACE blocks concise:
- * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
- * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
- * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
- * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
- 4. Special operations:
- * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
- * To delete code: Use empty REPLACE section
+- input: (required) The apply_patch command that you wish to execute.
- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
Usage:
-
-File path here
-Search and replace blocks here
+
+
Checklist here (optional)
-
+
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-focus-chain.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-focus-chain.snap
index 9c77a32d..faa3410b 100644
--- a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-focus-chain.snap
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-focus-chain.snap
@@ -44,50 +44,67 @@ Usage:
File path here
-## write_to_file
-Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
-Parameters:
-- path: (required) The path of the file to write to (relative to the current working directory /test/project)
-- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
-Usage:
-
-File path here
-Your file content here
-
+## apply_patch
+Description: This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
-## replace_in_file
-Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+[YOUR_PATCH]
+*** End Patch
+EOF
+
+Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
+
+*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
+For each snippet of code that needs to be changed, repeat the following:
+[context_before] -> See below for further instructions on context.
+- [old_code] -> Precede the old code with a minus sign.
++ [new_code] -> Precede the new, replacement code with a plus sign.
+[context_after] -> See below for further instructions on context.
+
+For instructions on [context_before] and [context_after]:
+- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
+- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
+@@ class BaseClass
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
+
+@@ class BaseClass
+@@ def method():
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/binary_search.py
+@@ class BaseClass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+@@ class Subclass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+*** End Patch
+EOF
Parameters:
-- path: (required) The path of the file to modify (relative to the current working directory /test/project)
-- diff: (required) One or more SEARCH/REPLACE blocks following this exact format:
- ```
- ------- SEARCH
- [exact content to find]
- =======
- [new content to replace with]
- +++++++ REPLACE
- ```
- Critical rules:
- 1. SEARCH content must match the associated file section to find EXACTLY:
- * Match character-for-character including whitespace, indentation, line endings
- * Include all comments, docstrings, etc.
- 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
- * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
- * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
- * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
- 3. Keep SEARCH/REPLACE blocks concise:
- * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
- * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
- * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
- * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
- 4. Special operations:
- * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
- * To delete code: Use empty REPLACE section
+- input: (required) The apply_patch command that you wish to execute.
Usage:
-
-File path here
-Search and replace blocks here
-
+
+
+
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
diff --git a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-mcp.snap b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-mcp.snap
index 0bfe1d9b..8f0ea1b3 100644
--- a/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-mcp.snap
+++ b/src/core/prompts/system-prompt/__tests__/__snapshots__/openai_gpt_5-no-mcp.snap
@@ -49,54 +49,69 @@ Usage:
Checklist here (optional)
-## write_to_file
-Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
-Parameters:
-- path: (required) The path of the file to write to (relative to the current working directory /test/project)
-- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
-- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
-Usage:
-
-File path here
-Your file content here
-Checklist here (optional)
-
+## apply_patch
+Description: This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
-## replace_in_file
-Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+[YOUR_PATCH]
+*** End Patch
+EOF
+
+Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
+
+*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
+For each snippet of code that needs to be changed, repeat the following:
+[context_before] -> See below for further instructions on context.
+- [old_code] -> Precede the old code with a minus sign.
++ [new_code] -> Precede the new, replacement code with a plus sign.
+[context_after] -> See below for further instructions on context.
+
+For instructions on [context_before] and [context_after]:
+- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
+- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
+@@ class BaseClass
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
+
+@@ class BaseClass
+@@ def method():
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/binary_search.py
+@@ class BaseClass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+@@ class Subclass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+*** End Patch
+EOF
Parameters:
-- path: (required) The path of the file to modify (relative to the current working directory /test/project)
-- diff: (required) One or more SEARCH/REPLACE blocks following this exact format:
- ```
- ------- SEARCH
- [exact content to find]
- =======
- [new content to replace with]
- +++++++ REPLACE
- ```
- Critical rules:
- 1. SEARCH content must match the associated file section to find EXACTLY:
- * Match character-for-character including whitespace, indentation, line endings
- * Include all comments, docstrings, etc.
- 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
- * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
- * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
- * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
- 3. Keep SEARCH/REPLACE blocks concise:
- * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
- * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
- * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
- * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
- 4. Special operations:
- * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
- * To delete code: Use empty REPLACE section
+- input: (required) The apply_patch command that you wish to execute.
- task_progress: (optional) A checklist showing task progress after this tool use is completed. (See 'Updating Task Progress' section for more details)
Usage:
-
-File path here
-Search and replace blocks here
+
+
Checklist here (optional)
-
+
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
diff --git a/src/core/prompts/system-prompt/__tests__/integration.test.ts b/src/core/prompts/system-prompt/__tests__/integration.test.ts
index 03561d9e..ef7d4655 100644
--- a/src/core/prompts/system-prompt/__tests__/integration.test.ts
+++ b/src/core/prompts/system-prompt/__tests__/integration.test.ts
@@ -164,13 +164,9 @@ const baseContext: SystemPromptContext = {
preferredLanguageInstructions: "Prefer TypeScript",
isTesting: true,
providerInfo: mockProviderInfo,
+ enableNativeToolCalls: false,
}
-const makeMockContext = (modelId: string, providerId: string = "test"): SystemPromptContext => ({
- ...baseContext,
- providerInfo: makeMockProviderInfo(modelId, providerId),
-})
-
describe("Prompt System Integration Tests", () => {
beforeEach(() => {
// Reset any necessary state before each test
@@ -214,12 +210,6 @@ describe("Prompt System Integration Tests", () => {
providerId: "zai",
contextVariations,
},
- {
- modelGroup: ModelFamily.GPT_5,
- modelIds: ["gpt-5"],
- providerId: "openai",
- contextVariations,
- },
{
modelGroup: ModelFamily.NEXT_GEN,
modelIds: ["claude-sonnet-4"],
@@ -232,6 +222,18 @@ describe("Prompt System Integration Tests", () => {
providerId: "lmstudio",
contextVariations,
},
+ {
+ modelGroup: ModelFamily.NATIVE_NEXT_GEN,
+ modelIds: ["claude-4-5-sonnet"],
+ providerId: "cline",
+ contextVariations,
+ },
+ {
+ modelGroup: ModelFamily.GPT_5,
+ modelIds: ["gpt-5"],
+ providerId: "openai",
+ contextVariations,
+ },
]
// Generate snapshots for all model/context combinations
@@ -255,17 +257,18 @@ describe("Prompt System Integration Tests", () => {
...baseContext,
providerInfo: makeMockProviderInfo(modelId, providerId),
isTesting: true,
+ enableNativeToolCalls: modelGroup === ModelFamily.NATIVE_NEXT_GEN,
}
it(`should generate consistent prompt for ${providerId}/${modelId} with ${contextName} context`, async function () {
this.timeout(30000) // Allow more time for prompt generation
try {
- const prompt = await getSystemPrompt(context as SystemPromptContext)
+ const { systemPrompt } = await getSystemPrompt(context as SystemPromptContext)
// Basic structure assertions
- expect(prompt).to.be.a("string")
- expect(prompt.length).to.be.greaterThan(100)
- expect(prompt).to.not.include("{{TOOL_USE_SECTION}}") // Tools placeholder should be removed
+ expect(systemPrompt).to.be.a("string")
+ expect(systemPrompt.length).to.be.greaterThan(100)
+ expect(systemPrompt).to.not.include("{{TOOL_USE_SECTION}}") // Tools placeholder should be removed
// Snapshot testing logic
const snapshotName = `${providerId}_${modelId.replace(/[^a-zA-Z0-9]/g, "_")}-${contextName}.snap`
@@ -273,13 +276,13 @@ describe("Prompt System Integration Tests", () => {
if (UPDATE_SNAPSHOTS) {
// Update mode: write new snapshot
- await fs.writeFile(snapshotPath, prompt, "utf-8")
- console.log(`Updated snapshot: ${snapshotName} (${prompt.length} chars)`)
+ await fs.writeFile(snapshotPath, systemPrompt, "utf-8")
+ console.log(`Updated snapshot: ${snapshotName} (${systemPrompt.length} chars)`)
} else {
// Test mode: compare with existing snapshot
try {
const existingSnapshot = await fs.readFile(snapshotPath, "utf-8")
- const differences = compareStrings(existingSnapshot, prompt)
+ const differences = compareStrings(existingSnapshot, systemPrompt)
if (differences) {
throw new Error(formatSnapshotError(snapshotName, differences))
@@ -325,8 +328,8 @@ describe("Prompt System Integration Tests", () => {
const contextWithBrowser = { ...baseContext, supportsBrowserUse: true }
try {
- const prompt = await getSystemPrompt(contextWithBrowser)
- expect(prompt.toLowerCase()).to.include("browser")
+ const { systemPrompt } = await getSystemPrompt(contextWithBrowser)
+ expect(systemPrompt.toLowerCase()).to.include("browser")
} catch (error) {
if (error instanceof Error && error.message.includes("No prompt variant found")) {
this.skip()
@@ -340,8 +343,8 @@ describe("Prompt System Integration Tests", () => {
this.timeout(30000)
try {
- const prompt = await getSystemPrompt(baseContext)
- expect(prompt).to.include("MCP")
+ const { systemPrompt } = await getSystemPrompt(baseContext)
+ expect(systemPrompt).to.include("MCP")
} catch (error) {
if (error instanceof Error && error.message.includes("No prompt variant found")) {
this.skip()
@@ -355,8 +358,8 @@ describe("Prompt System Integration Tests", () => {
this.timeout(30000)
try {
- const prompt = await getSystemPrompt(baseContext)
- expect(prompt).to.include("TODO")
+ const { systemPrompt } = await getSystemPrompt(baseContext)
+ expect(systemPrompt).to.include("TODO")
} catch (error) {
if (error instanceof Error && error.message.includes("No prompt variant found")) {
this.skip()
@@ -370,8 +373,8 @@ describe("Prompt System Integration Tests", () => {
this.timeout(30000)
try {
- const prompt = await getSystemPrompt(baseContext)
- expect(prompt).to.include("USER'S CUSTOM INSTRUCTIONS")
+ const { systemPrompt } = await getSystemPrompt(baseContext)
+ expect(systemPrompt).to.include("USER'S CUSTOM INSTRUCTIONS")
} catch (error) {
if (error instanceof Error && error.message.includes("No prompt variant found")) {
this.skip()
@@ -410,9 +413,9 @@ describe("Prompt System Integration Tests", () => {
}
try {
- const prompt = await getSystemPrompt(contextWithNulls)
- expect(prompt).to.be.a("string")
- expect(prompt).to.include("{{TOOL_USE_SECTION}}")
+ const { systemPrompt } = await getSystemPrompt(contextWithNulls)
+ expect(systemPrompt).to.be.a("string")
+ expect(systemPrompt).to.include("{{TOOL_USE_SECTION}}")
} catch (error) {
// Error is acceptable for invalid context
expect(error).to.be.instanceOf(Error)
diff --git a/src/core/prompts/system-prompt/__tests__/matcher-test.ts b/src/core/prompts/system-prompt/__tests__/matcher-test.ts
new file mode 100644
index 00000000..f204ad80
--- /dev/null
+++ b/src/core/prompts/system-prompt/__tests__/matcher-test.ts
@@ -0,0 +1,128 @@
+/**
+ * Test to verify the new matcher-based variant selection works correctly
+ */
+
+import { ApiProviderInfo } from "@/core/api"
+import { McpHub } from "@/services/mcp/McpHub"
+import { ModelFamily } from "@/shared/prompts"
+import { SystemPromptContext } from "../types"
+import { VARIANT_CONFIGS } from "../variants"
+
+// Mock provider info objects for testing
+const mockProviderInfos: { name: string; providerInfo: ApiProviderInfo; expectedFamily: ModelFamily }[] = [
+ {
+ name: "GPT-5 model",
+ providerInfo: {
+ providerId: "openai",
+ model: { id: "gpt-5", info: {} as any },
+ },
+ expectedFamily: ModelFamily.GPT_5,
+ },
+ {
+ name: "Next-gen model",
+ providerInfo: {
+ providerId: "anthropic",
+ model: { id: "claude-3.5-sonnet-20241022", info: {} as any },
+ },
+ expectedFamily: ModelFamily.NEXT_GEN,
+ },
+ {
+ name: "Compact local model",
+ providerInfo: {
+ providerId: "ollama",
+ model: { id: "llama-3.2-1b", info: {} as any },
+ customPrompt: "compact",
+ },
+ expectedFamily: ModelFamily.XS,
+ },
+ {
+ name: "Generic model",
+ providerInfo: {
+ providerId: "openai",
+ model: { id: "gpt-3.5-turbo", info: {} as any },
+ },
+ expectedFamily: ModelFamily.GENERIC,
+ },
+]
+
+/**
+ * Test the matcher logic for each variant
+ */
+export function testVariantMatching() {
+ console.log("🧪 Testing variant matching logic...")
+
+ for (const { name, providerInfo, expectedFamily } of mockProviderInfos) {
+ console.log(`\n📝 Testing: ${name}`)
+ console.log(` Model: ${providerInfo.model.id}`)
+ console.log(` Provider: ${providerInfo.providerId}`)
+ console.log(` Custom Prompt: ${providerInfo.customPrompt || "none"}`)
+ console.log(` Expected Family: ${expectedFamily}`)
+
+ let matchedFamily: ModelFamily | null = null
+
+ // Test each variant's matcher function
+ for (const [familyId, config] of Object.entries(VARIANT_CONFIGS)) {
+ const mockContext = {
+ cwd: "/test/project",
+ ide: "TestIde",
+ supportsBrowserUse: true,
+ mcpHub: {
+ getServers: () => [
+ {
+ name: "test-server",
+ status: "connected",
+ config: '{"command": "test"}',
+ tools: [
+ {
+ name: "test_tool",
+ description: "A test tool",
+ inputSchema: { type: "object", properties: {} },
+ },
+ ],
+ resources: [],
+ resourceTemplates: [],
+ },
+ ],
+ } as unknown as McpHub,
+ focusChainSettings: {
+ enabled: true,
+ remindClineInterval: 6,
+ },
+ browserSettings: {
+ viewport: {
+ width: 1280,
+ height: 720,
+ },
+ },
+ globalClineRulesFileInstructions: "Follow global rules",
+ localClineRulesFileInstructions: "Follow local rules",
+ preferredLanguageInstructions: "Prefer TypeScript",
+ isTesting: true,
+ enableNativeToolCalls: false,
+ providerInfo,
+ } satisfies SystemPromptContext
+
+ try {
+ if (config.matcher(mockContext)) {
+ matchedFamily = familyId as ModelFamily
+ console.log(` ✅ Matched: ${familyId}`)
+ break
+ }
+ } catch (error) {
+ console.log(` ❌ Matcher error for ${familyId}: ${error}`)
+ }
+ }
+
+ // Check if the match is correct
+ if (matchedFamily === expectedFamily) {
+ console.log(` 🎯 PASS: Correctly matched ${expectedFamily}`)
+ } else {
+ console.log(` 🚨 FAIL: Expected ${expectedFamily}, got ${matchedFamily || "null"}`)
+ }
+ }
+
+ console.log("\n✨ Variant matching test completed!")
+}
+
+// Export for potential use in other tests
+export { mockProviderInfos }
diff --git a/src/core/prompts/system-prompt/components/tool_use/index.ts b/src/core/prompts/system-prompt/components/tool_use/index.ts
index f045add9..570a5d47 100644
--- a/src/core/prompts/system-prompt/components/tool_use/index.ts
+++ b/src/core/prompts/system-prompt/components/tool_use/index.ts
@@ -19,7 +19,7 @@ export async function getToolUseSection(variant: PromptVariant, context: SystemP
})
}
-const TOOL_USE_TEMPLATE_TEXT = `TOOL USE
+const TOOL_USE_TEMPLATE_TEXT = (_context: SystemPromptContext) => `TOOL USE
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
diff --git a/src/core/prompts/system-prompt/index.ts b/src/core/prompts/system-prompt/index.ts
index c94afd17..b961c5b1 100644
--- a/src/core/prompts/system-prompt/index.ts
+++ b/src/core/prompts/system-prompt/index.ts
@@ -1,6 +1,3 @@
-import { isGLMModelFamily, isGPT5ModelFamily, isLocalModel, isNextGenModelFamily } from "@utils/model-utils"
-import { ApiProviderInfo } from "@/core/api"
-import { ModelFamily } from "@/shared/prompts"
import { PromptRegistry } from "./registry/PromptRegistry"
import type { SystemPromptContext } from "./types"
@@ -13,32 +10,12 @@ export * from "./types"
export { VariantBuilder } from "./variants/variant-builder"
export { validateVariant } from "./variants/variant-validator"
-/**
- * Extract model family from model ID (e.g., "claude-4" -> "claude")
- */
-export function getModelFamily(providerInfo: ApiProviderInfo): ModelFamily {
- if (isGPT5ModelFamily(providerInfo.model.id)) {
- return ModelFamily.GPT_5
- }
- // Check for next-gen models first
- if (isNextGenModelFamily(providerInfo.model.id)) {
- return ModelFamily.NEXT_GEN
- }
- // Check for GLM models
- if (isGLMModelFamily(providerInfo.model.id)) {
- return ModelFamily.GLM
- }
- if (providerInfo.customPrompt === "compact" && isLocalModel(providerInfo)) {
- return ModelFamily.XS
- }
- // Default fallback
- return ModelFamily.GENERIC
-}
-
/**
* Get the system prompt by id
*/
-export async function getSystemPrompt(context: SystemPromptContext): Promise {
+export async function getSystemPrompt(context: SystemPromptContext) {
const registry = PromptRegistry.getInstance()
- return await registry.get(context)
+ const systemPrompt = await registry.get(context)
+ const tools = registry.nativeTools
+ return { systemPrompt, tools }
}
diff --git a/src/core/prompts/system-prompt/registry/ClineToolSet.ts b/src/core/prompts/system-prompt/registry/ClineToolSet.ts
index 312adf9f..28d50f96 100644
--- a/src/core/prompts/system-prompt/registry/ClineToolSet.ts
+++ b/src/core/prompts/system-prompt/registry/ClineToolSet.ts
@@ -1,5 +1,8 @@
+import { CLINE_MCP_TOOL_IDENTIFIER, McpServer } from "@/shared/mcp"
import { ModelFamily } from "@/shared/prompts"
-import type { ClineToolSpec } from "../spec"
+import { ClineDefaultTool } from "@/shared/tools"
+import { type ClineToolSpec, toolSpecFunctionDeclarations, toolSpecFunctionDefinition, toolSpecInputSchema } from "../spec"
+import { PromptVariant, SystemPromptContext } from "../types"
export class ClineToolSet {
// A list of tools mapped by model group
@@ -79,4 +82,114 @@ export class ClineToolSet {
}
return resolved
}
+
+ public static getEnabledTools(variant: PromptVariant, context: SystemPromptContext): ClineToolSet[] {
+ const resolved: ClineToolSet[] = []
+ const requestedIds = variant.tools ? [...variant.tools] : []
+ for (const id of requestedIds) {
+ const tool = ClineToolSet.getToolByNameWithFallback(id, variant.family)
+ if (tool) {
+ // Avoid duplicates by id
+ if (!resolved.some((t) => t.config.id === tool.config.id)) {
+ resolved.push(tool)
+ }
+ }
+ }
+
+ // Filter by context requirements
+ const enabledTools = resolved.filter(
+ (tool) => !tool.config.contextRequirements || tool.config.contextRequirements(context),
+ )
+
+ return enabledTools
+ }
+
+ /**
+ * Get the appropriate native tool converter for the given provider
+ */
+ public static getNativeConverter(providerId: string) {
+ switch (providerId) {
+ case "anthropic":
+ return toolSpecInputSchema
+ case "gemini":
+ return toolSpecFunctionDeclarations
+ default:
+ return toolSpecFunctionDefinition
+ }
+ }
+
+ public static getNativeTools(variant: PromptVariant, context: SystemPromptContext) {
+ // Only return tool functions if the variant explicitly enables them
+ // via the "use_native_tools" label set to 1
+ // This avoids exposing tools to models that don't support them
+ // or variants that aren't designed for tool use
+ if (variant.labels["use_native_tools"] !== 1 || !context.enableNativeToolCalls) {
+ return undefined
+ }
+
+ // Base set
+ const toolsets = ClineToolSet.getEnabledTools(variant, context)
+ const toolConfigs = toolsets.map((tool) => tool.config)
+
+ // MCP tools
+ const mcpServers = context.mcpHub?.getServers()?.filter((s) => s.disabled !== true) || []
+ const mcpTools = mcpServers?.flatMap((server) => mcpToolToClineToolSpec(variant.family, server))
+
+ const enabledTools = [...toolConfigs, ...mcpTools]
+ const converter = ClineToolSet.getNativeConverter(context.providerInfo.providerId)
+
+ return enabledTools.map((tool) => converter(tool, context))
+ }
+}
+
+/**
+ * Convert an MCP server's tools to ClineToolSpec format
+ */
+export function mcpToolToClineToolSpec(family: ModelFamily, server: McpServer): ClineToolSpec[] {
+ const tools = server.tools || []
+ return tools.map((mcpTool) => {
+ let parameters: any[] = []
+
+ if (mcpTool.inputSchema && "properties" in mcpTool.inputSchema) {
+ const schema = mcpTool.inputSchema as any
+ const requiredFields = new Set(schema.required || [])
+
+ parameters = Object.entries(schema.properties as Record).map(([name, propSchema]) => {
+ // Preserve the full schema, not just basic fields
+ const param: any = {
+ name,
+ instruction: propSchema.description || "",
+ type: propSchema.type || "string",
+ required: requiredFields.has(name),
+ }
+
+ // Preserve items for array types
+ if (propSchema.items) {
+ param.items = propSchema.items
+ }
+
+ // Preserve properties for object types
+ if (propSchema.properties) {
+ param.properties = propSchema.properties
+ }
+
+ // Preserve other JSON Schema fields (enum, format, minimum, maximum, etc.)
+ for (const key in propSchema) {
+ if (!["type", "description", "items", "properties"].includes(key)) {
+ param[key] = propSchema[key]
+ }
+ }
+
+ return param
+ })
+ }
+
+ return {
+ variant: family,
+ id: ClineDefaultTool.MCP_USE,
+ name: server.name + CLINE_MCP_TOOL_IDENTIFIER + mcpTool.name,
+ description: mcpTool.description || "",
+ parameters,
+ }
+ })
}
diff --git a/src/core/prompts/system-prompt/registry/PromptBuilder.ts b/src/core/prompts/system-prompt/registry/PromptBuilder.ts
index 7cb99848..c9651020 100644
--- a/src/core/prompts/system-prompt/registry/PromptBuilder.ts
+++ b/src/core/prompts/system-prompt/registry/PromptBuilder.ts
@@ -1,7 +1,6 @@
import type { ClineDefaultTool } from "@/shared/tools"
-import { getModelFamily } from "../"
import { ClineToolSet } from "../registry/ClineToolSet"
-import type { ClineToolSpec } from "../spec"
+import { type ClineToolSpec } from "../spec"
import { STANDARD_PLACEHOLDERS } from "../templates/placeholders"
import { TemplateEngine } from "../templates/TemplateEngine"
import type { ComponentRegistry, PromptVariant, SystemPromptContext } from "../types"
@@ -62,7 +61,7 @@ export class PromptBuilder {
// Add standard system placeholders
placeholders[STANDARD_PLACEHOLDERS.CWD] = this.context.cwd || process.cwd()
placeholders[STANDARD_PLACEHOLDERS.SUPPORTS_BROWSER] = this.context.supportsBrowserUse || false
- placeholders[STANDARD_PLACEHOLDERS.MODEL_FAMILY] = getModelFamily(this.context.providerInfo)
+ placeholders[STANDARD_PLACEHOLDERS.MODEL_FAMILY] = this.variant.family
placeholders[STANDARD_PLACEHOLDERS.CURRENT_DATE] = new Date().toISOString().split("T")[0]
// Add all component sections
@@ -97,7 +96,7 @@ export class PromptBuilder {
.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) => {
+ .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
// Look for patterns like "SEARCH\n=======\n" or ";\n=======\n" (diff markers)
@@ -132,7 +131,7 @@ export class PromptBuilder {
}
}
- public static async getToolsPrompts(variant: PromptVariant, context: SystemPromptContext) {
+ private static getEnabledTools(variant: PromptVariant, context: SystemPromptContext) {
let resolvedTools: ReturnType = []
// If the variant explicitly lists tools, resolve each by id with fallback to GENERIC
@@ -156,6 +155,12 @@ export class PromptBuilder {
(tool) => !tool.config.contextRequirements || tool.config.contextRequirements(context),
)
+ return enabledTools
+ }
+
+ public static async getToolsPrompts(variant: PromptVariant, context: SystemPromptContext) {
+ const enabledTools = PromptBuilder.getEnabledTools(variant, context)
+
const ids = enabledTools.map((tool) => tool.config.id)
return Promise.all(enabledTools.map((tool) => PromptBuilder.tool(tool.config, ids, context)))
}
diff --git a/src/core/prompts/system-prompt/registry/PromptRegistry.ts b/src/core/prompts/system-prompt/registry/PromptRegistry.ts
index dbe9a975..30572b72 100644
--- a/src/core/prompts/system-prompt/registry/PromptRegistry.ts
+++ b/src/core/prompts/system-prompt/registry/PromptRegistry.ts
@@ -1,5 +1,6 @@
import { ModelFamily } from "@/shared/prompts"
-import { getModelFamily } from ".."
+import { ClineTool } from "@/shared/tools"
+import { ClineToolSet } from ".."
import { getSystemPromptComponents } from "../components"
import { registerClineToolSets } from "../tools"
import type { ComponentFunction, ComponentRegistry, PromptVariant, SystemPromptContext } from "../types"
@@ -12,6 +13,7 @@ export class PromptRegistry {
private variants: Map = new Map()
private components: ComponentRegistry = {}
private loaded: boolean = false
+ public nativeTools: ClineTool[] | undefined = undefined
private constructor() {
registerClineToolSets()
@@ -65,27 +67,39 @@ export class PromptRegistry {
)
}
+ getModelFamily(context: SystemPromptContext) {
+ // Loop through all registered variants to find the first one that matches
+ for (const [id, v] of this.variants.entries()) {
+ try {
+ if (v.matcher(context)) {
+ return v.family
+ }
+ } catch (error) {
+ console.warn(`Matcher function error for variant '${id}':`, error)
+ // Continue to next variant if matcher throws
+ }
+ }
+
+ return ModelFamily.GENERIC
+ }
/**
- * Get prompt by model ID with fallback to generic
+ * Get prompt by matching against all registered variants
*/
async get(context: SystemPromptContext): Promise {
await this.load()
- // Try model family fallback (e.g., "claude-4" -> "claude")
- const modelFamily = getModelFamily(context.providerInfo)
- let variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC)
+ // Loop through all registered variants to find the first one that matches
+ const family = this.getModelFamily(context)
- // If no variant found for the detected family, explicitly try generic
- if (!variant && modelFamily !== ModelFamily.GENERIC) {
- variant = this.variants.get(ModelFamily.GENERIC)
- }
+ // Fallback to generic variant if no match found
+
+ const variant = this.variants.get(family)
if (!variant) {
// Enhanced error with debugging information
const availableVariants = Array.from(this.variants.keys())
const errorDetails = {
requestedModel: context.providerInfo.model.id,
- detectedFamily: modelFamily,
availableVariants,
variantsCount: this.variants.size,
componentsCount: Object.keys(this.components).length,
@@ -95,12 +109,15 @@ export class PromptRegistry {
console.error("Prompt variant lookup failed:", errorDetails)
throw new Error(
- `No prompt variant found for model '${context.providerInfo.model.id}' (family: ${modelFamily}) and no generic fallback available. ` +
+ `No prompt variant found for model '${context.providerInfo.model.id}' and no generic fallback available. ` +
`Available variants: [${availableVariants.join(", ")}]. ` +
`Registry state: loaded=${this.loaded}, variants=${this.variants.size}, components=${Object.keys(this.components).length}`,
)
}
+ // Hacky way to get native tools for the current variant - it's bad and ugly
+ this.nativeTools = ClineToolSet.getNativeTools(variant, context)
+
const builder = new PromptBuilder(variant, context, this.components)
return await builder.build()
}
diff --git a/src/core/prompts/system-prompt/spec.ts b/src/core/prompts/system-prompt/spec.ts
index 65f61634..bf5adf9c 100644
--- a/src/core/prompts/system-prompt/spec.ts
+++ b/src/core/prompts/system-prompt/spec.ts
@@ -1,4 +1,7 @@
-import type { ModelFamily } from "@/shared/prompts"
+import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
+import { FunctionDeclaration as GoogleTool, Type as GoogleToolParamType } from "@google/genai"
+import { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
+import { ModelFamily } from "@/shared/prompts"
import type { ClineDefaultTool } from "@/shared/tools"
import type { SystemPromptContext } from "./types"
@@ -20,4 +23,314 @@ interface ClineToolSpecParameter {
dependencies?: ClineDefaultTool[]
description?: string
contextRequirements?: (context: SystemPromptContext) => boolean
+ // TODO: Confirm if "integer" is actually supported across providers
+ /**
+ * The type of the parameter. Default to string if not provided.
+ * Supported types: string, boolean, integer, array, object
+ */
+ type?: "string" | "boolean" | "integer" | "array" | "object"
+ /**
+ * For array types, this defines the schema of array items
+ */
+ items?: any
+ /**
+ * For object types, this defines the properties
+ */
+ properties?: Record
+ /**
+ * Additional JSON Schema fields to preserve from MCP tools
+ */
+ [key: string]: any
+}
+
+/**
+ * Converts a ClineToolSpec into an OpenAI ChatCompletionTool definition
+ * Docs: https://openrouter.ai/docs/features/tool-calling#step-1-inference-request-with-tools
+ */
+export function toolSpecFunctionDefinition(tool: ClineToolSpec, context: SystemPromptContext): OpenAITool {
+ // Check if the tool should be included based on context requirements
+ if (tool.contextRequirements && !tool.contextRequirements(context)) {
+ throw new Error(`Tool ${tool.name} does not meet context requirements`)
+ }
+
+ // Build the properties object for parameters
+ const properties: Record = {}
+ const required: string[] = []
+
+ if (tool.parameters) {
+ for (const param of tool.parameters) {
+ // Check if parameter should be included based on context requirements
+ if (param.contextRequirements && !param.contextRequirements(context)) {
+ continue
+ }
+
+ // Add to required array if parameter is required
+ if (param.required) {
+ required.push(param.name)
+ }
+
+ // Determine parameter type - use explicit type if provided.
+ // Default to string
+ const paramType: string = param.type || "string"
+
+ // Build parameter schema
+ const paramSchema: any = {
+ type: paramType,
+ description: replacer(param.instruction, context),
+ }
+
+ // Add items for array types
+ if (paramType === "array" && param.items) {
+ paramSchema.items = param.items
+ }
+
+ // Add properties for object types
+ if (paramType === "object" && param.properties) {
+ paramSchema.properties = param.properties
+ }
+
+ // Preserve any additional JSON Schema fields from MCP tools
+ // (e.g., enum, format, minimum, maximum, etc.)
+ const reservedKeys = new Set([
+ "name",
+ "required",
+ "instruction",
+ "usage",
+ "dependencies",
+ "description",
+ "contextRequirements",
+ "type",
+ "items",
+ "properties",
+ ])
+ for (const key in param) {
+ if (!reservedKeys.has(key) && param[key] !== undefined) {
+ paramSchema[key] = param[key]
+ }
+ }
+
+ // Add usage example as part of description if available
+ // if (param.usage) {
+ // paramSchema.description += ` Example: ${param.usage}`
+ // }
+
+ properties[param.name] = paramSchema
+ }
+ }
+
+ // Build the ChatCompletionTool object
+ const chatCompletionTool: OpenAITool = {
+ type: "function",
+ function: {
+ name: tool.name,
+ description: replacer(tool.description, context),
+ strict: false,
+ parameters: {
+ type: "object",
+ properties,
+ required,
+ additionalProperties: false,
+ },
+ },
+ }
+
+ return chatCompletionTool
+}
+
+/**
+ * Converts a ClineToolSpec into an Anthropic Tool definition
+ */
+export function toolSpecInputSchema(tool: ClineToolSpec, context: SystemPromptContext): AnthropicTool {
+ // Check if the tool should be included based on context requirements
+ if (tool.contextRequirements && !tool.contextRequirements(context)) {
+ throw new Error(`Tool ${tool.name} does not meet context requirements`)
+ }
+
+ // Build the properties object for parameters
+ const properties: Record = {}
+ const required: string[] = []
+
+ if (tool.parameters) {
+ for (const param of tool.parameters) {
+ // Check if parameter should be included based on context requirements
+ if (param.contextRequirements && !param.contextRequirements(context)) {
+ continue
+ }
+
+ // Add to required array if parameter is required
+ if (param.required) {
+ required.push(param.name)
+ }
+
+ // Determine parameter type - use explicit type if provided.
+ // Default to string
+ const paramType: string = param.type || "string"
+
+ // Build parameter schema
+ const paramSchema: any = {
+ type: paramType,
+ description: replacer(param.instruction, context),
+ }
+
+ // Add items for array types
+ if (paramType === "array" && param.items) {
+ paramSchema.items = param.items
+ }
+
+ // Add properties for object types
+ if (paramType === "object" && param.properties) {
+ paramSchema.properties = param.properties
+ }
+
+ // Preserve any additional JSON Schema fields from MCP tools
+ // (e.g., enum, format, minimum, maximum, etc.)
+ const reservedKeys = new Set([
+ "name",
+ "required",
+ "instruction",
+ "usage",
+ "dependencies",
+ "description",
+ "contextRequirements",
+ "type",
+ "items",
+ "properties",
+ ])
+ for (const key in param) {
+ if (!reservedKeys.has(key) && param[key] !== undefined) {
+ paramSchema[key] = param[key]
+ }
+ }
+
+ // Add usage example as part of description if available
+ // if (param.usage) {
+ // paramSchema.description += ` Example: ${param.usage}`
+ // }
+
+ properties[param.name] = paramSchema
+ }
+ }
+
+ // Build the Tool object
+ const toolInputSchema: AnthropicTool = {
+ name: tool.name,
+ description: replacer(tool.description, context),
+ input_schema: {
+ type: "object",
+ properties,
+ required,
+ },
+ }
+
+ return toolInputSchema
+}
+
+/**
+ * Converts a ClineToolSpec into a Google Gemini function.
+ * Docs: https://ai.google.dev/gemini-api/docs/function-calling
+ */
+export function toolSpecFunctionDeclarations(tool: ClineToolSpec, context: SystemPromptContext): GoogleTool {
+ // Check if the tool should be included based on context requirements
+ if (tool.contextRequirements && !tool.contextRequirements(context)) {
+ throw new Error(`Tool ${tool.name} does not meet context requirements`)
+ }
+
+ // Build the parameters object for parameters
+ const properties: Record = {}
+ const required: string[] = []
+
+ if (tool.parameters) {
+ for (const param of tool.parameters) {
+ // Check if parameter should be included based on context requirements
+ if (param.contextRequirements && !param.contextRequirements(context)) {
+ continue
+ }
+
+ // Add to required array if parameter is required
+ if (param.required) {
+ required.push(param.name)
+ }
+
+ // Determine parameter type - use explicit type if provided.
+ // Default to string
+ const paramType: string = param.type || GoogleToolParamType.STRING
+
+ // Build parameter schema
+ const paramSchema: any = {
+ type: paramType,
+ items: paramType === GoogleToolParamType.ARRAY ? { type: GoogleToolParamType.STRING } : undefined,
+ description: replacer(param.instruction, context),
+ }
+ properties[param.name] = paramSchema
+ }
+ }
+
+ const googleTool: GoogleTool = {
+ name: tool.name,
+ description: replacer(tool.description, context),
+ parameters: {
+ type: GoogleToolParamType.OBJECT,
+ properties,
+ required,
+ },
+ }
+
+ return googleTool
+}
+
+/**
+ * Converts an OpenAI ChatCompletionTool into an Anthropic Tool definition
+ */
+export function openAIToolToAnthropic(openAITool: OpenAITool): AnthropicTool {
+ const func = openAITool.function
+
+ return {
+ name: func.name,
+ description: func.description || "",
+ input_schema: {
+ type: "object",
+ properties: func.parameters?.properties || {},
+ required: func.parameters?.required || [],
+ },
+ }
+}
+
+type OpenAIResponseTool = {
+ type: "function"
+ function: {
+ name: string
+ description: string
+ strict: boolean
+ parameters: {
+ type: "object"
+ properties: Record
+ required: string[]
+ additionalProperties?: boolean
+ }
+ }
+}
+
+/**
+ * Converts an OpenAI ChatCompletionTool into Response API format.
+ */
+export function toOpenAIResponsesAPITool(openAITool: OpenAITool): OpenAIResponseTool {
+ return {
+ type: "function",
+ function: {
+ name: openAITool.function.name,
+ description: openAITool.function.description || "",
+ strict: openAITool.function.strict || false,
+ parameters: {
+ type: "object",
+ properties: openAITool.function.parameters?.properties || {},
+ required: openAITool.function.parameters?.required ? (openAITool.function.parameters?.required as string[]) : [],
+ },
+ },
+ } satisfies OpenAIResponseTool
+}
+
+function replacer(description: string, context: SystemPromptContext) {
+ return description
+ .replace("{{BROWSER_VIEWPORT_WIDTH}}", `${context.browserSettings?.viewport?.width || 900}`)
+ .replace("{{BROWSER_VIEWPORT_HEIGHT}}", `${context.browserSettings?.viewport?.height || 600}`)
}
diff --git a/src/core/prompts/system-prompt/tools/apply_patch.ts b/src/core/prompts/system-prompt/tools/apply_patch.ts
new file mode 100644
index 00000000..ce57d800
--- /dev/null
+++ b/src/core/prompts/system-prompt/tools/apply_patch.ts
@@ -0,0 +1,96 @@
+import { ModelFamily } from "@/shared/prompts"
+import { ClineDefaultTool } from "@/shared/tools"
+import type { ClineToolSpec } from "../spec"
+import { TASK_PROGRESS_PARAMETER } from "../types"
+
+// {
+// "name": "apply_patch",
+// "description": APPLY_PATCH_TOOL_DESC,
+// "parameters": {
+// "type": "object",
+// "properties": {
+// "input": {
+// "type": "string",
+// "description": " The apply_patch command that you wish to execute.",
+// }
+// },
+// "required": ["input"],
+// },
+// }
+
+const APPLY_PATCH_TOOL_DESC = `This is a custom utility that makes it more convenient to add, remove, move, or edit code files. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` command, you should pass a message of the following structure as "input":
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+[YOUR_PATCH]
+*** End Patch
+EOF
+
+Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
+
+*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
+For each snippet of code that needs to be changed, repeat the following:
+[context_before] -> See below for further instructions on context.
+- [old_code] -> Precede the old code with a minus sign.
++ [new_code] -> Precede the new, replacement code with a plus sign.
+[context_after] -> See below for further instructions on context.
+
+For instructions on [context_before] and [context_after]:
+- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
+- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
+@@ class BaseClass
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple \`@@\` statements to jump to the right context. For instance:
+
+@@ class BaseClass
+@@ def method():
+[3 lines of pre-context]
+- [old_code]
++ [new_code]
+[3 lines of post-context]
+
+Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
+
+%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/binary_search.py
+@@ class BaseClass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+@@ class Subclass
+@@ def search():
+- pass
++ raise NotImplementedError()
+
+*** End Patch
+EOF`
+
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
+ id: ClineDefaultTool.APPLY_PATCH,
+ name: "apply_patch",
+ description: APPLY_PATCH_TOOL_DESC,
+ contextRequirements: (context) => context.providerInfo.model.id.includes("gpt-5"),
+ parameters: [
+ {
+ name: "input",
+ required: true,
+ instruction: "The apply_patch command that you wish to execute.",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
+
+const GPT_5: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.GPT_5,
+}
+export const apply_patch_variants = [NATIVE_GPT_5, GPT_5]
diff --git a/src/core/prompts/system-prompt/tools/ask_followup_question.ts b/src/core/prompts/system-prompt/tools/ask_followup_question.ts
index b2f58ff0..12c10a19 100644
--- a/src/core/prompts/system-prompt/tools/ask_followup_question.ts
+++ b/src/core/prompts/system-prompt/tools/ask_followup_question.ts
@@ -29,8 +29,32 @@ const generic: ClineToolSpec = {
],
}
-const nextGen = { ...generic, variant: ModelFamily.NEXT_GEN }
-const gpt = { ...generic, variant: ModelFamily.GPT }
-const gemini = { ...generic, variant: ModelFamily.GEMINI }
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id: ClineDefaultTool.ASK,
+ name: "ask_followup_question",
+ description:
+ "Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user how you can help in response to a simple greeting message.",
+ contextRequirements: (context) => !context.yoloModeToggled,
+ parameters: [
+ {
+ name: "question",
+ required: true,
+ instruction: 'The question to ask the user. E.g. "How can I help you?"',
+ },
+ {
+ name: "options",
+ required: false,
+ instruction:
+ 'An array of 2-5 options (e.x: "["Option 1", "Option 2", "Option 3"]") for the user to choose from related to the question. Each option should be a string describing a possible answer. You may not always need to provide options, but it may be helpful in many cases where it can save the user from having to type out a response manually. IMPORTANT: NEVER include an option to toggle to Act mode, as this would be something you need to direct the user to do manually themselves if needed.',
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
-export const ask_followup_question_variants = [generic, nextGen, gpt, gemini]
+const NATIVE_GPT_5: ClineToolSpec = {
+ ...NATIVE_NEXT_GEN,
+ variant: ModelFamily.NATIVE_GPT_5,
+}
+
+export const ask_followup_question_variants = [generic, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/attempt_completion.ts b/src/core/prompts/system-prompt/tools/attempt_completion.ts
index 64025442..50f1448a 100644
--- a/src/core/prompts/system-prompt/tools/attempt_completion.ts
+++ b/src/core/prompts/system-prompt/tools/attempt_completion.ts
@@ -38,7 +38,7 @@ IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user th
],
}
-const gpt5: ClineToolSpec = {
+const GPT_5: ClineToolSpec = {
variant: ModelFamily.GPT_5,
id,
name: "attempt_completion",
@@ -72,4 +72,36 @@ IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user th
],
}
-export const attempt_completion_variants = [generic, gpt5]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id,
+ name: "attempt_completion",
+ description:
+ "Once you've completed the user's task, use this tool to present the final result to the user, including a summary of the task and what was done to resolve it.",
+ parameters: [
+ {
+ name: "result",
+ required: true,
+ instruction: "A clear, specific description of the final result of the task.",
+ },
+ {
+ name: "command",
+ required: false,
+ instruction:
+ "An actionable terminal command that is non-verbose that allows user to review the result of your work. For example, use \`open index.html\` to display a created html website, or \`open localhost:3000\` to display a locally running development server. Commands like \`echo\` or \`cat\` that merely print text are not allowed. Ensure the command is properly formatted for user's OS and does not contain any harmful instructions",
+ },
+ {
+ name: "task_progress",
+ required: false,
+ dependencies: [ClineDefaultTool.TODO],
+ instruction: "A checklist showing task progress with the latest status of each subtasks included previously if any.",
+ },
+ ],
+}
+
+const NATIVE_GPT_5: ClineToolSpec = {
+ ...NATIVE_NEXT_GEN,
+ variant: ModelFamily.NATIVE_GPT_5,
+}
+
+export const attempt_completion_variants = [generic, GPT_5, NATIVE_NEXT_GEN, NATIVE_GPT_5]
diff --git a/src/core/prompts/system-prompt/tools/browser_action.ts b/src/core/prompts/system-prompt/tools/browser_action.ts
index acc8362a..4b6a5a70 100644
--- a/src/core/prompts/system-prompt/tools/browser_action.ts
+++ b/src/core/prompts/system-prompt/tools/browser_action.ts
@@ -4,7 +4,7 @@ import type { ClineToolSpec } from "../spec"
const id = ClineDefaultTool.BROWSER
-const generic: ClineToolSpec = {
+const GENERIC: ClineToolSpec = {
variant: ModelFamily.GENERIC,
id,
name: "browser_action",
@@ -57,4 +57,50 @@ const generic: ClineToolSpec = {
],
}
-export const browser_action_variants = [generic]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id,
+ name: "browser_action",
+ description: `Request to interact with a Puppeteer-controlled browser. Every action, except \`close\`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action.
+- The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL.
+- While the browser is active, only the \`browser_action\` tool can be used. No other tools should be called during this time. You may proceed to use other tools only after closing the browser. For example if you run into an error and need to fix a file, you must close the browser, then use other tools to make the necessary changes, then re-launch the browser to verify the result.
+- The browser window has a resolution of **{{BROWSER_VIEWPORT_WIDTH}}x{{BROWSER_VIEWPORT_HEIGHT}}** pixels. When performing any click actions, ensure the coordinates are within this resolution range.
+- Before clicking on any elements such as icons, links, or buttons, you must consult the provided screenshot of the page to determine the coordinates of the element. The click should be targeted at the **center of the element**, not on its edges.`,
+ contextRequirements: (context) => context.supportsBrowserUse === true,
+ parameters: [
+ {
+ name: "action",
+ required: true,
+ instruction: `The action to perform. The available actions are:
+ * launch: Launch a new Puppeteer-controlled browser instance at the specified URL. This **must always be the first action**.
+ - Use with the \`url\` parameter to provide the URL.
+ - Ensure the URL is valid and includes the appropriate protocol (e.g. http://localhost:3000/page, file:///path/to/file.html, etc.)
+ * click: Click at a specific x,y coordinate.
+ - Use with the \`coordinate\` parameter to specify the location.
+ - Always click in the center of an element (icon, button, link, etc.) based on coordinates derived from a screenshot.
+ * type: Type a string of text on the keyboard. You might use this after clicking on a text field to input text.
+ - Use with the \`text\` parameter to provide the string to type.
+ * scroll_down: Scroll down the page by one page height.
+ * scroll_up: Scroll up the page by one page height.
+ * close: Close the Puppeteer-controlled browser instance. This **must always be the final browser action**.
+ - Example: 'scroll_up'`,
+ },
+ {
+ name: "url",
+ required: false,
+ instruction: `Use this for providing the URL for the \`launch\` action.`,
+ },
+ {
+ name: "coordinate",
+ required: false,
+ instruction: `x,y coordinates - The X and Y coordinates for the \`click\` action. Coordinates should be within the **{{BROWSER_VIEWPORT_WIDTH}}x{{BROWSER_VIEWPORT_HEIGHT}}** resolution. Example: '450,300'`,
+ },
+ {
+ name: "text",
+ required: false,
+ instruction: `Use this for providing the text for the \`type\` action. Example: 'Hello, world!'`,
+ },
+ ],
+}
+
+export const browser_action_variants = [GENERIC, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/execute_command.ts b/src/core/prompts/system-prompt/tools/execute_command.ts
index 42ffb587..a692c57a 100644
--- a/src/core/prompts/system-prompt/tools/execute_command.ts
+++ b/src/core/prompts/system-prompt/tools/execute_command.ts
@@ -1,9 +1,8 @@
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import type { ClineToolSpec } from "../spec"
-import { TASK_PROGRESS_PARAMETER } from "../types"
-const generic: ClineToolSpec = {
+const GENERIC: ClineToolSpec = {
variant: ModelFamily.GENERIC,
id: ClineDefaultTool.BASH,
name: "execute_command",
@@ -21,10 +20,12 @@ const generic: ClineToolSpec = {
instruction:
"A boolean indicating whether this command requires explicit user approval before execution in case the user has auto-approve mode enabled. Set to 'true' for potentially impactful operations like installing/uninstalling packages, deleting/overwriting files, system configuration changes, network operations, or any commands that could have unintended side effects. Set to 'false' for safe operations like reading files/directories, running development servers, building projects, and other non-destructive operations.",
usage: "true or false",
+ type: "boolean",
},
{
name: "timeout",
required: false,
+ type: "integer",
contextRequirements: (context) => context.yoloModeToggled === true,
instruction:
"Integer representing the timeout in seconds for how long to run the terminal command, before timing out and continuing the task.",
@@ -33,34 +34,32 @@ const generic: ClineToolSpec = {
],
}
-const gpt: ClineToolSpec = {
- variant: ModelFamily.GPT,
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
id: ClineDefaultTool.BASH,
- name: "bash",
+ name: ClineDefaultTool.BASH,
description:
- "Run an arbitrary terminal command at the root of the users project. E.g. `ls -la` for listing files, or `find` for searching latest version of the codebase files locally.",
+ "Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task.",
parameters: [
{
name: "command",
required: true,
- instruction: "The command to run in the root of the users project. Must be shell escaped.",
- usage: "Your command here",
+ instruction:
+ "The CLI command to execute. This should be valid for the current operating system. Do not use the ~ character or $HOME to refer to the home directory. Always use absolute paths.",
},
{
name: "requires_approval",
- required: false,
- instruction: "Whether the command is dangerous. If true, user will be asked to confirm.",
- },
- {
- name: "timeout",
- required: false,
- contextRequirements: (context) => context.yoloModeToggled === true,
+ required: true,
instruction:
- "Integer representing the timeout in seconds for how long to run the terminal command, before timing out and continuing the task.",
- usage: "30",
+ "To indicate whether this command requires explicit user approval or interaction before it should be executed. For system/file altering operations like installing/uninstalling packages, removing/overwriting files, system configuration changes, network operations, or any commands that are considered potentially dangerous must be set to true. False for safe operations like running development servers, building projects, and other non-destructive operations.",
+ type: "boolean",
},
- TASK_PROGRESS_PARAMETER,
],
}
-export const execute_command_variants = [generic, gpt]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+}
+
+export const execute_command_variants: ClineToolSpec[] = [GENERIC, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/focus_chain.ts b/src/core/prompts/system-prompt/tools/focus_chain.ts
index 75ef0e49..74a002d3 100644
--- a/src/core/prompts/system-prompt/tools/focus_chain.ts
+++ b/src/core/prompts/system-prompt/tools/focus_chain.ts
@@ -11,8 +11,4 @@ const generic: ClineToolSpec = {
contextRequirements: (context) => context.focusChainSettings?.enabled === true,
}
-const nextGen = { ...generic, variant: ModelFamily.NEXT_GEN }
-const gpt = { ...generic, variant: ModelFamily.GPT }
-const gemini = { ...generic, variant: ModelFamily.GEMINI }
-
-export const focus_chain_variants = [generic, nextGen, gpt, gemini]
+export const focus_chain_variants = [generic]
diff --git a/src/core/prompts/system-prompt/tools/index.ts b/src/core/prompts/system-prompt/tools/index.ts
index 00fa2f3f..d3ea8557 100644
--- a/src/core/prompts/system-prompt/tools/index.ts
+++ b/src/core/prompts/system-prompt/tools/index.ts
@@ -1,4 +1,5 @@
export * from "./access_mcp_resource"
+export * from "./apply_patch"
export * from "./ask_followup_question"
export * from "./attempt_completion"
export * from "./browser_action"
diff --git a/src/core/prompts/system-prompt/tools/init.ts b/src/core/prompts/system-prompt/tools/init.ts
index aa3fe89a..9a548f78 100644
--- a/src/core/prompts/system-prompt/tools/init.ts
+++ b/src/core/prompts/system-prompt/tools/init.ts
@@ -1,6 +1,7 @@
// Import all tool variants
import { ClineToolSet } from "../registry/ClineToolSet"
import { access_mcp_resource_variants } from "./access_mcp_resource"
+import { apply_patch_variants } from "./apply_patch"
import { ask_followup_question_variants } from "./ask_followup_question"
import { attempt_completion_variants } from "./attempt_completion"
import { browser_action_variants } from "./browser_action"
@@ -43,6 +44,7 @@ export function registerClineToolSets(): void {
...use_mcp_tool_variants,
...web_fetch_variants,
...write_to_file_variants,
+ ...apply_patch_variants,
]
// Register each variant
diff --git a/src/core/prompts/system-prompt/tools/list_code_definition_names.ts b/src/core/prompts/system-prompt/tools/list_code_definition_names.ts
index a593e80c..fbf99ca1 100644
--- a/src/core/prompts/system-prompt/tools/list_code_definition_names.ts
+++ b/src/core/prompts/system-prompt/tools/list_code_definition_names.ts
@@ -22,4 +22,25 @@ const generic: ClineToolSpec = {
],
}
-export const list_code_definition_names_variants = [generic]
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
+ id,
+ name: "list_code_definition_names",
+ description:
+ "Request to list definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.",
+ parameters: [
+ {
+ name: "path",
+ required: true,
+ instruction: `The path of the directory (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}} to list top level source code definitions for.`,
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
+
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+}
+
+export const list_code_definition_names_variants = [generic, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/list_files.ts b/src/core/prompts/system-prompt/tools/list_files.ts
index 22533662..e51d7189 100644
--- a/src/core/prompts/system-prompt/tools/list_files.ts
+++ b/src/core/prompts/system-prompt/tools/list_files.ts
@@ -24,9 +24,37 @@ const generic: ClineToolSpec = {
required: false,
instruction: "Whether to list files recursively. Use true for recursive listing, false or omit for top-level only.",
usage: "true or false (optional)",
+ type: "boolean",
},
TASK_PROGRESS_PARAMETER,
],
}
-export const list_files_variants = [generic]
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
+ id,
+ name: "list_files",
+ description:
+ "Request to list files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents. Do not use this tool to confirm the existence of files you may have created, as the user will let you know if the files were created successfully or not.",
+ parameters: [
+ {
+ name: "path",
+ required: true,
+ instruction: "The path of the directory to list contents for.",
+ },
+ {
+ name: "recursive",
+ required: false,
+ instruction: "Whether to list files recursively. Use true for recursive listing, false or omit for top-level only.",
+ type: "boolean",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
+
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+}
+
+export const list_files_variants = [generic, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/plan_mode_respond.ts b/src/core/prompts/system-prompt/tools/plan_mode_respond.ts
index a8e2521f..f0ea3e7b 100644
--- a/src/core/prompts/system-prompt/tools/plan_mode_respond.ts
+++ b/src/core/prompts/system-prompt/tools/plan_mode_respond.ts
@@ -41,6 +41,7 @@ However, if while writing your response you realize you actually need to do more
instruction:
"Set to true if while formulating your response that you found you need to do more exploration with tools, for example reading files. (Remember, you can explore the project with tools like read_file in PLAN MODE without the user having to toggle to ACT MODE.) Defaults to false if not specified.",
usage: "true or false (optional, but you MUST set to true if in you need to read files or use other exploration tools)",
+ type: "boolean",
},
// Different than the vanilla TASK_PROGRESS_PARAMETER
{
@@ -54,4 +55,30 @@ However, if while writing your response you realize you actually need to do more
],
}
-export const plan_mode_respond_variants = [generic]
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
+ id,
+ name: "plan_mode_respond",
+ description: `Respond to the user's inquiry in an effort to plan a solution to the user's task. This tool should ONLY be used when you have already explored the relevant files and are ready to present a concrete plan. DO NOT use this tool to announce what files you're going to read - just read them first. This tool is only available in PLAN MODE. The environment_details will specify the current mode; if it is not PLAN_MODE then you should not use this tool.
+However, if while writing your response you realize you actually need to do more exploration before providing a complete plan, you can add the optional needs_more_exploration parameter to indicate this. This allows you to acknowledge that you should have done more exploration first, and signals that your next message will use exploration tools instead.`,
+ parameters: [
+ {
+ name: "response",
+ required: true,
+ instruction: `The response to provide to the user. Do not try to use tools in this parameter, this is simply a chat response. (You MUST use the response parameter, do not simply place the response text directly within tags.)`,
+ usage: "Your response here",
+ },
+ {
+ name: "task_progress",
+ required: false,
+ instruction: "A checklist showing task progress with the latest status of each subtasks included previously if any.",
+ },
+ ],
+}
+
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+}
+
+export const plan_mode_respond_variants = [generic, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/read_file.ts b/src/core/prompts/system-prompt/tools/read_file.ts
index 5c3c7b45..f60c517f 100644
--- a/src/core/prompts/system-prompt/tools/read_file.ts
+++ b/src/core/prompts/system-prompt/tools/read_file.ts
@@ -22,8 +22,26 @@ const generic: ClineToolSpec = {
],
}
-const nextGen = { ...generic, variant: ModelFamily.NEXT_GEN }
-const gpt = { ...generic, variant: ModelFamily.GPT }
-const gemini = { ...generic, variant: ModelFamily.GEMINI }
+const NATIVE_GPT_5: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_GPT_5,
+ id,
+ name: "read_file",
+ description:
+ "Request to read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file you do not know the contents of, for example to analyze code, review text files, or extract information from configuration files. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string. Do NOT use this tool to list the contents of a directory. Only use this tool on files.",
+ parameters: [
+ {
+ name: "path",
+ required: true,
+ instruction: `The path of the file to read (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}}`,
+ usage: "File path here",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
-export const read_file_variants = [generic, nextGen, gpt, gemini]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ ...NATIVE_GPT_5,
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+}
+
+export const read_file_variants = [generic, NATIVE_NEXT_GEN, NATIVE_GPT_5]
diff --git a/src/core/prompts/system-prompt/tools/replace_in_file.ts b/src/core/prompts/system-prompt/tools/replace_in_file.ts
index 396ad349..a23488eb 100644
--- a/src/core/prompts/system-prompt/tools/replace_in_file.ts
+++ b/src/core/prompts/system-prompt/tools/replace_in_file.ts
@@ -51,8 +51,48 @@ const generic: ClineToolSpec = {
],
}
-const nextGen = { ...generic, variant: ModelFamily.NEXT_GEN }
-const gpt = { ...generic, variant: ModelFamily.GPT }
-const gemini = { ...generic, variant: ModelFamily.GEMINI }
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id,
+ name: "replace_in_file",
+ description:
+ "[IMPORTANT: Always output the absolutePath first] Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
+ parameters: [
+ {
+ name: "absolutePath",
+ required: true,
+ instruction: "The absolute path to the file to write to.",
+ },
+ {
+ name: "diff",
+ required: true,
+ instruction: `One or more SEARCH/REPLACE blocks following this exact format:
+ \`\`\`
+ ------- SEARCH
+ [exact content to find]
+ =======
+ [new content to replace with]
+ +++++++ REPLACE
+ \`\`\`
+ Critical rules:
+ 1. SEARCH content must match the associated file section to find EXACTLY:
+ * Match character-for-character including whitespace, indentation, line endings
+ * Include all comments, docstrings, etc.
+ 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
+ * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
+ * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
+ * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
+ 3. Keep SEARCH/REPLACE blocks concise:
+ * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
+ * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
+ * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
+ * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
+ 4. Special operations:
+ * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
+ * To delete code: Use empty REPLACE section`,
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
-export const replace_in_file_variants = [generic, nextGen, gpt, gemini]
+export const replace_in_file_variants = [generic, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/search_files.ts b/src/core/prompts/system-prompt/tools/search_files.ts
index a45bb3ab..4b2d2cb4 100644
--- a/src/core/prompts/system-prompt/tools/search_files.ts
+++ b/src/core/prompts/system-prompt/tools/search_files.ts
@@ -50,4 +50,39 @@ const generic: ClineToolSpec = {
],
}
-export const search_files_variants = [generic]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id,
+ name: "search_files",
+ description:
+ "Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.",
+ parameters: [
+ {
+ name: "path",
+ required: true,
+ instruction: `The path of the directory to search in (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}}. This directory will be recursively searched.`,
+ usage: "Directory path here",
+ },
+ {
+ name: "regex",
+ required: true,
+ instruction: "The regular expression pattern to search for. Uses Rust regex syntax.",
+ usage: "Your regex pattern here",
+ },
+ {
+ name: "file_pattern",
+ required: false,
+ instruction:
+ "Glob pattern to filter files (e.g., '*.ts' for TypeScript files). If not provided, it will search all files (*).",
+ usage: "file pattern here (optional)",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
+
+const NATIVE_GPT_5: ClineToolSpec = {
+ ...NATIVE_NEXT_GEN,
+ variant: ModelFamily.NATIVE_GPT_5,
+}
+
+export const search_files_variants = [generic, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/use_mcp_tool.ts b/src/core/prompts/system-prompt/tools/use_mcp_tool.ts
index b37e65c3..e00ebd8a 100644
--- a/src/core/prompts/system-prompt/tools/use_mcp_tool.ts
+++ b/src/core/prompts/system-prompt/tools/use_mcp_tool.ts
@@ -66,8 +66,4 @@ const generic: ClineToolSpec = {
],
}
-const nextGen = { ...generic, variant: ModelFamily.NEXT_GEN }
-const gpt = { ...generic, variant: ModelFamily.GPT }
-const gemini = { ...generic, variant: ModelFamily.GEMINI }
-
-export const use_mcp_tool_variants = [generic, nextGen, gpt, gemini]
+export const use_mcp_tool_variants = [generic]
diff --git a/src/core/prompts/system-prompt/tools/web_fetch.ts b/src/core/prompts/system-prompt/tools/web_fetch.ts
index 8a0de774..b99ae2aa 100644
--- a/src/core/prompts/system-prompt/tools/web_fetch.ts
+++ b/src/core/prompts/system-prompt/tools/web_fetch.ts
@@ -26,6 +26,24 @@ const nextGen: ClineToolSpec = {
],
}
-const gpt = { ...nextGen, variant: ModelFamily.GPT }
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id: ClineDefaultTool.WEB_FETCH,
+ name: "web_fetch",
+ description: "Fetches content from a specified URL. Only used for gathering needed information relevant to the task.",
+ parameters: [
+ {
+ name: "url",
+ required: true,
+ instruction: "The URL to fetch content from",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
-export const web_fetch_variants = [nextGen, gpt]
+const NATIVE_GPT_5: ClineToolSpec = {
+ ...NATIVE_NEXT_GEN,
+ variant: ModelFamily.NATIVE_GPT_5,
+}
+
+export const web_fetch_variants = [nextGen, NATIVE_GPT_5, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/tools/write_to_file.ts b/src/core/prompts/system-prompt/tools/write_to_file.ts
index d8957e5e..0ebb0e7e 100644
--- a/src/core/prompts/system-prompt/tools/write_to_file.ts
+++ b/src/core/prompts/system-prompt/tools/write_to_file.ts
@@ -24,7 +24,7 @@ Checklist here (optional)
const id = ClineDefaultTool.FILE_NEW
-const generic: ClineToolSpec = {
+const GENERIC: ClineToolSpec = {
variant: ModelFamily.GENERIC,
id,
name: "write_to_file",
@@ -48,4 +48,26 @@ const generic: ClineToolSpec = {
],
}
-export const write_to_file_variants = [generic]
+const NATIVE_NEXT_GEN: ClineToolSpec = {
+ variant: ModelFamily.NATIVE_NEXT_GEN,
+ id,
+ name: "write_to_file",
+ description:
+ "[IMPORTANT: Always output the absolutePath first] Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.",
+ parameters: [
+ {
+ name: "absolutePath",
+ required: true,
+ instruction: "The absolute path to the file to write to.",
+ },
+ {
+ name: "content",
+ required: true,
+ instruction:
+ "After providing the path so a file can be created, then use this to provide the content to write to the file.",
+ },
+ TASK_PROGRESS_PARAMETER,
+ ],
+}
+
+export const write_to_file_variants = [GENERIC, NATIVE_NEXT_GEN]
diff --git a/src/core/prompts/system-prompt/types.ts b/src/core/prompts/system-prompt/types.ts
index 5ba89285..ab353e55 100644
--- a/src/core/prompts/system-prompt/types.ts
+++ b/src/core/prompts/system-prompt/types.ts
@@ -30,6 +30,7 @@ export interface PromptVariant {
readonly labels: Readonly> // Immutable labels mapping
readonly family: ModelFamily // Model family enum
readonly description: string // Brief description of the variant
+ readonly matcher: (context: SystemPromptContext) => boolean // Function to determine if this variant should be used for the given providerInfo
// Prompt configuration
readonly config: PromptConfig // Model-specific config
@@ -53,6 +54,7 @@ export interface MutablePromptVariant {
labels: Record
family: ModelFamily
description?: string
+ matcher?: (providerInfo: ApiProviderInfo) => boolean
config: PromptConfig
baseTemplate?: string
componentOrder: SystemPromptSection[]
@@ -110,6 +112,7 @@ export interface SystemPromptContext {
readonly workspaceRoots?: Array<{ path: string; name: string; vcs?: string }>
readonly isSubagentsEnabledAndCliInstalled?: boolean
readonly isCliSubagent?: boolean
+ readonly enableNativeToolCalls?: boolean
}
/**
@@ -182,6 +185,7 @@ export interface VariantBuilder {
version(version: number): this
tags(...tags: string[]): this
labels(labels: Record): this
+ matcher(matcherFn: (providerInfo: ApiProviderInfo) => boolean): this
template(baseTemplate: string): this
components(...sections: SystemPromptSection[]): this
overrideComponent(section: SystemPromptSection, override: ConfigOverride): this
diff --git a/src/core/prompts/system-prompt/variants/generic/config.ts b/src/core/prompts/system-prompt/variants/generic/config.ts
index ceeabec0..57f91678 100644
--- a/src/core/prompts/system-prompt/variants/generic/config.ts
+++ b/src/core/prompts/system-prompt/variants/generic/config.ts
@@ -1,3 +1,4 @@
+import { isGLMModelFamily, isLocalModel, isNextGenModelFamily, isNextGenModelProvider } from "@utils/model-utils"
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import { SystemPromptSection } from "../../templates/placeholders"
@@ -13,6 +14,23 @@ export const config = createVariant(ModelFamily.GENERIC)
stable: 1,
fallback: 1,
})
+ // Generic matcher - fallback for everything that doesn't match other variants
+ // This will match anything that doesn't match the other specific variants
+ .matcher((context) => {
+ const providerInfo = context.providerInfo
+ if (!providerInfo.providerId || !providerInfo.model.id) {
+ return true
+ }
+ const modelId = providerInfo.model.id.toLowerCase()
+ return (
+ // Not a local model with compact prompt enabled
+ !(providerInfo.customPrompt === "compact" && isLocalModel(providerInfo)) &&
+ // Not a next-gen model
+ !(isNextGenModelProvider(providerInfo) && isNextGenModelFamily(modelId)) &&
+ // Not a GLM model
+ !isGLMModelFamily(modelId)
+ )
+ })
.template(baseTemplate)
.components(
SystemPromptSection.AGENT_ROLE,
diff --git a/src/core/prompts/system-prompt/variants/glm/config.ts b/src/core/prompts/system-prompt/variants/glm/config.ts
index f9ce426a..2dbe038f 100644
--- a/src/core/prompts/system-prompt/variants/glm/config.ts
+++ b/src/core/prompts/system-prompt/variants/glm/config.ts
@@ -1,5 +1,6 @@
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
+import { isGLMModelFamily } from "@/utils/model-utils"
import { SystemPromptSection } from "../../templates/placeholders"
import { createVariant } from "../variant-builder"
import { validateVariant } from "../variant-validator"
@@ -14,6 +15,9 @@ export const config = createVariant(ModelFamily.GLM)
stable: 1,
production: 1,
})
+ .matcher((context) => {
+ return isGLMModelFamily(context.providerInfo.model.id)
+ })
.template(baseTemplate)
.components(
SystemPromptSection.AGENT_ROLE,
@@ -49,7 +53,7 @@ export const config = createVariant(ModelFamily.GLM)
ClineDefaultTool.TODO,
)
.placeholders({
- MODEL_FAMILY: "glm",
+ MODEL_FAMILY: ModelFamily.GLM,
})
.config({})
// Apply GLM-specific component overrides
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 fa8b10b6..2b26b55e 100644
--- a/src/core/prompts/system-prompt/variants/gpt-5/config.ts
+++ b/src/core/prompts/system-prompt/variants/gpt-5/config.ts
@@ -1,13 +1,14 @@
+import { isGPT5ModelFamily, isNextGenModelProvider } from "@utils/model-utils"
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import { SystemPromptSection } from "../../templates/placeholders"
import { createVariant } from "../variant-builder"
import { validateVariant } from "../variant-validator"
-import { baseTemplate, rules_template } from "./template"
+import { GPT_5_TEMPLATE_OVERRIDES } from "./template"
// Type-safe variant configuration using the builder pattern
export const config = createVariant(ModelFamily.GPT_5)
- .description("Prompt tailored to GPT-5")
+ .description("Prompt tailored to GPT-5 with native tool use support")
.version(1)
.tags("gpt", "gpt-5", "advanced", "production")
.labels({
@@ -15,7 +16,18 @@ export const config = createVariant(ModelFamily.GPT_5)
production: 1,
advanced: 1,
})
- .template(baseTemplate)
+ // Match GPT-5 models from providers that support native tools
+ .matcher((context) => {
+ const providerInfo = context.providerInfo
+ const modelId = providerInfo.model.id
+ return (
+ isGPT5ModelFamily(modelId) &&
+ !modelId.includes("chat") &&
+ isNextGenModelProvider(providerInfo) &&
+ !context.enableNativeToolCalls
+ )
+ })
+ .template(GPT_5_TEMPLATE_OVERRIDES.BASE)
.components(
SystemPromptSection.AGENT_ROLE,
SystemPromptSection.TOOL_USE,
@@ -35,8 +47,7 @@ export const config = createVariant(ModelFamily.GPT_5)
.tools(
ClineDefaultTool.BASH,
ClineDefaultTool.FILE_READ,
- ClineDefaultTool.FILE_NEW,
- ClineDefaultTool.FILE_EDIT,
+ ClineDefaultTool.APPLY_PATCH,
ClineDefaultTool.SEARCH,
ClineDefaultTool.LIST_FILES,
ClineDefaultTool.LIST_CODE_DEF,
@@ -57,12 +68,12 @@ export const config = createVariant(ModelFamily.GPT_5)
.config({})
// Override the RULES component with custom template
.overrideComponent(SystemPromptSection.RULES, {
- template: rules_template,
+ template: GPT_5_TEMPLATE_OVERRIDES.RULES,
})
.build()
// Compile-time validation
-const validationResult = validateVariant({ ...config, id: "gpt-5" }, { strict: true })
+const validationResult = validateVariant({ ...config, id: ModelFamily.GPT_5 }, { strict: true })
if (!validationResult.isValid) {
console.error("GPT-5 variant configuration validation failed:", validationResult.errors)
throw new Error(`Invalid GPT-5 variant configuration: ${validationResult.errors.join(", ")}`)
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 1b9ab7a1..7f1e8826 100644
--- a/src/core/prompts/system-prompt/variants/gpt-5/template.ts
+++ b/src/core/prompts/system-prompt/variants/gpt-5/template.ts
@@ -1,7 +1,11 @@
import { SystemPromptSection } from "../../templates/placeholders"
import type { SystemPromptContext } from "../../types"
-export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}
+/**
+ * Base template for GPT-5 variant with structured sections
+ * Removed SystemPromptSection.TASK_PROGRESS
+ */
+export const BASE = `{{${SystemPromptSection.AGENT_ROLE}}}
{{${SystemPromptSection.TOOL_USE}}}
@@ -53,7 +57,7 @@ export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}
{{${SystemPromptSection.USER_INSTRUCTIONS}}}`
-export const rules_template = (context: SystemPromptContext) => `RULES
+const RULES = (context: SystemPromptContext) => `RULES
- Your current working directory is: {{CWD}}
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '{{CWD}}', so be sure to pass in the correct 'path' parameter when using tools that require a path.
@@ -80,3 +84,8 @@ export const rules_template = (context: SystemPromptContext) => `RULES
- When using the replace_in_file tool, Do NOT add extra characters to the markers (e.g., ------- SEARCH> is INVALID). Do NOT forget to use the closing +++++++ REPLACE marker. Do NOT modify the marker format in any way. Malformed XML will cause complete tool failure and break the entire editing process.
- It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to make a todo app, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.{{BROWSER_WAIT_RULES}}
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.`
+
+export const GPT_5_TEMPLATE_OVERRIDES = {
+ BASE,
+ RULES,
+} as const
diff --git a/src/core/prompts/system-prompt/variants/index.ts b/src/core/prompts/system-prompt/variants/index.ts
index 500f4fe9..1390e1e2 100644
--- a/src/core/prompts/system-prompt/variants/index.ts
+++ b/src/core/prompts/system-prompt/variants/index.ts
@@ -9,6 +9,8 @@
export { config as genericConfig, type GenericVariantConfig } from "./generic/config"
export { config as glmConfig, type GLMVariantConfig } from "./glm/config"
export { config as gpt5Config, type GPT5VariantConfig } from "./gpt-5/config"
+export { config as NativeGPT5Config } from "./native-gpt-5/config"
+export { config as nativeNextGenConfig, type NativeNextGenVariantConfig } from "./native-next-gen/config"
export { config as nextGenConfig, type NextGenVariantConfig } from "./next-gen/config"
export { config as xsConfig, type XsVariantConfig } from "./xs/config"
@@ -16,6 +18,8 @@ import { ModelFamily } from "@/shared/prompts"
import { config as genericConfig } from "./generic/config"
import { config as glmConfig } from "./glm/config"
import { config as gpt5Config } from "./gpt-5/config"
+import { config as NativeGPT5Config } from "./native-gpt-5/config"
+import { config as NativeNextGenVariantConfig } from "./native-next-gen/config"
import { config as nextGenConfig } from "./next-gen/config"
import { config as xsConfig } from "./xs/config"
@@ -26,10 +30,17 @@ import { config as xsConfig } from "./xs/config"
*/
export const VARIANT_CONFIGS = {
/**
- * Generic variant - Fallback for all model types
- * Optimized for broad compatibility and stable performance
+ * GPT-5 variant with native tool support.
*/
- [ModelFamily.GENERIC]: genericConfig,
+ [ModelFamily.NATIVE_GPT_5]: NativeGPT5Config,
+ /**
+ * GPT-5 variant without native tool support.
+ */
+ [ModelFamily.GPT_5]: gpt5Config,
+ /**
+ * Next-gen variant with native tool support.
+ */
+ [ModelFamily.NATIVE_NEXT_GEN]: NativeNextGenVariantConfig,
/**
* GLM variant - Optimized for GLM-4.6 model
* Configured for advanced agentic coding capabilities
@@ -40,15 +51,16 @@ export const VARIANT_CONFIGS = {
* Includes additional features like feedback loops and web fetching
*/
[ModelFamily.NEXT_GEN]: nextGenConfig,
- /**
- * GPT-5 variant
- */
- [ModelFamily.GPT_5]: gpt5Config,
/**
* XS variant - Compact models with limited context windows
* Streamlined for efficiency with essential tools only
*/
[ModelFamily.XS]: xsConfig,
+ /**
+ * Generic variant - Fallback for any model types not specifically covered above.
+ * Optimized for broad compatibility and stable performance.
+ */
+ [ModelFamily.GENERIC]: genericConfig,
} as const
/**
diff --git a/src/core/prompts/system-prompt/variants/native-gpt-5/config.ts b/src/core/prompts/system-prompt/variants/native-gpt-5/config.ts
new file mode 100644
index 00000000..e1f7bbd9
--- /dev/null
+++ b/src/core/prompts/system-prompt/variants/native-gpt-5/config.ts
@@ -0,0 +1,96 @@
+import { isGPT5ModelFamily, isNextGenModelProvider } from "@utils/model-utils"
+import { ModelFamily } from "@/shared/prompts"
+import { ClineDefaultTool } from "@/shared/tools"
+import { SystemPromptSection } from "../../templates/placeholders"
+import { createVariant } from "../variant-builder"
+import { validateVariant } from "../variant-validator"
+import { GPT_5_TEMPLATE_OVERRIDES } from "./template"
+
+// Type-safe variant configuration using the builder pattern
+export const config = createVariant(ModelFamily.NATIVE_GPT_5)
+ .description("Prompt tailored to GPT-5 with native tool use support")
+ .version(1)
+ .tags("gpt", "gpt-5", "advanced", "production", "native_tools")
+ .labels({
+ stable: 1,
+ production: 1,
+ advanced: 1,
+ use_native_tools: 1,
+ })
+ // Match GPT-5 models from providers that support native tools
+ .matcher((context) => {
+ if (!context.enableNativeToolCalls) {
+ return false
+ }
+ const providerInfo = context.providerInfo
+ const modelId = providerInfo.model.id
+
+ // gpt-5-chat models do not support native tool use
+ return isGPT5ModelFamily(modelId) && !modelId.includes("chat") && isNextGenModelProvider(providerInfo)
+ })
+ .template(GPT_5_TEMPLATE_OVERRIDES.BASE)
+ .components(
+ SystemPromptSection.AGENT_ROLE,
+ SystemPromptSection.TOOL_USE,
+ SystemPromptSection.TODO,
+ SystemPromptSection.ACT_VS_PLAN,
+ SystemPromptSection.CLI_SUBAGENTS,
+ SystemPromptSection.CAPABILITIES,
+ SystemPromptSection.FEEDBACK,
+ SystemPromptSection.RULES,
+ SystemPromptSection.SYSTEM_INFO,
+ SystemPromptSection.OBJECTIVE,
+ SystemPromptSection.USER_INSTRUCTIONS,
+ )
+ .tools(
+ ClineDefaultTool.BASH,
+ ClineDefaultTool.FILE_READ,
+ ClineDefaultTool.APPLY_PATCH,
+ ClineDefaultTool.SEARCH,
+ ClineDefaultTool.LIST_FILES,
+ ClineDefaultTool.LIST_CODE_DEF,
+ ClineDefaultTool.BROWSER,
+ ClineDefaultTool.WEB_FETCH,
+ ClineDefaultTool.MCP_ACCESS,
+ ClineDefaultTool.ASK,
+ ClineDefaultTool.ATTEMPT,
+ ClineDefaultTool.NEW_TASK,
+ ClineDefaultTool.PLAN_MODE,
+ ClineDefaultTool.MCP_DOCS,
+ ClineDefaultTool.TODO,
+ )
+ .placeholders({
+ MODEL_FAMILY: ModelFamily.NATIVE_GPT_5,
+ })
+ .config({})
+ // Override the RULES component with custom template
+ .overrideComponent(SystemPromptSection.RULES, {
+ template: GPT_5_TEMPLATE_OVERRIDES.RULES,
+ })
+ .overrideComponent(SystemPromptSection.TOOL_USE, {
+ template: GPT_5_TEMPLATE_OVERRIDES.TOOL_USE,
+ })
+ .overrideComponent(SystemPromptSection.ACT_VS_PLAN, {
+ template: GPT_5_TEMPLATE_OVERRIDES.ACT_VS_PLAN,
+ })
+ .overrideComponent(SystemPromptSection.OBJECTIVE, {
+ template: GPT_5_TEMPLATE_OVERRIDES.OBJECTIVE,
+ })
+ .overrideComponent(SystemPromptSection.FEEDBACK, {
+ template: GPT_5_TEMPLATE_OVERRIDES.FEEDBACK,
+ })
+ .build()
+
+// Compile-time validation
+const validationResult = validateVariant({ ...config, id: ModelFamily.NATIVE_GPT_5 }, { strict: true })
+if (!validationResult.isValid) {
+ console.error("GPT-5 variant configuration validation failed:", validationResult.errors)
+ throw new Error(`Invalid GPT-5 variant configuration: ${validationResult.errors.join(", ")}`)
+}
+
+if (validationResult.warnings.length > 0) {
+ console.warn("GPT-5 variant configuration warnings:", validationResult.warnings)
+}
+
+// Export type information for better IDE support
+export type GPT5VariantConfig = typeof config
diff --git a/src/core/prompts/system-prompt/variants/native-gpt-5/template.ts b/src/core/prompts/system-prompt/variants/native-gpt-5/template.ts
new file mode 100644
index 00000000..df4cf61d
--- /dev/null
+++ b/src/core/prompts/system-prompt/variants/native-gpt-5/template.ts
@@ -0,0 +1,101 @@
+import { SystemPromptSection } from "../../templates/placeholders"
+import type { SystemPromptContext } from "../../types"
+
+/**
+ * Base template for GPT-5 variant with structured sections
+ * Removed SystemPromptSection.TASK_PROGRESS
+ */
+export const BASE = `{{${SystemPromptSection.AGENT_ROLE}}}
+
+{{${SystemPromptSection.TOOL_USE}}}
+
+====
+
+{{${SystemPromptSection.TODO}}}
+
+====
+
+{{${SystemPromptSection.EDITING_FILES}}}
+
+====
+
+{{${SystemPromptSection.ACT_VS_PLAN}}}
+
+====
+
+{{${SystemPromptSection.CLI_SUBAGENTS}}}
+
+====
+
+{{${SystemPromptSection.CAPABILITIES}}}
+
+====
+
+{{${SystemPromptSection.FEEDBACK}}}
+
+====
+
+{{${SystemPromptSection.RULES}}}
+
+====
+
+{{${SystemPromptSection.SYSTEM_INFO}}}
+
+====
+
+{{${SystemPromptSection.OBJECTIVE}}}
+
+====
+
+{{${SystemPromptSection.USER_INSTRUCTIONS}}}`
+
+const RULES = (_context: SystemPromptContext) => `RULES
+
+- Your current working directory is: {{CWD}} - this is where you will be using tools from.
+- Do not use the ~ character or $HOME to refer to the home directory. Use absolute paths instead.
+- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.`
+
+const TOOL_USE = (_context: SystemPromptContext) => `TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.`
+
+const ACT_VS_PLAN = (context: SystemPromptContext) => `ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task.${context.yoloModeToggled !== true ? " You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task." : ""}
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.`
+
+const OBJECTIVE = (context: SystemPromptContext) => `OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params)${context.yoloModeToggled !== true ? " and instead, ask the user to provide the missing parameters using the ask_followup_question tool" : ""}. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.`
+
+const FEEDBACK = (_context: SystemPromptContext) => `FEEDBACK
+
+When user is providing you with feedback on how you could improve, you can let the user know to report new issue using the '/reportbug' slash command.`
+
+export const GPT_5_TEMPLATE_OVERRIDES = {
+ BASE,
+ RULES,
+ TOOL_USE,
+ OBJECTIVE,
+ FEEDBACK,
+ ACT_VS_PLAN,
+} as const
diff --git a/src/core/prompts/system-prompt/variants/native-next-gen/config.ts b/src/core/prompts/system-prompt/variants/native-next-gen/config.ts
new file mode 100644
index 00000000..63415bc4
--- /dev/null
+++ b/src/core/prompts/system-prompt/variants/native-next-gen/config.ts
@@ -0,0 +1,97 @@
+import { isGPT5ModelFamily, isNextGenModelFamily, isNextGenModelProvider } from "@utils/model-utils"
+import { ModelFamily } from "@/shared/prompts"
+import { ClineDefaultTool } from "@/shared/tools"
+import { SystemPromptSection } from "../../templates/placeholders"
+import { createVariant } from "../variant-builder"
+import { validateVariant } from "../variant-validator"
+import { TEMPLATE_OVERRIDES } from "./template"
+
+// Type-safe variant configuration using the builder pattern
+export const config = createVariant(ModelFamily.NATIVE_NEXT_GEN)
+ .description("Next gen models with native tool calling")
+ .version(1)
+ .tags("advanced", "production", "native_tools")
+ .labels({
+ stable: 1,
+ production: 1,
+ advanced: 1,
+ use_native_tools: 1,
+ })
+ .matcher((context) => {
+ if (!context.enableNativeToolCalls) {
+ return false
+ }
+ const providerInfo = context.providerInfo
+ if (!isNextGenModelProvider(providerInfo)) {
+ return false
+ }
+ const modelId = providerInfo.model.id.toLowerCase()
+ return !isGPT5ModelFamily(modelId) && isNextGenModelFamily(modelId)
+ })
+ .template(TEMPLATE_OVERRIDES.BASE)
+ .components(
+ SystemPromptSection.AGENT_ROLE,
+ SystemPromptSection.TOOL_USE,
+ SystemPromptSection.TODO,
+ SystemPromptSection.ACT_VS_PLAN,
+ SystemPromptSection.TASK_PROGRESS,
+ SystemPromptSection.CAPABILITIES,
+ SystemPromptSection.FEEDBACK,
+ SystemPromptSection.RULES,
+ SystemPromptSection.SYSTEM_INFO,
+ SystemPromptSection.OBJECTIVE,
+ SystemPromptSection.USER_INSTRUCTIONS,
+ )
+ .tools(
+ ClineDefaultTool.ASK,
+ ClineDefaultTool.BASH,
+ ClineDefaultTool.FILE_READ,
+ ClineDefaultTool.FILE_NEW,
+ ClineDefaultTool.FILE_EDIT,
+ ClineDefaultTool.SEARCH,
+ ClineDefaultTool.LIST_FILES,
+ ClineDefaultTool.LIST_CODE_DEF,
+ ClineDefaultTool.BROWSER,
+ ClineDefaultTool.WEB_FETCH,
+ ClineDefaultTool.MCP_ACCESS,
+ ClineDefaultTool.ATTEMPT,
+ ClineDefaultTool.NEW_TASK,
+ ClineDefaultTool.PLAN_MODE,
+ ClineDefaultTool.MCP_DOCS,
+ ClineDefaultTool.TODO,
+ )
+ .placeholders({
+ MODEL_FAMILY: ModelFamily.NATIVE_NEXT_GEN,
+ })
+ .config({})
+ // Override the RULES component with custom template
+ .overrideComponent(SystemPromptSection.RULES, {
+ template: TEMPLATE_OVERRIDES.RULES,
+ })
+ .overrideComponent(SystemPromptSection.TOOL_USE, {
+ template: TEMPLATE_OVERRIDES.TOOL_USE,
+ })
+ .overrideComponent(SystemPromptSection.OBJECTIVE, {
+ template: TEMPLATE_OVERRIDES.OBJECTIVE,
+ })
+ .overrideComponent(SystemPromptSection.ACT_VS_PLAN, {
+ template: TEMPLATE_OVERRIDES.ACT_VS_PLAN,
+ })
+ .overrideComponent(SystemPromptSection.FEEDBACK, {
+ template: TEMPLATE_OVERRIDES.FEEDBACK,
+ })
+ .build()
+
+// Compile-time validation
+const validationResult = validateVariant({ ...config, id: ModelFamily.NATIVE_NEXT_GEN }, { strict: true })
+if (!validationResult.isValid) {
+ console.error("Native Next Gen variant configuration validation failed:", validationResult.errors)
+ throw new Error(`Invalid Native Next Gen variant configuration: ${validationResult.errors.join(", ")}`)
+}
+
+if (validationResult.warnings.length > 0) {
+ console.warn("Native Next Gen variant configuration warnings:", validationResult.warnings)
+}
+
+// Export type information for better IDE support
+export type NativeNextGenVariantConfig = typeof config
diff --git a/src/core/prompts/system-prompt/variants/native-next-gen/template.ts b/src/core/prompts/system-prompt/variants/native-next-gen/template.ts
new file mode 100644
index 00000000..c636e872
--- /dev/null
+++ b/src/core/prompts/system-prompt/variants/native-next-gen/template.ts
@@ -0,0 +1,95 @@
+import { SystemPromptSection } from "../../templates/placeholders"
+import type { SystemPromptContext } from "../../types"
+
+/**
+ * Base template for GPT-5 variant with structured sections
+ * Removed SystemPromptSection.TASK_PROGRESS
+ */
+export const BASE = `{{${SystemPromptSection.AGENT_ROLE}}}
+
+{{${SystemPromptSection.TOOL_USE}}}
+
+====
+
+{{${SystemPromptSection.TODO}}}
+
+====
+
+{{${SystemPromptSection.EDITING_FILES}}}
+
+====
+
+{{${SystemPromptSection.ACT_VS_PLAN}}}
+
+====
+
+{{${SystemPromptSection.CAPABILITIES}}}
+
+====
+
+{{${SystemPromptSection.FEEDBACK}}}
+
+====
+
+{{${SystemPromptSection.RULES}}}
+
+====
+
+{{${SystemPromptSection.SYSTEM_INFO}}}
+
+====
+
+{{${SystemPromptSection.OBJECTIVE}}}
+
+====
+
+{{${SystemPromptSection.USER_INSTRUCTIONS}}}`
+
+const RULES = (_context: SystemPromptContext) => `RULES
+
+- The current working directory is \`{{CWD}}\` - this is the directory where all the tools will be executed from.`
+
+const TOOL_USE = (_context: SystemPromptContext) => `TOOL USE
+
+You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.`
+
+const ACT_VS_PLAN = (context: SystemPromptContext) => `ACT MODE V.S. PLAN MODE
+
+In each user message, the environment_details will specify the current mode. There are two modes:
+
+- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
+ - In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
+- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
+ - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
+ - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
+
+## What is PLAN MODE?
+
+- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
+- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task.${context.yoloModeToggled !== true ? " You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task." : ""}
+- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
+- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
+- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.`
+
+const OBJECTIVE = (context: SystemPromptContext) => `OBJECTIVE
+
+You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
+
+1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
+2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
+3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params)${context.yoloModeToggled !== true ? " and instead, ask the user to provide the missing parameters using the ask_followup_question tool" : ""}. DO NOT ask for more information on optional parameters if it is not provided.
+4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
+5. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.`
+
+const FEEDBACK = (_context: SystemPromptContext) => `FEEDBACK
+
+When user is providing you with feedback on how you could improve, you can let the user know to report new issue using the '/reportbug' slash command.`
+
+export const TEMPLATE_OVERRIDES = {
+ BASE,
+ RULES,
+ TOOL_USE,
+ OBJECTIVE,
+ FEEDBACK,
+ ACT_VS_PLAN,
+} as const
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 f445a856..5f853276 100644
--- a/src/core/prompts/system-prompt/variants/next-gen/config.ts
+++ b/src/core/prompts/system-prompt/variants/next-gen/config.ts
@@ -1,3 +1,4 @@
+import { isGPT5ModelFamily, isLocalModel, isNextGenModelFamily, isNextGenModelProvider } from "@utils/model-utils"
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import { SystemPromptSection } from "../../templates/placeholders"
@@ -15,6 +16,20 @@ export const config = createVariant(ModelFamily.NEXT_GEN)
production: 1,
advanced: 1,
})
+ .matcher((context) => {
+ // Match next-gen models
+ const providerInfo = context.providerInfo
+ if (isNextGenModelFamily(providerInfo.model.id) && !context.enableNativeToolCalls) {
+ return true
+ }
+ const modelId = providerInfo.model.id
+ return (
+ !(providerInfo.customPrompt === "compact" && isLocalModel(providerInfo)) &&
+ !isNextGenModelProvider(providerInfo) &&
+ isNextGenModelFamily(modelId) &&
+ !(isGPT5ModelFamily(modelId) && !modelId.includes("chat"))
+ )
+ })
.template(baseTemplate)
.components(
SystemPromptSection.AGENT_ROLE,
@@ -62,7 +77,7 @@ export const config = createVariant(ModelFamily.NEXT_GEN)
.build()
// Compile-time validation
-const validationResult = validateVariant({ ...config, id: "next-gen" }, { strict: true })
+const validationResult = validateVariant({ ...config, id: ModelFamily.NEXT_GEN }, { strict: true })
if (!validationResult.isValid) {
console.error("Next-gen variant configuration validation failed:", validationResult.errors)
throw new Error(`Invalid next-gen variant configuration: ${validationResult.errors.join(", ")}`)
diff --git a/src/core/prompts/system-prompt/variants/variant-builder.ts b/src/core/prompts/system-prompt/variants/variant-builder.ts
index 7a621cc6..d3c65438 100644
--- a/src/core/prompts/system-prompt/variants/variant-builder.ts
+++ b/src/core/prompts/system-prompt/variants/variant-builder.ts
@@ -1,7 +1,7 @@
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import { SystemPromptSection } from "../templates/placeholders"
-import type { ConfigOverride, PromptVariant } from "../types"
+import type { ConfigOverride, PromptVariant, SystemPromptContext } from "../types"
/**
* Type-safe builder for creating prompt variants
@@ -60,6 +60,7 @@ export class VariantBuilder {
/**
* Set labels with version mapping
+ * e.g., use_native_tools: 1 to indicate support for native tools
*/
labels(labels: Record): this {
this.variant = {
@@ -69,6 +70,17 @@ export class VariantBuilder {
return this
}
+ /**
+ * Set the matcher function to determine if this variant should be used for the given context
+ */
+ matcher(matcherFn: (context: SystemPromptContext) => boolean): this {
+ this.variant = {
+ ...this.variant,
+ matcher: matcherFn,
+ }
+ return this
+ }
+
/**
* Set the base template (optional)
* If not provided, will be auto-generated from componentOrder
@@ -162,6 +174,9 @@ export class VariantBuilder {
if (!this.variant.description) {
throw new Error("Description is required")
}
+ if (!this.variant.matcher) {
+ throw new Error("Matcher function is required")
+ }
// Auto-generate baseTemplate from componentOrder if not provided
const baseTemplate = this.variant.baseTemplate || this.generateTemplateFromComponents(this.variant.componentOrder || [])
diff --git a/src/core/prompts/system-prompt/variants/xs/config.ts b/src/core/prompts/system-prompt/variants/xs/config.ts
index 1a913c7e..039910de 100644
--- a/src/core/prompts/system-prompt/variants/xs/config.ts
+++ b/src/core/prompts/system-prompt/variants/xs/config.ts
@@ -1,3 +1,4 @@
+import { isLocalModel } from "@utils/model-utils"
import { ModelFamily } from "@/shared/prompts"
import { ClineDefaultTool } from "@/shared/tools"
import { SystemPromptSection } from "../../templates/placeholders"
@@ -16,6 +17,11 @@ export const config = createVariant(ModelFamily.XS)
production: 1,
advanced: 1,
})
+ .matcher((context) => {
+ const providerInfo = context.providerInfo
+ // Match compact local models
+ return providerInfo.customPrompt === "compact" && isLocalModel(providerInfo)
+ })
.template(baseTemplate)
.components(
SystemPromptSection.AGENT_ROLE,
@@ -51,7 +57,7 @@ export const config = createVariant(ModelFamily.XS)
Object.assign(config.componentOverrides, xsComponentOverrides)
// Compile-time validation
-const validationResult = validateVariant({ ...config, id: "xs" }, { strict: true })
+const validationResult = validateVariant({ ...config, id: ModelFamily.XS }, { strict: true })
if (!validationResult.isValid) {
console.error("XS variant configuration validation failed:", validationResult.errors)
throw new Error(`Invalid XS variant configuration: ${validationResult.errors.join(", ")}`)
diff --git a/src/core/task/TaskState.ts b/src/core/task/TaskState.ts
index ff525137..fdb44ae0 100644
--- a/src/core/task/TaskState.ts
+++ b/src/core/task/TaskState.ts
@@ -11,8 +11,10 @@ export class TaskState {
// Content processing
currentStreamingContentIndex = 0
assistantMessageContent: AssistantMessageContent[] = []
- userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = []
+ userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolResultBlockParam)[] = []
userMessageContentReady = false
+ // Map of tool names to their tool_use_id for creating proper ToolResultBlockParam
+ toolUseIdMap: Map = new Map()
// Presentation locks
presentAssistantMessageLocked = false
diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts
index 41d1f722..6592c30e 100644
--- a/src/core/task/ToolExecutor.ts
+++ b/src/core/task/ToolExecutor.ts
@@ -22,6 +22,7 @@ import { MessageStateHandler } from "./message-state"
import { TaskState } from "./TaskState"
import { AutoApprove } from "./tools/autoApprove"
import { AccessMcpResourceHandler } from "./tools/handlers/AccessMcpResourceHandler"
+import { ApplyPatchHandler } from "./tools/handlers/ApplyPatchHandler"
import { AskFollowupQuestionToolHandler } from "./tools/handlers/AskFollowupQuestionToolHandler"
import { AttemptCompletionHandler } from "./tools/handlers/AttemptCompletionHandler"
import { BrowserToolHandler } from "./tools/handlers/BrowserToolHandler"
@@ -207,6 +208,7 @@ export class ToolExecutor {
this.coordinator.register(new CondenseHandler())
this.coordinator.register(new SummarizeTaskHandler(validator))
this.coordinator.register(new ReportBugHandler())
+ this.coordinator.register(new ApplyPatchHandler(validator))
}
/**
@@ -252,6 +254,7 @@ export class ToolExecutor {
this.taskState.didAlreadyUseTool = true
},
this.coordinator,
+ this.taskState.toolUseIdMap,
)
}
@@ -268,6 +271,9 @@ export class ToolExecutor {
* Execute a tool through the coordinator if it's registered
*/
private async execute(block: ToolUse): Promise {
+ // Note: MCP tool name transformation happens earlier in ToolUseHandler.getPartialToolUsesAsContent()
+ // The toolUseIdMap is updated at the point of transformation in index.ts
+
if (!this.coordinator.has(block.name)) {
return false // Tool not handled by coordinator
}
@@ -454,7 +460,8 @@ export class ToolExecutor {
} catch (error) {
executionSuccess = false
toolResult = formatResponse.toolError(`Tool execution failed: ${error}`)
- this.pushToolResult(toolResult, block)
+ // Don't push tool result here - let the outer catch block (handleError) handle it
+ // to avoid duplicate tool_result blocks
throw error
} finally {
// Run PostToolUse hook if enabled
diff --git a/src/core/task/focus-chain/index.ts b/src/core/task/focus-chain/index.ts
index 0c8073cb..05491498 100644
--- a/src/core/task/focus-chain/index.ts
+++ b/src/core/task/focus-chain/index.ts
@@ -14,6 +14,7 @@ import {
extractFocusChainListFromText,
getFocusChainFilePath,
} from "./file-utils"
+import { FocusChainPrompts } from "./prompts"
import { parseFocusChainListCounts } from "./utils"
export interface FocusChainDependencies {
@@ -139,71 +140,6 @@ export class FocusChainManager {
* @returns string - Formatted markdown instructions for focus chain list management, varies by context
*/
public generateFocusChainInstructions(): string {
- // Prompt for initial list creation
- const listInstructionsInitial = `\n
-# TODO LIST CREATION REQUIRED - ACT MODE ACTIVATED\n
-\n
-**You've just switched from PLAN MODE to ACT MODE!**\n
-\n
-** IMMEDIATE ACTION REQUIRED:**\n
-1. Create a comprehensive todo list in your NEXT tool call\n
-2. Use the task_progress parameter to provide the list\n
-3. Format each item using markdown checklist syntax:\n
- - [ ] For tasks to be done\n
- - [x] For any tasks already completed\n
-\n
-**Your todo list should include:**\n
- - All major implementation steps\n
- - Testing and validation tasks\n
- - Documentation updates if needed\n
- - Final verification steps\n
-\n
-**Example format:**\n\
- - [ ] Set up project structure\n
- - [ ] Implement core functionality\n
- - [ ] Add error handling\n-
- - [ ] Write tests\n
- - [ ] Test implementation\n
- - [ ] Document changes\n
-\n
-**Remember:** Keeping the todo list updated helps track progress and ensures nothing is missed.`
-
- // For when recommending but not requiring a list
- const listInstructionsRecommended = `\n
-1. Include the task_progress parameter in your next tool call\n
-2. Create a comprehensive checklist of all steps needed\n
-3. Use markdown format: - [ ] for incomplete, - [x] for complete\n
-\n
-**Benefits of creating a todo list now:**\n
- - Clear roadmap for implementation\n
- - Progress tracking throughout the task\n
- - Nothing gets forgotten or missed\n
- - Users can see, monitor, and edit the plan\n
-\n
-**Example structure:**\n\`\`\`\n
-- [ ] Analyze requirements\n
-- [ ] Set up necessary files\n
-- [ ] Implement main functionality\n
-- [ ] Handle edge cases\n
-- [ ] Test the implementation\n
-- [ ] Verify results\n\`\`\`\n
-\n
-Keeping the todo list updated helps track progress and ensures nothing is missed.`
-
- // Prompt for reminders to update the list periodically
- const listInstrunctionsReminder = `\n
-1. To create or update a todo list, include the task_progress parameter in the next tool call\n
-2. Review each item and update its status:\n
- - Mark completed items with: - [x]\n
- - Keep incomplete items as: - [ ]\n
- - Add new items if you discover additional steps\n
-3. Modify the list as needed:\n
- - Add any new steps you've discovered\n
- - Reorder if the sequence has changed\n
-4. Ensure the list accurately reflects the current state\n
-\n
-**Remember:** Keeping the todo list updated helps track progress and ensures nothing is missed.`
-
// If list exists already exists, we need to remind it to update rather than demand initialization
if (this.taskState.currentFocusChainChecklist) {
// Parse the current list for counts/stats
@@ -224,7 +160,7 @@ Keeping the todo list updated helps track progress and ensures nothing is missed
\n
${this.taskState.currentFocusChainChecklist}\n
${userHasUpdatedList}\n
- ${listInstrunctionsReminder}\n
+ ${FocusChainPrompts.reminder}\n
`
// If there are no user changes, proceed with reminders based on list progress
@@ -243,17 +179,9 @@ Keeping the todo list updated helps track progress and ensures nothing is missed
}
// Every item on the list has been completed. Hooray!
else if (completedItems === totalItems && totalItems > 0) {
- progressBasedMessageStub = `\n\n**🎉 EXCELLENT! All ${totalItems} items have been completed!**
-
-**Completed Items:**
-${this.taskState.currentFocusChainChecklist}
-
-**Next Steps:**
-- If the task is fully complete and meets all requirements, use attempt_completion
-- If you've discovered additional work that wasn't in the original scope (new features, improvements, edge cases, etc.), create a new task_progress list with those items
-- If there are related tasks or follow-up items the user might want, you can suggest them in a new checklist
-
-**Remember:** Only use attempt_completion if you're confident the task is truly finished. If there's any remaining work, create a new focus chain list to track it.`
+ progressBasedMessageStub = FocusChainPrompts.completed
+ .replace("{{totalItems}}", totalItems.toString())
+ .replace("{{currentFocusChainChecklist}}", this.taskState.currentFocusChainChecklist)
}
// Return with progress-based stub
@@ -262,39 +190,26 @@ ${this.taskState.currentFocusChainChecklist}
${listCurrentProgress}\n
${this.taskState.currentFocusChainChecklist}\n
\n
- ${listInstrunctionsReminder}\n
+ ${FocusChainPrompts.reminder}\n
${progressBasedMessageStub}\n
`
}
}
// When switching from Plan to Act, request that a new list be generated
else if (this.taskState.didRespondToPlanAskBySwitchingMode) {
- return `${listInstructionsInitial}`
+ return `${FocusChainPrompts.initial}`
}
// When in plan mode, lists are optional. TODO - May want to improve this soft prompt approach in a future version
else if (this.stateManager.getGlobalSettingsKey("mode") === "plan") {
- return `\n
-# Todo List (Optional - Plan Mode)\n
-\n
-While in PLAN MODE, if you've outlined concrete steps or requirements for the user, you may include a preliminary todo list using the task_progress parameter.\n
-Reminder on how to use the task_progress parameter:\n
-${listInstrunctionsReminder}`
+ return FocusChainPrompts.planModeReminder
} else {
// Check if we're early in the task
const isEarlyInTask = this.taskState.apiRequestCount < 10
if (isEarlyInTask) {
- return `\n
-# TODO LIST RECOMMENDED
-When starting a new task, it is recommended to create a todo list.
-\n
-${listInstructionsRecommended}\n`
+ return FocusChainPrompts.recommended
} else {
- return `\n
-# TODO LIST \n
-You've made ${this.taskState.apiRequestCount} API requests without a todo list. Consider creating one to track remaining work.\n
-\n
-${listInstrunctionsReminder}\n`
+ return FocusChainPrompts.apiRequestCount.replace("{{apiRequestCount}}", this.taskState.apiRequestCount.toString())
}
}
}
diff --git a/src/core/task/focus-chain/prompts.ts b/src/core/task/focus-chain/prompts.ts
new file mode 100644
index 00000000..58f11a99
--- /dev/null
+++ b/src/core/task/focus-chain/prompts.ts
@@ -0,0 +1,112 @@
+// Prompt for initial list creation
+const initial = `
+# TODO LIST CREATION REQUIRED - ACT MODE ACTIVATED
+
+**You've just switched from PLAN MODE to ACT MODE!**
+
+** IMMEDIATE ACTION REQUIRED:**
+1. Create a comprehensive todo list in your NEXT tool call
+2. Use the task_progress parameter to provide the list
+3. Format each item using markdown checklist syntax:
+ - [ ] For tasks to be done
+ - [x] For any tasks already completed
+
+**Your todo list should include:**
+ - All major implementation steps
+ - Testing and validation tasks
+ - Documentation updates if needed
+ - Final verification steps
+
+**Example format:**\
+ - [ ] Set up project structure
+ - [ ] Implement core functionality
+ - [ ] Add error handling
+ - [ ] Write tests
+ - [ ] Test implementation
+ - [ ] Document changes
+
+**Remember:** Keeping the todo list updated helps track progress and ensures nothing is missed.`
+
+// For when recommending but not requiring a list
+const listInstructionsRecommended = `
+1. Include the task_progress parameter in your next tool call
+2. Create a comprehensive checklist of all steps needed
+3. Use markdown format: - [ ] for incomplete, - [x] for complete
+
+**Benefits of creating a todo list now:**
+ - Clear roadmap for implementation
+ - Progress tracking throughout the task
+ - Nothing gets forgotten or missed
+ - Users can see, monitor, and edit the plan
+
+**Example structure:**\`\`\`
+- [ ] Analyze requirements
+- [ ] Set up necessary files
+- [ ] Implement main functionality
+- [ ] Handle edge cases
+- [ ] Test the implementation
+- [ ] Verify results\`\`\`
+
+Keeping the todo list updated helps track progress and ensures nothing is missed.`
+
+// Prompt for reminders to update the list periodically
+const reminder = `
+1. To create or update a todo list, include the task_progress parameter in the next tool call
+2. Review each item and update its status:
+ - Mark completed items with: - [x]
+ - Keep incomplete items as: - [ ]
+ - Add new items if you discover additional steps
+3. Modify the list as needed:
+ - Add any new steps you've discovered
+ - Reorder if the sequence has changed
+4. Ensure the list accurately reflects the current state
+
+**Remember:** Keeping the todo list updated helps track progress and ensures nothing is missed.`
+
+const completed = `
+
+**🎉 EXCELLENT! All {{totalItems}} items have been completed!**
+
+**Completed Items:**
+{{currentFocusChainChecklist}}
+
+**Next Steps:**
+- If the task is fully complete and meets all requirements, use attempt_completion
+- If you've discovered additional work that wasn't in the original scope (new features, improvements, edge cases, etc.), create a new task_progress list with those items
+- If there are related tasks or follow-up items the user might want, you can suggest them in a new checklist
+
+**Remember:** Only use attempt_completion if you're confident the task is truly finished. If there's any remaining work, create a new focus chain list to track it.`
+
+const planModeReminder = `
+# Todo List (Optional - Plan Mode)
+
+While in PLAN MODE, if you've outlined concrete steps or requirements for the user, you may include a preliminary todo list using the task_progress parameter.
+
+Reminder on how to use the task_progress parameter:
+
+${reminder}`
+
+const recommended = `
+# TODO LIST RECOMMENDED
+
+When starting a new task, it is recommended to create a todo list.
+
+${listInstructionsRecommended}
+`
+
+const apiRequestCount = `
+# TODO LIST
+
+You've made {{apiRequestCount}} API requests without a todo list. Consider creating one to track remaining work.
+
+${reminder}
+`
+
+export const FocusChainPrompts = {
+ initial,
+ reminder,
+ recommended,
+ planModeReminder,
+ completed,
+ apiRequestCount,
+}
diff --git a/src/core/task/index.ts b/src/core/task/index.ts
index 15d05742..7810042e 100644
--- a/src/core/task/index.ts
+++ b/src/core/task/index.ts
@@ -2,7 +2,7 @@ import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import { Anthropic } from "@anthropic-ai/sdk"
import { ApiHandler, ApiProviderInfo, buildApiHandler } from "@core/api"
import { ApiStream } from "@core/api/transform/stream"
-import { parseAssistantMessageV2 } from "@core/assistant-message"
+import { AssistantMessageContent, parseAssistantMessageV2 } from "@core/assistant-message"
import { ContextManager } from "@core/context/context-management/ContextManager"
import { checkContextWindowExceededError } from "@core/context/context-management/context-error-handling"
import { getContextWindowInfo } from "@core/context/context-management/context-window-utils"
@@ -63,6 +63,7 @@ import {
} from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages"
+import { CLINE_MCP_TOOL_IDENTIFIER } from "@shared/mcp"
import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message"
import { ClineDefaultTool } from "@shared/tools"
import { ClineAskResponse } from "@shared/WebviewMessage"
@@ -75,6 +76,7 @@ import pWaitFor from "p-wait-for"
import * as path from "path"
import { ulid } from "ulid"
import * as vscode from "vscode"
+import { ToolUseHandler } from "@/core/api/transform/tool-use-handler"
import type { SystemPromptContext } from "@/core/prompts/system-prompt"
import { getSystemPrompt } from "@/core/prompts/system-prompt"
import { HostProvider } from "@/hosts/host-provider"
@@ -151,6 +153,14 @@ export class Task {
public checkpointManager?: ICheckpointManager
private clineIgnoreController: ClineIgnoreController
private toolExecutor: ToolExecutor
+ /**
+ * Whether the task is using native tool calls.
+ * This is used to determine how we would format response.
+ * Example: We don't add noToolsUsed response when native tool call is used
+ * because of the expected format from the tool calls is different.
+ */
+ private useNativeToolCalls: boolean = false
+ private toolUseHandler: ToolUseHandler
private terminalExecutionMode: "vscodeTerminal" | "backgroundExec"
private activeBackgroundCommand?: {
@@ -264,6 +274,7 @@ export class Task {
this.browserSession = new BrowserSession(stateManager)
this.contextManager = new ContextManager()
this.diffViewProvider = HostProvider.get().createDiffViewProvider()
+ this.toolUseHandler = new ToolUseHandler()
this.cwd = cwd
this.stateManager = stateManager
this.workspaceManager = workspaceManager
@@ -917,6 +928,7 @@ export class Task {
// Now present the cline messages to the user and ask if they want to resume (NOTE: we ran into a bug before where the apiconversationhistory wouldn't be initialized when opening a old task, and it was because we were waiting for resume)
// This is important in case the user deletes messages without resuming the task first
const savedApiConversationHistory = await getSavedApiConversationHistory(this.taskId)
+
this.messageStateHandler.setApiConversationHistory(savedApiConversationHistory)
// load the context history state
@@ -1126,7 +1138,7 @@ export class Task {
nextUserContent = [
{
type: "text",
- text: formatResponse.noToolsUsed(),
+ text: formatResponse.noToolsUsed(this.useNativeToolCalls),
},
]
this.taskState.consecutiveMistakeCount++
@@ -1821,9 +1833,11 @@ export class Task {
workspaceRoots,
isSubagentsEnabledAndCliInstalled,
isCliSubagent,
+ enableNativeToolCalls: featureFlagsService.getNativeToolCallEnabled(),
}
- const systemPrompt = await getSystemPrompt(promptContext)
+ const { systemPrompt, tools } = await getSystemPrompt(promptContext)
+ this.useNativeToolCalls = !!tools?.length
const contextManagementMetadata = await this.contextManager.getNewContextMessagesAndMetadata(
this.messageStateHandler.getApiConversationHistory(),
@@ -1841,7 +1855,7 @@ export class Task {
// saves task history item which we use to keep track of conversation history deleted range
}
- const stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory)
+ const stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory, tools)
const iterator = stream[Symbol.asyncIterator]()
@@ -1857,9 +1871,7 @@ export class Task {
const clineError = ErrorService.get().toClineError(error, model.id, providerId)
// Capture provider failure telemetry using clineError
- // TODO: Move into errorService
ErrorService.get().logMessage(clineError.message)
- ErrorService.get().logException(clineError)
if (isContextWindowExceededError && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
await this.handleContextWindowExceededError()
@@ -2558,9 +2570,12 @@ export class Task {
this.taskState.presentAssistantMessageHasPendingUpdates = false
this.taskState.didAutomaticallyRetryFailedApiRequest = false
await this.diffViewProvider.reset()
+ this.toolUseHandler.reset()
+ this.taskState.toolUseIdMap.clear()
const stream = this.attemptApiRequest(previousApiReqIndex) // yields only if the first chunk is successful, otherwise will allow the user to retry the request (most likely due to rate limit error, which gets thrown on the first chunk)
- let assistantMessage = ""
+ let assistantMessage = "" // For UI display (includes XML)
+ let assistantTextOnly = "" // For API history (text only, no tool XML)
let reasoningMessage = ""
const reasoningDetails = []
const antThinkingContent: (Anthropic.Messages.RedactedThinkingBlock | Anthropic.Messages.ThinkingBlock)[] = []
@@ -2611,12 +2626,54 @@ export class Task {
data: chunk.data,
})
break
+ case "tool_calls": {
+ if (!chunk.tool_call) {
+ console.log("no tool call in chunk, skipping...", chunk)
+ break
+ }
+ // Accumulate tool use blocks in proper Anthropic format
+ this.toolUseHandler.processToolUseDelta({
+ id: chunk.tool_call.function?.id,
+ type: "tool_use",
+ name: chunk.tool_call.function?.name,
+ input: chunk.tool_call.function?.arguments,
+ })
+
+ // Extract and store tool_use_id for creating proper ToolResultBlockParam
+ if (chunk.tool_call.function?.id && chunk.tool_call.function?.name) {
+ this.taskState.toolUseIdMap.set(chunk.tool_call.function.name, chunk.tool_call.function.id)
+
+ // For MCP tools, also store the mapping with the transformed name
+ // since getPartialToolUsesAsContent() will transform the name to "use_mcp_tool"
+ if (chunk.tool_call.function.name.includes(CLINE_MCP_TOOL_IDENTIFIER)) {
+ this.taskState.toolUseIdMap.set(ClineDefaultTool.MCP_USE, chunk.tool_call.function.id)
+ }
+ }
+
+ const prevLength = this.taskState.assistantMessageContent.length
+
+ // Combine any text content with tool uses
+ const textContent = assistantTextOnly.trim()
+ const textBlocks: AssistantMessageContent[] = textContent
+ ? [{ type: "text", content: textContent, partial: false }]
+ : []
+ const toolBlocks = this.toolUseHandler.getPartialToolUsesAsContent()
+ assistantMessage += toolBlocks.map((block) => JSON.stringify(block)).join("\n")
+ this.taskState.assistantMessageContent = [...textBlocks, ...toolBlocks]
+
+ if (this.taskState.assistantMessageContent.length > prevLength) {
+ this.taskState.userMessageContentReady = false
+ }
+ this.presentAssistantMessage()
+ break
+ }
case "text": {
if (reasoningMessage && assistantMessage.length === 0) {
// complete reasoning message
await this.say("reasoning", reasoningMessage, undefined, undefined, false)
}
assistantMessage += chunk.text
+ assistantTextOnly += chunk.text // Accumulate text separately
// parse raw assistant message into content blocks
const prevLength = this.taskState.assistantMessageContent.length
@@ -2655,6 +2712,30 @@ export class Task {
break
}
}
+
+ // Finalize any remaining tool calls at the end of the stream
+ if (this.useNativeToolCalls) {
+ // For native tool calls, mark all pending tool uses as complete
+ const prevLength = this.taskState.assistantMessageContent.length
+
+ // Get finalized tool uses and mark them as complete
+ const textContent = assistantTextOnly.trim()
+ const textBlocks: AssistantMessageContent[] = textContent
+ ? [{ type: "text", content: textContent, partial: false }]
+ : []
+
+ // Get all finalized tool uses and mark as complete
+ const toolBlocks = this.toolUseHandler
+ .getPartialToolUsesAsContent()
+ .map((block) => ({ ...block, partial: false }))
+
+ this.taskState.assistantMessageContent = [...textBlocks, ...toolBlocks]
+
+ if (this.taskState.assistantMessageContent.length > prevLength) {
+ this.taskState.userMessageContentReady = false
+ }
+ this.presentAssistantMessage()
+ }
} catch (error) {
// abandoned happens when extension is no longer waiting for the cline instance to finish aborting (error is thrown here when any function in the for loop throws due to this.abort)
if (!this.taskState.abandoned) {
@@ -2769,7 +2850,7 @@ export class Task {
// now add to apiconversationhistory
// need to save assistant responses to file before proceeding to tool use since user can exit at any moment and we wouldn't be able to save the assistant's response
let didEndLoop = false
- if (assistantMessage.length > 0) {
+ if (assistantMessage.length > 0 || this.useNativeToolCalls) {
telemetryService.captureConversationTurnEvent(this.ulid, providerId, model.id, "assistant", {
tokensIn: inputTokens,
tokensOut: outputTokens,
@@ -2778,23 +2859,41 @@ export class Task {
totalCost,
})
+ // Get finalized tool use blocks from the handler
+ const toolUseBlocks = this.toolUseHandler.getAllFinalizedToolUses()
+
+ // Build content array with thinking blocks, text (if any), and tool use blocks
+ const assistantContent: Array<
+ | Anthropic.Messages.RedactedThinkingBlock
+ | Anthropic.Messages.ThinkingBlock
+ | Anthropic.Messages.TextBlockParam
+ | Anthropic.ToolUseBlockParam
+ > = [
+ // This is critical for maintaining the model's reasoning flow and conversation integrity.
+ // "When providing thinking blocks, the entire sequence of consecutive thinking blocks must match the outputs generated by the model during the original request; you cannot rearrange or modify the sequence of these blocks." The signature_delta is used to verify that the thinking was generated by Claude, and the thinking blocks will be ignored if it's incorrect or missing.
+ // https://docs.claude.com/en/docs/build-with-claude/extended-thinking#preserving-thinking-blocks
+ ...antThinkingContent,
+ ]
+
+ // Only add text block if there's actual text (not just tool XML)
+ if (assistantTextOnly.trim().length > 0) {
+ assistantContent.push({
+ type: "text",
+ text: assistantTextOnly,
+ // reasoning_details only exists for cline/openrouter providers
+ // @ts-ignore-next-line
+ reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined,
+ })
+ }
+
+ // Append tool use blocks if any exist
+ if (toolUseBlocks.length > 0) {
+ assistantContent.push(...toolUseBlocks)
+ }
+
await this.messageStateHandler.addToApiConversationHistory({
role: "assistant",
- content: [
- // This is critical for maintaining the model’s reasoning flow and conversation integrity.
- // "When providing thinking blocks, the entire sequence of consecutive thinking blocks must match the outputs generated by the model during the original request; you cannot rearrange or modify the sequence of these blocks." The signature_delta is used to verify that the thinking was generated by Claude, and the thinking blocks will be ignored if it's incorrect or missing.
- // https://docs.claude.com/en/docs/build-with-claude/extended-thinking#preserving-thinking-blocks
- ...antThinkingContent,
- {
- type: "text",
- text: assistantMessage,
- // reasoning_details only exists for cline/openrouter providers
- // @ts-ignore-next-line
- reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined,
- },
- ] as Array<
- Anthropic.Messages.RedactedThinkingBlock | Anthropic.Messages.ThinkingBlock | Anthropic.Messages.TextBlock
- >,
+ content: assistantContent,
})
// NOTE: this comment is here for future reference - this was a workaround for userMessageContent not getting set to true. It was due to it not recursively calling for partial blocks when didRejectTool, so it would get stuck waiting for a partial block to complete before it could continue.
@@ -2814,7 +2913,7 @@ export class Task {
// normal request where tool use is required
this.taskState.userMessageContent.push({
type: "text",
- text: formatResponse.noToolsUsed(),
+ text: formatResponse.noToolsUsed(this.useNativeToolCalls),
})
this.taskState.consecutiveMistakeCount++
}
@@ -2983,13 +3082,15 @@ export class Task {
clinerulesError = await ensureLocalClineDirExists(this.cwd, GlobalFileNames.clineRules)
}
- // Add focu chain list instructions if needed
+ // Add focus chain list instructions if needed
if (!useCompactPrompt && this.FocusChainManager?.shouldIncludeFocusChainInstructions()) {
const focusChainInstructions = this.FocusChainManager.generateFocusChainInstructions()
- processedUserContent.push({
- type: "text",
- text: focusChainInstructions,
- })
+ if (focusChainInstructions.trim()) {
+ processedUserContent.push({
+ type: "text",
+ text: focusChainInstructions,
+ })
+ }
this.taskState.apiRequestsSinceLastTodoUpdate = 0
this.taskState.todoListWasUpdatedByUser = false
diff --git a/src/core/task/tools/ToolExecutorCoordinator.ts b/src/core/task/tools/ToolExecutorCoordinator.ts
index 910fff62..2be30fa7 100644
--- a/src/core/task/tools/ToolExecutorCoordinator.ts
+++ b/src/core/task/tools/ToolExecutorCoordinator.ts
@@ -1,4 +1,5 @@
import type { ToolUse } from "@core/assistant-message"
+import { CLINE_MCP_TOOL_IDENTIFIER } from "@/shared/mcp"
import { ClineDefaultTool } from "@/shared/tools"
import type { ToolResponse } from "../index"
import type { TaskConfig } from "./types/TaskConfig"
@@ -66,6 +67,10 @@ export class ToolExecutorCoordinator {
* Get a handler for the given tool name
*/
getHandler(toolName: string): IToolHandler | undefined {
+ // HACK: Normalize MCP tool names to the standard handler
+ if (toolName.includes(CLINE_MCP_TOOL_IDENTIFIER)) {
+ toolName = ClineDefaultTool.MCP_USE
+ }
return this.handlers.get(toolName)
}
diff --git a/src/core/task/tools/handlers/ApplyPatchHandler.ts b/src/core/task/tools/handlers/ApplyPatchHandler.ts
new file mode 100644
index 00000000..45bdad4d
--- /dev/null
+++ b/src/core/task/tools/handlers/ApplyPatchHandler.ts
@@ -0,0 +1,1201 @@
+import { readFile } from "node:fs/promises"
+import type { ToolUse } from "@core/assistant-message"
+import { resolveWorkspacePath } from "@core/workspace"
+import { processFilesIntoText } from "@integrations/misc/extract-text"
+import { ClineSayTool } from "@shared/ExtensionMessage"
+import { fileExistsAtPath } from "@utils/fs"
+import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider"
+import { telemetryService } from "@/services/telemetry"
+import { ClineDefaultTool } from "@/shared/tools"
+import { isLocatedInWorkspace } from "@/utils/path"
+import type { ToolResponse } from "../../index"
+import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils"
+import type { IFullyManagedTool } from "../ToolExecutorCoordinator"
+import type { ToolValidator } from "../ToolValidator"
+import type { TaskConfig } from "../types/TaskConfig"
+import type { StronglyTypedUIHelpers } from "../types/UIHelpers"
+import { ToolResultUtils } from "../utils/ToolResultUtils"
+
+// Domain types
+enum ActionType {
+ ADD = "add",
+ DELETE = "delete",
+ UPDATE = "update",
+}
+
+interface FileChange {
+ type: ActionType
+ oldContent?: string
+ newContent?: string
+ movePath?: string
+}
+
+interface Commit {
+ changes: Record
+}
+
+interface Chunk {
+ origIndex: number
+ delLines: string[]
+ insLines: string[]
+}
+
+interface PatchAction {
+ type: ActionType
+ newFile?: string
+ chunks: Chunk[]
+ movePath?: string
+}
+
+interface Patch {
+ actions: Record
+}
+
+class DiffError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = "DiffError"
+ }
+}
+
+// Patch format constants
+const PATCH_MARKERS = {
+ BEGIN: "*** Begin Patch",
+ END: "*** End Patch",
+ ADD: "*** Add File: ",
+ UPDATE: "*** Update File: ",
+ DELETE: "*** Delete File: ",
+ MOVE: "*** Move to: ",
+ SECTION: "@@",
+ END_FILE: "*** End of File",
+} as const
+
+const BASH_WRAPPERS = ["%%bash", "apply_patch", "EOF", "```"] as const
+
+// Helper functions for path resolution and validation
+class PathResolver {
+ constructor(
+ private config: TaskConfig,
+ private validator: ToolValidator,
+ ) {}
+
+ resolve(filePath: string, caller: string): { absolutePath: string; resolvedPath: string } | undefined {
+ try {
+ const pathResult = resolveWorkspacePath(this.config, filePath, caller)
+ return typeof pathResult === "string"
+ ? { absolutePath: pathResult, resolvedPath: filePath }
+ : { absolutePath: pathResult.absolutePath, resolvedPath: pathResult.resolvedPath }
+ } catch {
+ return undefined
+ }
+ }
+
+ validate(resolvedPath: string): { ok: boolean; error?: string } {
+ return this.validator.checkClineIgnorePath(resolvedPath)
+ }
+
+ async resolveAndValidate(
+ filePath: string,
+ caller: string,
+ ): Promise<{ absolutePath: string; resolvedPath: string } | undefined> {
+ const resolution = this.resolve(filePath, caller)
+ if (!resolution) {
+ return undefined
+ }
+
+ const validation = this.validate(resolution.resolvedPath)
+ if (!validation.ok) {
+ return undefined
+ }
+
+ return resolution
+ }
+}
+
+// Helper class for provider operations
+class ProviderOperations {
+ constructor(private provider: DiffViewProvider) {}
+
+ async createFile(path: string, content: string): Promise<{ finalContent?: string }> {
+ this.provider.editType = "create"
+ await this.provider.open(path)
+ await this.provider.update(content, true)
+ const result = await this.provider.saveChanges()
+ await this.provider.reset()
+ return result
+ }
+
+ async modifyFile(path: string, content: string): Promise<{ finalContent?: string }> {
+ this.provider.editType = "modify"
+ await this.provider.open(path)
+ await this.provider.update(content, true)
+ const result = await this.provider.saveChanges()
+ await this.provider.reset()
+ return result
+ }
+
+ async deleteFile(path: string): Promise {
+ this.provider.editType = "modify"
+ await this.provider.open(path)
+ await this.provider.revertChanges()
+ }
+
+ async moveFile(oldPath: string, newPath: string, content: string): Promise<{ finalContent?: string }> {
+ const result = await this.createFile(newPath, content)
+ await this.deleteFile(oldPath)
+ return result
+ }
+}
+
+export class ApplyPatchHandler implements IFullyManagedTool {
+ readonly name = ClineDefaultTool.APPLY_PATCH
+ private appliedCommit?: Commit
+ private config?: TaskConfig
+ private pathResolver?: PathResolver
+ private providerOps?: ProviderOperations
+ private partialPreviewState?: {
+ originalFiles: Record
+ currentPreviewPath?: string
+ }
+
+ constructor(private validator: ToolValidator) {}
+
+ private initializeHelpers(config: TaskConfig): void {
+ if (!this.pathResolver || this.config !== config) {
+ this.pathResolver = new PathResolver(config, this.validator)
+ }
+ if (!this.providerOps) {
+ this.providerOps = new ProviderOperations(config.services.diffViewProvider)
+ }
+ }
+
+ getDescription(block: ToolUse): string {
+ return `[${block.name} for patch application]`
+ }
+
+ async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise {
+ const rawInput = block.params.input
+ if (!rawInput) {
+ return
+ }
+
+ try {
+ const allFiles = this.extractAllFiles(rawInput)
+ if (allFiles.length === 0) {
+ return
+ }
+
+ const autoApproveCheck = async (path: string, message: ClineSayTool) => {
+ const blockName = message.tool === "newFileCreated" ? ClineDefaultTool.FILE_NEW : ClineDefaultTool.FILE_EDIT
+ const shouldAutoApprove = await uiHelpers.shouldAutoApproveToolWithPath(blockName, path)
+ if (shouldAutoApprove) {
+ await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool")
+ await uiHelpers.say("tool", JSON.stringify(message), undefined, undefined, block.partial)
+ } else {
+ await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool")
+ await uiHelpers.ask("tool", JSON.stringify(message), block.partial).catch(() => {})
+ }
+ }
+
+ const lines = this.stripBashWrapper(rawInput.split("\n"))
+ const operations = {
+ add: this.extractFilesFromLines(lines, PATCH_MARKERS.ADD, rawInput),
+ update: this.extractFilesFromLines(lines, PATCH_MARKERS.UPDATE, rawInput),
+ delete: this.extractFilesFromLines(lines, PATCH_MARKERS.DELETE, rawInput),
+ }
+
+ if (operations.add.length > 0) {
+ for (const file of operations.add) {
+ const operationIsLocatedInWorkspace = await isLocatedInWorkspace(file)
+ await autoApproveCheck(file, {
+ tool: "newFileCreated",
+ path: file,
+ operationIsLocatedInWorkspace,
+ })
+ }
+ }
+ if (operations.update.length > 0) {
+ for (const file of operations.update) {
+ const operationIsLocatedInWorkspace = await isLocatedInWorkspace(file)
+ await autoApproveCheck(file, {
+ tool: "editedExistingFile",
+ path: file,
+ operationIsLocatedInWorkspace,
+ })
+ }
+ }
+ if (operations.delete.length > 0) {
+ for (const file of operations.delete) {
+ const operationIsLocatedInWorkspace = await isLocatedInWorkspace(file)
+ await autoApproveCheck(file, {
+ tool: "editedExistingFile",
+ path: file,
+ operationIsLocatedInWorkspace,
+ })
+ }
+ }
+
+ await this.previewPatchStream(rawInput, uiHelpers).catch(() => {})
+ } catch {
+ // Wait for more data if parsing fails
+ }
+ }
+
+ private ensurePartialPreviewState(): { originalFiles: Record; currentPreviewPath?: string } {
+ if (!this.partialPreviewState) {
+ this.partialPreviewState = { originalFiles: {} }
+ }
+ return this.partialPreviewState
+ }
+
+ private async getOriginalFileContentForPreview(
+ pathKey: string,
+ resolution: { absolutePath: string; resolvedPath: string },
+ ): Promise {
+ const state = this.ensurePartialPreviewState()
+ if (state.originalFiles[pathKey] !== undefined) {
+ return state.originalFiles[pathKey]
+ }
+
+ const validation = this.validator.checkClineIgnorePath(resolution.resolvedPath)
+ if (!validation.ok) {
+ return undefined
+ }
+
+ try {
+ if (!(await fileExistsAtPath(resolution.absolutePath))) {
+ return undefined
+ }
+ const fileContent = await readFile(resolution.absolutePath, "utf8")
+ const normalizedContent = fileContent.replace(/\r\n/g, "\n")
+ state.originalFiles[pathKey] = normalizedContent
+ return normalizedContent
+ } catch {
+ return undefined
+ }
+ }
+
+ private async previewPatchStream(rawInput: string, uiHelpers: StronglyTypedUIHelpers): Promise {
+ const config = uiHelpers.getConfig()
+ const provider = config.services.diffViewProvider
+ this.initializeHelpers(config)
+
+ // OPTIMIZATION: Instead of full parsing + chunk application on every streaming chunk,
+ // we do lightweight incremental extraction of content for real-time preview.
+ // Full parsing happens once in execute().
+
+ const state = this.ensurePartialPreviewState()
+ const lines = this.stripBashWrapper(rawInput.split("\n"))
+
+ // Extract the first operation path and type incrementally
+ let targetPath: string | undefined
+ let actionType: ActionType | undefined
+ let contentStartIndex = -1
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]
+
+ if (line.startsWith(PATCH_MARKERS.ADD)) {
+ targetPath = line.substring(PATCH_MARKERS.ADD.length).trim()
+ actionType = ActionType.ADD
+ contentStartIndex = i + 1
+ break
+ } else if (line.startsWith(PATCH_MARKERS.UPDATE)) {
+ targetPath = line.substring(PATCH_MARKERS.UPDATE.length).trim()
+ actionType = ActionType.UPDATE
+ contentStartIndex = i + 1
+ break
+ } else if (line.startsWith(PATCH_MARKERS.DELETE)) {
+ targetPath = line.substring(PATCH_MARKERS.DELETE.length).trim()
+ actionType = ActionType.DELETE
+ contentStartIndex = i + 1
+ break
+ }
+ }
+
+ // Skip if we haven't parsed a valid path yet
+ if (!targetPath || targetPath.length === 0 || targetPath.includes("***")) {
+ return
+ }
+
+ // Check for move/rename marker
+ let movePath: string | undefined
+ if (actionType === ActionType.UPDATE && contentStartIndex >= 0) {
+ const nextLine = lines[contentStartIndex]
+ if (nextLine?.startsWith(PATCH_MARKERS.MOVE)) {
+ movePath = nextLine.substring(PATCH_MARKERS.MOVE.length).trim()
+ contentStartIndex++
+ }
+ }
+
+ // For ADD operations, ensure we have actual content before proceeding
+ if (actionType === ActionType.ADD) {
+ if (contentStartIndex < 0 || contentStartIndex >= lines.length) {
+ return
+ }
+ const contentLines = lines.slice(contentStartIndex)
+ if (contentLines.length === 0 || (contentLines.length === 1 && contentLines[0] === "")) {
+ return // No content yet, don't create the file
+ }
+ }
+
+ const finalPath = movePath || targetPath
+ const targetResolution = await this.pathResolver!.resolveAndValidate(finalPath, "ApplyPatchHandler.previewPatch.target")
+ if (!targetResolution) {
+ return
+ }
+
+ const requiresOpen =
+ !provider.isEditing || state.currentPreviewPath !== targetResolution.resolvedPath || provider.editType === undefined
+
+ const needsCreateEditor = actionType === ActionType.ADD || (actionType === ActionType.UPDATE && !!movePath)
+
+ if (requiresOpen) {
+ provider.editType = needsCreateEditor ? "create" : "modify"
+ await provider.open(targetResolution.absolutePath, { displayPath: targetResolution.resolvedPath })
+ state.currentPreviewPath = targetResolution.resolvedPath
+ }
+
+ let newContent: string | undefined
+
+ switch (actionType) {
+ case ActionType.ADD: {
+ // For ADD: stream the raw content directly (lines after the header)
+ // We've already validated content exists above
+ const contentLines = lines.slice(contentStartIndex)
+ newContent = contentLines.join("\n")
+ break
+ }
+ case ActionType.UPDATE: {
+ // For UPDATE: we need original content, but we can stream incremental chunk application
+ // To avoid re-parsing, we'll use cached original content from state
+ const sourceResolution = await this.pathResolver!.resolveAndValidate(
+ targetPath,
+ "ApplyPatchHandler.previewPatch.source",
+ )
+ if (!sourceResolution) {
+ return
+ }
+
+ const originalContent = await this.getOriginalFileContentForPreview(targetPath, sourceResolution)
+ if (originalContent === undefined) {
+ return
+ }
+
+ // Extract chunks incrementally without full parser
+ const chunks = this.extractChunksIncremental(lines, contentStartIndex)
+ if (chunks.length === 0) {
+ return
+ }
+
+ try {
+ newContent = this.applyChunks(originalContent, chunks, targetPath)
+ } catch {
+ return
+ }
+
+ provider.editType = movePath ? "create" : "modify"
+ break
+ }
+ case ActionType.DELETE:
+ newContent = ""
+ provider.editType = "modify"
+ break
+ default:
+ return
+ }
+
+ if (newContent === undefined) {
+ return
+ }
+
+ try {
+ await provider.update(newContent, false)
+ } catch {
+ // Ignore streaming errors - final execute will handle them
+ }
+ }
+
+ // Lightweight incremental chunk extraction for streaming preview
+ // This avoids the full parser state machine that happens in parsePatch()
+ private extractChunksIncremental(lines: string[], startIndex: number): Chunk[] {
+ if (startIndex < 0 || startIndex >= lines.length) {
+ return []
+ }
+
+ const chunks: Chunk[] = []
+ let currentChunk: Chunk | null = null
+
+ for (let i = startIndex; i < lines.length; i++) {
+ const line = lines[i]
+
+ // Section marker indicates a new chunk
+ if (line.startsWith(PATCH_MARKERS.SECTION)) {
+ // Save previous chunk if exists
+ if (currentChunk !== null) {
+ chunks.push(currentChunk)
+ }
+
+ // Parse section header: *** Section:
+ const match = line.match(/\*\*\* Section: (\d+)/)
+ const origIndex = match ? Number.parseInt(match[1], 10) : 0
+
+ currentChunk = {
+ origIndex,
+ delLines: [],
+ insLines: [],
+ }
+ } else if (currentChunk !== null) {
+ // Process diff lines
+ if (line.startsWith("-")) {
+ currentChunk.delLines.push(line.substring(1))
+ } else if (line.startsWith("+")) {
+ currentChunk.insLines.push(line.substring(1))
+ } else if (line.startsWith(" ")) {
+ // Context line - add to both
+ const contextLine = line.substring(1)
+ currentChunk.delLines.push(contextLine)
+ currentChunk.insLines.push(contextLine)
+ }
+ // Stop at next operation marker
+ else if (
+ line.startsWith(PATCH_MARKERS.ADD) ||
+ line.startsWith(PATCH_MARKERS.UPDATE) ||
+ line.startsWith(PATCH_MARKERS.DELETE) ||
+ line === PATCH_MARKERS.END
+ ) {
+ break
+ }
+ }
+ }
+
+ // Save final chunk
+ if (currentChunk !== null) {
+ chunks.push(currentChunk)
+ }
+
+ return chunks
+ }
+
+ async execute(config: TaskConfig, block: ToolUse): Promise {
+ const provider = config.services.diffViewProvider
+ const rawInput = block.params.input
+
+ if (!rawInput) {
+ config.taskState.consecutiveMistakeCount++
+ return await config.callbacks.sayAndCreateMissingParamError(block.name, "input")
+ }
+
+ config.taskState.consecutiveMistakeCount = 0
+ this.initializeHelpers(config)
+
+ if (provider.isEditing) {
+ try {
+ await provider.reset()
+ } catch {
+ // Ignore reset errors - we will attempt to continue with a fresh state
+ }
+ }
+ this.partialPreviewState = undefined
+
+ try {
+ const patch = this.parsePatch(rawInput)
+ const allFiles = this.extractAllFiles(rawInput)
+
+ if (allFiles.length === 0) {
+ throw new DiffError(
+ "No files found in patch - patch must contain at least one *** Update File:, *** Delete File:, or *** Add File: directive",
+ )
+ }
+
+ // Load existing files for update/delete operations
+ const filesToLoad = this.extractFilesForOperations(rawInput, [PATCH_MARKERS.UPDATE, PATCH_MARKERS.DELETE])
+ const currentFiles = await this.loadFiles(config, filesToLoad)
+
+ // Convert patch to commit
+ const commit = this.patchToCommit(patch, currentFiles)
+
+ // Store state for potential revert
+ this.appliedCommit = commit
+ this.config = config
+
+ // Apply the commit and get results
+ const applyResults = await this.applyCommit(commit)
+
+ // Generate summary
+ const changedFiles = Object.keys(commit.changes)
+ const messages = await this.generateChangeSummary(commit.changes)
+
+ const finalResponses = []
+
+ for (const message of messages) {
+ // Handle approval flow
+ const approved = await this.handleApproval(config, block, message, changedFiles[0] || "")
+ if (!approved) {
+ // Revert all changes on rejection
+ await this.revertChanges()
+ return "The user denied this patch operation."
+ }
+
+ // Track file edits
+ for (const filePath of changedFiles) {
+ config.services.fileContextTracker.markFileAsEditedByCline(filePath)
+ await config.services.fileContextTracker.trackFileContext(filePath, "cline_edited")
+ }
+
+ config.taskState.didEditFile = true
+ finalResponses.push(message.path)
+ }
+
+ // Clear state after successful application
+ this.appliedCommit = undefined
+ this.config = undefined
+
+ // Build detailed response with file contents
+ const responseLines = ["Successfully applied patch to the following files:"]
+ for (const [path, result] of Object.entries(applyResults)) {
+ if (result.deleted) {
+ responseLines.push(`\n${path}: [deleted]`)
+ } else if (result.finalContent !== undefined) {
+ responseLines.push(`\n${path}:\n${result.finalContent}`)
+ }
+ }
+
+ return responseLines.join("\n")
+ } catch (error) {
+ console.error("Error applying patch:", error)
+ // Revert any changes that may have been applied before the error
+
+ await provider.revertChanges()
+ await provider.reset()
+
+ // Don't manually push tool result here - let the coordinator handle it
+ // Otherwise we get duplicate tool_result blocks in the message
+ throw error
+ }
+ }
+
+ // Core parsing logic
+ private parsePatch(text: string, allowIncompleteSentinels = false): Patch {
+ const lines = this.preprocessLines(text, allowIncompleteSentinels)
+ const parser = new PatchParser(lines)
+ return parser.parse()
+ }
+
+ private preprocessLines(text: string, allowIncompleteSentinels: boolean): string[] {
+ let lines = text.split("\n").map((line) => line.replace(/\r$/, ""))
+ lines = this.stripBashWrapper(lines)
+
+ const hasBegin = lines.length > 0 && lines[0].startsWith(PATCH_MARKERS.BEGIN)
+ const hasEnd = lines.length > 0 && lines[lines.length - 1] === PATCH_MARKERS.END
+
+ if (!hasBegin && !hasEnd) {
+ return [PATCH_MARKERS.BEGIN, ...lines, PATCH_MARKERS.END]
+ }
+ if (hasBegin && hasEnd) {
+ return lines
+ }
+
+ if (allowIncompleteSentinels) {
+ if (!hasBegin) {
+ lines = [PATCH_MARKERS.BEGIN, ...lines]
+ }
+ if (!hasEnd) {
+ lines = [...lines, PATCH_MARKERS.END]
+ }
+ return lines
+ }
+
+ throw new DiffError("Invalid patch text - incomplete sentinels (missing either Begin or End)")
+ }
+
+ private stripBashWrapper(lines: string[]): string[] {
+ const result: string[] = []
+ let insidePatch = false
+ let foundBegin = false
+ let foundContent = false
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]
+ // Skip bash wrappers outside patch
+ if (!insidePatch && BASH_WRAPPERS.some((wrapper) => line.startsWith(wrapper))) {
+ continue
+ }
+
+ if (line.startsWith(PATCH_MARKERS.BEGIN)) {
+ insidePatch = true
+ foundBegin = true
+ result.push(line)
+ continue
+ }
+
+ if (line === PATCH_MARKERS.END) {
+ insidePatch = false
+ result.push(line)
+ continue
+ }
+
+ const isPatchContent = this.isPatchLine(line)
+ // Makes sure the next line after patch content is ready,
+ // else we may cut off important context lines
+ if (isPatchContent && i !== lines.length - 1) {
+ foundContent = true
+ }
+
+ if (insidePatch || (!foundBegin && isPatchContent) || (line === "" && foundContent)) {
+ result.push(line)
+ }
+ }
+
+ // Trim trailing empty lines that may remain after stripping bash wrappers
+ while (result.length > 0 && result[result.length - 1] === "") {
+ result.pop()
+ }
+
+ return !foundBegin && !foundContent ? lines : result
+ }
+
+ private isPatchLine(line: string): boolean {
+ return (
+ line.startsWith(PATCH_MARKERS.ADD) ||
+ line.startsWith(PATCH_MARKERS.UPDATE) ||
+ line.startsWith(PATCH_MARKERS.DELETE) ||
+ line.startsWith(PATCH_MARKERS.MOVE) ||
+ line.startsWith(PATCH_MARKERS.SECTION) ||
+ line.startsWith("+") ||
+ line.startsWith("-") ||
+ line.startsWith(" ") ||
+ line === "***"
+ )
+ }
+
+ // File extraction utilities
+ private extractFilesForOperations(text: string, markers: readonly string[]): string[] {
+ const lines = this.stripBashWrapper(text.split("\n"))
+ const files: string[] = []
+
+ for (const line of lines) {
+ for (const marker of markers) {
+ if (line.startsWith(marker)) {
+ files.push(line.substring(marker.length).trim())
+ break
+ }
+ }
+ }
+
+ return files
+ }
+
+ private extractAllFiles(text: string): string[] {
+ return this.extractFilesForOperations(text, [PATCH_MARKERS.ADD, PATCH_MARKERS.UPDATE, PATCH_MARKERS.DELETE])
+ }
+
+ private extractFilesFromLines(lines: string[], marker: string, rawInput?: string): string[] {
+ const results: string[] = []
+
+ // Check if the raw input ends with a newline
+ // If it doesn't, the last line is incomplete and should be ignored
+ const endsWithNewline = rawInput ? rawInput.endsWith("\n") : true
+ const maxIndex = endsWithNewline ? lines.length : lines.length - 1
+
+ for (let i = 0; i < maxIndex; i++) {
+ const line = lines[i]
+ if (line.startsWith(marker)) {
+ const path = line.substring(marker.length).trim()
+
+ // Filter out incomplete paths
+ if (path.length === 0 || path.includes("***")) {
+ continue
+ }
+
+ // For Add File operations, ensure the next line exists and is not empty
+ if (marker === PATCH_MARKERS.ADD) {
+ const nextLineIndex = i + 1
+ if (nextLineIndex >= lines.length) {
+ continue // No next line yet
+ }
+ const nextLine = lines[nextLineIndex]
+ if (nextLine === "") {
+ continue // Next line is empty, wait for content
+ }
+ }
+
+ results.push(path)
+ }
+ }
+
+ return results
+ }
+
+ // File operations
+ private async loadFiles(config: TaskConfig, filePaths: string[]): Promise> {
+ const files: Record = {}
+
+ for (const filePath of filePaths) {
+ const pathResult = resolveWorkspacePath(config, filePath, "ApplyPatchHandler.loadFiles")
+ const absolutePath = typeof pathResult === "string" ? pathResult : pathResult.absolutePath
+ const resolvedPath = typeof pathResult === "string" ? filePath : pathResult.resolvedPath
+
+ const accessValidation = this.validator.checkClineIgnorePath(resolvedPath)
+ if (!accessValidation.ok) {
+ await config.callbacks.say("clineignore_error", resolvedPath)
+ // Don't manually push tool result here - let the coordinator handle it via the thrown error
+ // to avoid duplicate tool_result blocks
+ throw new DiffError(`Access denied: ${resolvedPath}`)
+ }
+
+ if (!(await fileExistsAtPath(absolutePath))) {
+ throw new DiffError(`File not found: ${filePath}`)
+ }
+
+ // Read directly from disk to avoid saving any preview changes that may be in the dirty document
+ const fileContent = await readFile(absolutePath, "utf8")
+ const normalizedContent = fileContent.replace(/\r\n/g, "\n")
+ files[filePath] = normalizedContent
+ }
+
+ return files
+ }
+
+ private patchToCommit(patch: Patch, originalFiles: Record): Commit {
+ const changes: Record = {}
+
+ for (const [path, action] of Object.entries(patch.actions)) {
+ switch (action.type) {
+ case ActionType.DELETE:
+ changes[path] = { type: ActionType.DELETE, oldContent: originalFiles[path] }
+ break
+ case ActionType.ADD:
+ if (!action.newFile) {
+ throw new DiffError("ADD action without file content")
+ }
+ changes[path] = { type: ActionType.ADD, newContent: action.newFile }
+ break
+ case ActionType.UPDATE:
+ changes[path] = {
+ type: ActionType.UPDATE,
+ oldContent: originalFiles[path],
+ newContent: this.applyChunks(originalFiles[path], action.chunks, path),
+ movePath: action.movePath,
+ }
+ break
+ }
+ }
+
+ return { changes }
+ }
+
+ private applyChunks(content: string, chunks: Chunk[], path: string): string {
+ // Preserve whether the original content ends with a newline
+ const endsWithNewline = content.endsWith("\n")
+ const lines = content.split("\n")
+ const result: string[] = []
+ let currentIndex = 0
+
+ for (const chunk of chunks) {
+ if (chunk.origIndex > lines.length) {
+ throw new DiffError(`${path}: chunk.origIndex ${chunk.origIndex} exceeds file length`)
+ }
+ if (currentIndex > chunk.origIndex) {
+ throw new DiffError(`${path}: overlapping chunks at ${currentIndex} > ${chunk.origIndex}`)
+ }
+
+ result.push(...lines.slice(currentIndex, chunk.origIndex))
+ result.push(...chunk.insLines)
+ currentIndex = chunk.origIndex + chunk.delLines.length
+ }
+
+ result.push(...lines.slice(currentIndex))
+ const joined = result.join("\n")
+
+ // Restore the original trailing newline behavior
+ // When split() encounters a trailing newline, it creates an empty string at the end
+ // So we need to preserve this behavior when joining back
+ return endsWithNewline && !joined.endsWith("\n") ? joined + "\n" : joined
+ }
+
+ private async applyCommit(commit: Commit): Promise> {
+ const ops = this.providerOps!
+ const results: Record = {}
+
+ for (const [path, change] of Object.entries(commit.changes)) {
+ switch (change.type) {
+ case ActionType.DELETE:
+ await ops.deleteFile(path)
+ results[path] = { deleted: true }
+ break
+ case ActionType.ADD:
+ if (!change.newContent) {
+ throw new DiffError(`Cannot create ${path} with no content`)
+ }
+ const addResult = await ops.createFile(path, change.newContent)
+ results[path] = { finalContent: addResult.finalContent }
+ break
+ case ActionType.UPDATE:
+ if (!change.newContent) {
+ throw new DiffError(`UPDATE change for ${path} has no new content`)
+ }
+ if (change.movePath) {
+ const moveResult = await ops.moveFile(path, change.movePath, change.newContent)
+ results[change.movePath] = { finalContent: moveResult.finalContent }
+ results[path] = { deleted: true }
+ } else {
+ const updateResult = await ops.modifyFile(path, change.newContent)
+ results[path] = { finalContent: updateResult.finalContent }
+ }
+ break
+ }
+ }
+
+ return results
+ }
+
+ /**
+ * Reverts all changes made by the last applyCommit operation.
+ * This method restores files to their original state before the patch was applied.
+ */
+ private async revertChanges(): Promise {
+ if (!this.appliedCommit || !this.providerOps) {
+ return
+ }
+
+ const ops = this.providerOps
+
+ // Revert changes for each file
+ for (const [path, change] of Object.entries(this.appliedCommit.changes)) {
+ try {
+ switch (change.type) {
+ case ActionType.DELETE:
+ // Restore deleted file
+ if (change.oldContent !== undefined) {
+ await ops.createFile(path, change.oldContent)
+ }
+ break
+ case ActionType.ADD:
+ // Remove newly created file
+ await ops.deleteFile(path)
+ break
+ case ActionType.UPDATE:
+ // Restore original content
+ if (change.movePath) {
+ // If file was moved, delete the new file and restore the original
+ await ops.deleteFile(change.movePath)
+ if (change.oldContent !== undefined) {
+ await ops.createFile(path, change.oldContent)
+ }
+ } else if (change.oldContent !== undefined) {
+ // Restore original content at same location
+ await ops.modifyFile(path, change.oldContent)
+ }
+ break
+ }
+ } catch (error) {
+ // Continue reverting other files even if one fails
+ console.error(`Failed to revert ${path}:`, error)
+ }
+ }
+
+ // Clear state after reverting
+ this.appliedCommit = undefined
+ this.config = undefined
+ }
+
+ // Promise all for generateChangeSummary
+ private async generateChangeSummary(changes: Record): Promise {
+ const summaries = await Promise.all(
+ Object.entries(changes).map(async ([file, change]) => {
+ switch (change.type) {
+ case ActionType.ADD:
+ return {
+ tool: "newFileCreated",
+ path: file,
+ content: change.newContent,
+ operationIsLocatedInWorkspace: await isLocatedInWorkspace(file),
+ } as ClineSayTool
+ case ActionType.UPDATE:
+ return {
+ tool: change.movePath ? "newFileCreated" : "editedExistingFile",
+ path: change.movePath || file,
+ content: change.movePath ? change.oldContent : change.newContent,
+ operationIsLocatedInWorkspace: await isLocatedInWorkspace(file),
+ } as ClineSayTool
+ case ActionType.DELETE:
+ default:
+ return {
+ tool: "editedExistingFile",
+ path: file,
+ content: change.newContent,
+ operationIsLocatedInWorkspace: await isLocatedInWorkspace(file),
+ } as ClineSayTool
+ }
+ }),
+ )
+
+ return summaries
+ }
+
+ // Approval handling
+ private async handleApproval(
+ config: TaskConfig,
+ block: ToolUse,
+ message: ClineSayTool,
+ primaryFile: string,
+ ): Promise {
+ const messageStr = JSON.stringify(message)
+ const shouldAutoApprove = await config.callbacks.shouldAutoApproveToolWithPath(block.name, primaryFile)
+
+ if (shouldAutoApprove) {
+ await config.callbacks.say("tool", messageStr, undefined, undefined, false)
+ config.taskState.consecutiveAutoApprovedRequestsCount++
+ telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true)
+ return true
+ }
+
+ const fileCount = Object.keys(JSON.parse(messageStr).content.match(/\d+/)?.[0] || "0").length
+ showNotificationForApprovalIfAutoApprovalEnabled(
+ `Cline wants to apply a patch to ${fileCount} file(s)`,
+ config.autoApprovalSettings.enabled,
+ config.autoApprovalSettings.enableNotifications,
+ )
+
+ const { response, text, images, files } = await config.callbacks.ask("tool", messageStr, false)
+
+ if (text || images?.length || files?.length) {
+ const fileContent = files?.length ? await processFilesIntoText(files) : ""
+ ToolResultUtils.pushAdditionalToolFeedback(config.taskState.userMessageContent, text, images, fileContent)
+ await config.callbacks.say("user_feedback", text, images, files)
+ }
+
+ const approved = response === "yesButtonClicked"
+ config.taskState.didRejectTool = !approved
+ telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, approved)
+
+ return approved
+ }
+}
+
+// Optimized parser
+class PatchParser {
+ private patch: Patch = { actions: {} }
+ private index = 0
+
+ constructor(private lines: string[]) {}
+
+ parse(): Patch {
+ this.skipBeginSentinel()
+
+ while (this.hasMoreLines() && !this.isEndMarker()) {
+ this.parseNextAction()
+ }
+
+ return this.patch
+ }
+
+ private skipBeginSentinel(): void {
+ if (this.lines[this.index]?.startsWith(PATCH_MARKERS.BEGIN)) {
+ this.index++
+ }
+ }
+
+ private hasMoreLines(): boolean {
+ return this.index < this.lines.length
+ }
+
+ private isEndMarker(): boolean {
+ return this.lines[this.index].startsWith(PATCH_MARKERS.END)
+ }
+
+ private isStopMarker(): boolean {
+ const line = this.lines[this.index]
+ return (
+ line.startsWith(PATCH_MARKERS.SECTION) ||
+ line.startsWith(PATCH_MARKERS.END_FILE) ||
+ line === "***" ||
+ this.isAtFileMarker()
+ )
+ }
+
+ private parseNextAction(): void {
+ const line = this.lines[this.index]
+
+ if (line.startsWith(PATCH_MARKERS.UPDATE)) {
+ this.parseUpdate(line.substring(PATCH_MARKERS.UPDATE.length).trim())
+ } else if (line.startsWith(PATCH_MARKERS.DELETE)) {
+ this.parseDelete(line.substring(PATCH_MARKERS.DELETE.length).trim())
+ } else if (line.startsWith(PATCH_MARKERS.ADD)) {
+ this.parseAdd(line.substring(PATCH_MARKERS.ADD.length).trim())
+ } else {
+ throw new DiffError(`Unknown line while parsing: ${line}`)
+ }
+ }
+
+ private checkDuplicate(path: string, operation: string): void {
+ if (path in this.patch.actions) {
+ throw new DiffError(`Duplicate ${operation} for file: ${path}`)
+ }
+ }
+
+ private parseUpdate(path: string): void {
+ this.checkDuplicate(path, "update")
+
+ this.index++
+ const movePath = this.lines[this.index]?.startsWith(PATCH_MARKERS.MOVE)
+ ? this.lines[this.index++].substring(PATCH_MARKERS.MOVE.length).trim()
+ : undefined
+
+ const chunks: Chunk[] = []
+ while (this.hasMoreLines() && !this.isAtFileMarker()) {
+ if (this.lines[this.index].startsWith(PATCH_MARKERS.SECTION) || this.lines[this.index] === PATCH_MARKERS.SECTION) {
+ this.index++
+ }
+ chunks.push(...this.parseChunks())
+ }
+
+ // Sort chunks by origIndex to handle multiple @@ sections in any order
+ chunks.sort((a, b) => a.origIndex - b.origIndex)
+
+ this.patch.actions[path] = { type: ActionType.UPDATE, chunks, movePath }
+ }
+
+ private parseDelete(path: string): void {
+ this.checkDuplicate(path, "delete")
+ this.patch.actions[path] = { type: ActionType.DELETE, chunks: [] }
+ this.index++
+ }
+
+ private parseAdd(path: string): void {
+ this.checkDuplicate(path, "add")
+
+ this.index++
+ const lines: string[] = []
+
+ while (this.hasMoreLines() && !this.isAtFileMarker()) {
+ const line = this.lines[this.index++]
+ if (!line.startsWith("+")) {
+ throw new DiffError(`Invalid Add File line (missing '+'): ${line}`)
+ }
+ lines.push(line.substring(1))
+ }
+
+ this.patch.actions[path] = { type: ActionType.ADD, newFile: lines.join("\n"), chunks: [] }
+ }
+
+ private isAtFileMarker(): boolean {
+ const line = this.lines[this.index]
+ return (
+ line.startsWith(PATCH_MARKERS.END) ||
+ line.startsWith(PATCH_MARKERS.UPDATE) ||
+ line.startsWith(PATCH_MARKERS.DELETE) ||
+ line.startsWith(PATCH_MARKERS.ADD)
+ )
+ }
+
+ private parseChunks(): Chunk[] {
+ const chunks: Chunk[] = []
+ let currentOriginalLineCount = 0 // Track position in original file for this section
+ let delLines: string[] = []
+ let insLines: string[] = []
+ let lastMode: "keep" | "add" | "delete" = "keep"
+
+ while (this.hasMoreLines() && !this.isStopMarker()) {
+ const line = this.lines[this.index]
+
+ if (line.startsWith("***")) {
+ throw new DiffError(`Invalid Line: ${line}`)
+ }
+
+ this.index++
+ const content = line === "" ? " " : line
+ const firstChar = content[0]
+
+ const mode = this.getLineMode(firstChar, line)
+ const lineContent = content.substring(1)
+
+ // Flush accumulated changes when transitioning to "keep" mode
+ if (mode === "keep" && lastMode !== "keep" && (insLines.length > 0 || delLines.length > 0)) {
+ // Cancel out matching delete/add pairs before creating chunk
+ const { filteredDelLines, filteredInsLines } = this.cancelMatchingLines(delLines, insLines)
+ if (filteredDelLines.length > 0 || filteredInsLines.length > 0) {
+ chunks.push(
+ this.createChunk(currentOriginalLineCount - filteredDelLines.length, filteredDelLines, filteredInsLines),
+ )
+ }
+ delLines = []
+ insLines = []
+ }
+
+ // Track original file line position and accumulate lines
+ if (mode === "delete") {
+ delLines.push(lineContent)
+ currentOriginalLineCount++
+ } else if (mode === "add") {
+ insLines.push(lineContent)
+ // Additions don't advance the original line counter
+ } else {
+ // mode === "keep"
+ currentOriginalLineCount++
+ }
+
+ lastMode = mode
+ }
+
+ // Flush any remaining changes
+ if (insLines.length > 0 || delLines.length > 0) {
+ // Cancel out matching delete/add pairs before creating chunk
+ const { filteredDelLines, filteredInsLines } = this.cancelMatchingLines(delLines, insLines)
+ if (filteredDelLines.length > 0 || filteredInsLines.length > 0) {
+ chunks.push(
+ this.createChunk(currentOriginalLineCount - filteredDelLines.length, filteredDelLines, filteredInsLines),
+ )
+ }
+ }
+
+ this.skipEndFileMarker()
+ return chunks
+ }
+
+ private cancelMatchingLines(
+ delLines: string[],
+ insLines: string[],
+ ): { filteredDelLines: string[]; filteredInsLines: string[] } {
+ // Match lines from the beginning - cancel only consecutive matching pairs
+ // In unified diff: -A +A (cancel), but -A +B +A (don't cancel, it's a reorder/replace)
+ let delIdx = 0
+ let insIdx = 0
+
+ // Skip matching lines from the start
+ while (delIdx < delLines.length && insIdx < insLines.length && delLines[delIdx] === insLines[insIdx]) {
+ delIdx++
+ insIdx++
+ }
+
+ // Return the remaining unmatched portions
+ return {
+ filteredDelLines: delLines.slice(delIdx),
+ filteredInsLines: insLines.slice(insIdx),
+ }
+ }
+
+ private getLineMode(firstChar: string, line: string): "keep" | "add" | "delete" {
+ if (firstChar === "+") {
+ return "add"
+ }
+ if (firstChar === "-") {
+ return "delete"
+ }
+ if (firstChar === " ") {
+ return "keep"
+ }
+ throw new DiffError(`Invalid Line: ${line}`)
+ }
+
+ private createChunk(origIndex: number, delLines: string[], insLines: string[]): Chunk {
+ return { origIndex, delLines, insLines }
+ }
+
+ private skipEndFileMarker(): void {
+ if (this.hasMoreLines() && this.lines[this.index] === PATCH_MARKERS.END_FILE) {
+ this.index++
+ }
+ }
+}
diff --git a/src/core/task/tools/handlers/WriteToFileToolHandler.ts b/src/core/task/tools/handlers/WriteToFileToolHandler.ts
index 2df04ba6..247ea497 100644
--- a/src/core/task/tools/handlers/WriteToFileToolHandler.ts
+++ b/src/core/task/tools/handlers/WriteToFileToolHandler.ts
@@ -26,11 +26,11 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
constructor(private validator: ToolValidator) {}
getDescription(block: ToolUse): string {
- return `[${block.name} for '${block.params.path}']`
+ return `[${block.name} for '${block.params.path || block.params.absolutePath}']`
}
async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise {
- const rawRelPath = block.params.path
+ const rawRelPath = block.params.path || block.params.absolutePath
const rawContent = block.params.content // for write_to_file
const rawDiff = block.params.diff // for replace_in_file
@@ -54,7 +54,10 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
// Create and show partial UI message
const sharedMessageProps: ClineSayTool = {
tool: fileExists ? "editedExistingFile" : "newFileCreated",
- path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)),
+ path: getReadablePath(
+ config.cwd,
+ uiHelpers.removeClosingTag(block, block.params.path ? "path" : "absolutePath", relPath),
+ ),
content: diff || content,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath),
}
@@ -85,7 +88,7 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
}
async execute(config: TaskConfig, block: ToolUse): Promise {
- const rawRelPath = block.params.path
+ const rawRelPath = block.params.path || block.params.absolutePath
const rawContent = block.params.content // for write_to_file
const rawDiff = block.params.diff // for replace_in_file
@@ -93,7 +96,10 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
if (!rawRelPath) {
config.taskState.consecutiveMistakeCount++
await config.services.diffViewProvider.reset()
- return await config.callbacks.sayAndCreateMissingParamError(block.name, "path")
+ return await config.callbacks.sayAndCreateMissingParamError(
+ block.name,
+ block.params.absolutePath ? "absolutePath" : "path",
+ )
}
if (block.name === "replace_in_file" && !rawDiff) {
@@ -348,6 +354,7 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
config.taskState.didAlreadyUseTool = true
},
config.coordinator,
+ config.taskState.toolUseIdMap,
)
return
}
@@ -413,6 +420,7 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
config.taskState.didAlreadyUseTool = true
},
config.coordinator,
+ config.taskState.toolUseIdMap,
)
// Revert changes and reset diff view
diff --git a/src/core/task/tools/utils/ToolResultUtils.ts b/src/core/task/tools/utils/ToolResultUtils.ts
index 6d4adaff..3feef3b5 100644
--- a/src/core/task/tools/utils/ToolResultUtils.ts
+++ b/src/core/task/tools/utils/ToolResultUtils.ts
@@ -22,6 +22,7 @@ export class ToolResultUtils {
_api: ApiHandler,
markToolAsUsed: () => void,
coordinator?: ToolExecutorCoordinator,
+ toolUseIdMap?: Map,
): void {
if (typeof content === "string") {
const resultText = content || "(tool did not return anything)"
@@ -34,22 +35,41 @@ export class ToolResultUtils {
})()
: toolDescription(block)
- // Non-Claude 4: Use traditional format with header
- userMessageContent.push({
- type: "text",
- text: `${description} Result:`,
- })
- userMessageContent.push({
- type: "text",
- text: resultText,
- })
+ // Get tool_use_id from map, or use "cline" as fallback for backward compatibility
+ const toolUseId = toolUseIdMap?.get(block.name) || "cline"
+
+ // Create ToolResultBlockParam with description and result
+ userMessageContent.push(ToolResultUtils.createToolResultBlock(`${description} Result:\n${resultText}`, toolUseId))
} else {
- userMessageContent.push(...content)
+ // For complex content (arrays with text/image blocks), pass it through directly
+ // The content array should already be properly formatted with type, text, source, etc.
+ const toolUseId = toolUseIdMap?.get(block.name) || "cline"
+ userMessageContent.push(ToolResultUtils.createToolResultBlock(content, toolUseId))
}
// once a tool result has been collected, ignore all other tool uses since we should only ever present one tool result per message
markToolAsUsed()
}
+ private static createToolResultBlock(content: ToolResponse, id?: string) {
+ // If id is "cline", we treat it as a plain text result for backward compatibility
+ // as we cannot find any existing tool call that matches this id.
+ if (id === "cline") {
+ return {
+ type: "text",
+ text: typeof content === "string" ? content : JSON.stringify(content, null, 2),
+ }
+ }
+
+ // For tool_result blocks, content can be either a string or an array of content blocks
+ // When it's a string, we need to wrap it in the proper format
+ // When it's an array, it should already be properly formatted (e.g., with text and image blocks)
+ return {
+ type: "tool_result",
+ tool_use_id: id,
+ content: typeof content === "string" ? content : content,
+ }
+ }
+
/**
* Push additional tool feedback from user to message content
*/
@@ -59,14 +79,22 @@ export class ToolResultUtils {
images?: string[],
fileContentString?: string,
): void {
- if (!feedback && (!images || images.length === 0) && !fileContentString) {
+ // Check if we have any meaningful content to add
+ const hasMeaningfulFeedback = feedback && feedback.trim() !== ""
+ const hasImages = images && images.length > 0
+ const hasMeaningfulFileContent = fileContentString && fileContentString.trim() !== ""
+
+ // Only proceed if we have at least one meaningful piece of content
+ if (!hasMeaningfulFeedback && !hasImages && !hasMeaningfulFileContent) {
return
}
- const content = formatResponse.toolResult(
- `The user provided the following feedback:\n\n${feedback}\n`,
- images,
- fileContentString,
- )
+
+ // Build the feedback text only if we have meaningful feedback
+ const feedbackText = hasMeaningfulFeedback
+ ? `The user provided the following feedback:\n\n${feedback}\n`
+ : "The user provided additional content:"
+
+ const content = formatResponse.toolResult(feedbackText, images, hasMeaningfulFileContent ? fileContentString : undefined)
if (typeof content === "string") {
userMessageContent.push({
type: "text",
diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts
index 767ce803..33c0deaf 100644
--- a/src/integrations/editor/DiffViewProvider.ts
+++ b/src/integrations/editor/DiffViewProvider.ts
@@ -224,6 +224,10 @@ export abstract class DiffViewProvider {
}
}
+ async showFile(absolutePath: string): Promise {
+ await openFile(absolutePath, true)
+ }
+
/**
* Replaces text in the diff editor with the specified content.
*
@@ -264,7 +268,7 @@ export abstract class DiffViewProvider {
// get text after save in case there is any auto-formatting done by the editor
const postSaveContent = (await this.getDocumentText()) || ""
- await openFile(this.absolutePath, true)
+ await this.showFile(this.absolutePath)
await this.closeAllDiffViews()
const newProblems = await this.getNewDiagnosticProblems()
diff --git a/src/integrations/editor/FileEditProvider.ts b/src/integrations/editor/FileEditProvider.ts
new file mode 100644
index 00000000..639b6966
--- /dev/null
+++ b/src/integrations/editor/FileEditProvider.ts
@@ -0,0 +1,116 @@
+import { DiffViewProvider } from "@integrations/editor/DiffViewProvider"
+import * as fs from "fs/promises"
+
+/**
+ * A file-system-based implementation of DiffViewProvider that performs direct file operations
+ * without visual editor integration. This provider uses the Node.js fs package to handle
+ * file edits in-memory and then writes them to disk.
+ *
+ * Visual operations like scrolling are implemented as no-ops since there is no UI component.
+ * This makes it suitable for headless or non-interactive environments.
+ */
+export class FileEditProvider extends DiffViewProvider {
+ private documentContent?: string
+
+ constructor() {
+ super()
+ }
+
+ override showFile(_absolutePath: string): Promise {
+ // No-op: No visual editor to show the file
+ return Promise.resolve()
+ }
+
+ protected async openDiffEditor(): Promise {
+ // No-op: No visual editor to open in a file-system-only provider
+ // The file content is already loaded in the base class's open() method
+ this.documentContent = this.originalContent || ""
+ }
+
+ override async open(relPath: string, options?: { displayPath?: string }): Promise {
+ await super.open(relPath, options)
+ this.documentContent = this.originalContent || ""
+ }
+
+ async replaceText(
+ content: string,
+ rangeToReplace: { startLine: number; endLine: number },
+ _currentLine: number | undefined,
+ ): Promise {
+ if (this.documentContent === undefined) {
+ throw new Error("Document not initialized")
+ }
+
+ // Split the document into lines
+ const lines = this.documentContent.split("\n")
+
+ // Replace the specified range with the new content
+ const newContentLines = content.split("\n")
+ // Remove trailing empty line if present in newContentLines for proper splicing
+ if (newContentLines[newContentLines.length - 1] === "") {
+ newContentLines.pop()
+ }
+
+ // Splice the lines array to replace the range
+ lines.splice(rangeToReplace.startLine, rangeToReplace.endLine - rangeToReplace.startLine, ...newContentLines)
+
+ // Join the lines back together
+ this.documentContent = lines.join("\n")
+ }
+
+ protected async scrollEditorToLine(_line: number): Promise {
+ // No-op: No visual editor to scroll
+ }
+
+ protected async scrollAnimation(_startLine: number, _endLine: number): Promise {
+ // No-op: No visual editor to animate
+ }
+
+ protected async truncateDocument(lineNumber: number): Promise {
+ if (!this.documentContent) {
+ return
+ }
+
+ // Split the document into lines and keep only up to lineNumber
+ const lines = this.documentContent.split("\n")
+ if (lineNumber < lines.length) {
+ this.documentContent = lines.slice(0, lineNumber).join("\n")
+ }
+ }
+
+ protected async getDocumentText(): Promise {
+ return this.documentContent
+ }
+
+ /**
+ * Public method to get the current document content.
+ * This is exposed for use by tools that need to read the document state.
+ */
+ public async getContent(): Promise {
+ return this.getDocumentText()
+ }
+
+ protected async saveDocument(): Promise {
+ if (!this.absolutePath || !this.documentContent) {
+ return false
+ }
+
+ try {
+ // Write the content to the file using fs
+ await fs.writeFile(this.absolutePath, this.documentContent, { encoding: this.fileEncoding as BufferEncoding })
+ return true
+ } catch (error) {
+ console.error(`Failed to save document to ${this.absolutePath}:`, error)
+ return false
+ }
+ }
+
+ protected async closeAllDiffViews(): Promise {
+ // No-op: No visual diff views to close
+ }
+
+ protected async resetDiffView(): Promise {
+ // Clean up the in-memory document content
+ this.documentContent = undefined
+ }
+}
diff --git a/src/services/feature-flags/FeatureFlagsService.ts b/src/services/feature-flags/FeatureFlagsService.ts
index 11d1d108..7d2d8290 100644
--- a/src/services/feature-flags/FeatureFlagsService.ts
+++ b/src/services/feature-flags/FeatureFlagsService.ts
@@ -1,4 +1,3 @@
-import { Logger } from "@/services/logging/Logger"
import { FEATURE_FLAGS, FeatureFlag, FeatureFlagDefaultValue } from "@/shared/services/feature-flags/feature-flags"
import type { IFeatureFlagsProvider } from "./providers/IFeatureFlagsProvider"
@@ -35,9 +34,6 @@ export class FeatureFlagsService {
const flagEnabled = await this.getFeatureFlag(flag).catch(() => false)
this.cache.set(flag, flagEnabled === true)
}
-
- // Print DO_NOTHING flag status after polling
- Logger.log(`do_nothing flag: ${this.getDoNothingFlag()}`)
}
private async getFeatureFlag(flagName: FeatureFlag): Promise {
@@ -90,6 +86,10 @@ export class FeatureFlagsService {
return this.getBooleanFlagEnabled(FeatureFlag.HOOKS)
}
+ public getNativeToolCallEnabled(): boolean {
+ return this.getBooleanFlagEnabled(FeatureFlag.NATIVE_TOOL_CALLS_NEXT_GEN_MODELS)
+ }
+
/**
* Get the feature flag payload for advanced use cases
* @param flagName The feature flag key
diff --git a/src/shared/mcp.ts b/src/shared/mcp.ts
index dbc76a88..ed7e8f2b 100644
--- a/src/shared/mcp.ts
+++ b/src/shared/mcp.ts
@@ -1,3 +1,4 @@
+export const CLINE_MCP_TOOL_IDENTIFIER = "0mcp0"
export const DEFAULT_MCP_TIMEOUT_SECONDS = 60 // matches Anthropic's default timeout in their MCP SDK
export const MIN_MCP_TIMEOUT_SECONDS = 1
export type McpMode = "full" | "server-use-only" | "off"
diff --git a/src/shared/prompts.ts b/src/shared/prompts.ts
index 22e9c071..1cfe234e 100644
--- a/src/shared/prompts.ts
+++ b/src/shared/prompts.ts
@@ -2,10 +2,12 @@ export enum ModelFamily {
CLAUDE = "claude",
GPT = "gpt",
GPT_5 = "gpt-5",
+ NATIVE_GPT_5 = "gpt-5-native", // Uses native tool calling
GEMINI = "gemini",
QWEN = "qwen",
GLM = "glm",
NEXT_GEN = "next-gen",
GENERIC = "generic",
XS = "xs",
+ NATIVE_NEXT_GEN = "native-next-gen", // Uses native tool calling
}
diff --git a/src/shared/services/feature-flags/feature-flags.ts b/src/shared/services/feature-flags/feature-flags.ts
index e4cdd138..bd1c6a15 100644
--- a/src/shared/services/feature-flags/feature-flags.ts
+++ b/src/shared/services/feature-flags/feature-flags.ts
@@ -6,12 +6,15 @@ export enum FeatureFlag {
WORKOS_AUTH = "workos_auth",
DO_NOTHING = "do_nothing",
HOOKS = "hooks",
+ // Feature flag for enabling native tool calls for next-gen models
+ NATIVE_TOOL_CALLS_NEXT_GEN_MODELS = "native_tool_calls_next_gen",
}
export const FeatureFlagDefaultValue: Partial> = {
[FeatureFlag.WORKOS_AUTH]: true,
[FeatureFlag.DO_NOTHING]: false,
[FeatureFlag.HOOKS]: false,
+ [FeatureFlag.NATIVE_TOOL_CALLS_NEXT_GEN_MODELS]: process.env.IS_DEV === "true",
}
export const FEATURE_FLAGS = Object.values(FeatureFlag)
diff --git a/src/shared/tools.ts b/src/shared/tools.ts
index 10a6abfa..c84c4f98 100644
--- a/src/shared/tools.ts
+++ b/src/shared/tools.ts
@@ -1,3 +1,9 @@
+import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
+import { FunctionDeclaration as GoogleTool } from "@google/genai"
+import { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
+
+export type ClineTool = OpenAITool | AnthropicTool | GoogleTool
+
// Define available tool ids
export enum ClineDefaultTool {
ASK = "ask_followup_question",
@@ -21,6 +27,7 @@ export enum ClineDefaultTool {
SUMMARIZE_TASK = "summarize_task",
REPORT_BUG = "report_bug",
NEW_RULE = "new_rule",
+ APPLY_PATCH = "apply_patch",
}
// Array of all tool names for compatibility
diff --git a/src/utils/model-utils.ts b/src/utils/model-utils.ts
index 7d06c0b4..e3037dc1 100644
--- a/src/utils/model-utils.ts
+++ b/src/utils/model-utils.ts
@@ -1,6 +1,15 @@
import { ApiHandlerModel, ApiProviderInfo } from "@core/api"
import { AnthropicModelId, anthropicModels } from "@/shared/api"
+const CLAUDE_VERSION_MATCH_REGEX = /[-_ ]([\d](?:\.[05])?)[-_ ]?/
+
+export function isNextGenModelProvider(providerInfo: ApiProviderInfo): boolean {
+ const providerId = normalize(providerInfo.providerId)
+ return ["cline", "anthropic", "gemini", "openrouter", "xai", "openai", "openai-native", "vercel-ai-gateway"].some(
+ (id) => providerId === id,
+ )
+}
+
export function modelDoesntSupportWebp(apiHandlerModel: ApiHandlerModel): boolean {
const modelId = apiHandlerModel.id.toLowerCase()
return modelId.includes("grok")
@@ -18,20 +27,23 @@ export function shouldSkipReasoningForModel(modelId?: string): boolean {
}
export function isAnthropicModelId(modelId: string): modelId is AnthropicModelId {
- return modelId in anthropicModels || isClaude4ModelFamily(modelId)
+ const CLAUDE_MODELS = ["sonnet", "opus", "haiku"]
+ return modelId in anthropicModels || CLAUDE_MODELS.some((substring) => modelId.includes(substring))
}
-export function isClaude4ModelFamily(id: string): boolean {
+export function isClaude4PlusModelFamily(id: string): boolean {
const modelId = normalize(id)
- return (
- modelId.includes("sonnet-4") ||
- modelId.includes("opus-4") ||
- modelId.includes("4-sonnet") ||
- modelId.includes("4-opus") ||
- modelId.includes("haiku-4") ||
- modelId.includes("4-5-haiku") ||
- modelId.includes("4.5-haiku")
- )
+ if (!isAnthropicModelId(modelId)) {
+ return false
+ }
+ // Get model version number
+ const versionMatch = modelId.match(CLAUDE_VERSION_MATCH_REGEX)
+ if (!versionMatch) {
+ return false
+ }
+ const version = parseFloat(versionMatch[1])
+ // Check if version is 4.0 or higher
+ return version >= 4
}
export function isGemini2dot5ModelFamily(id: string): boolean {
@@ -41,7 +53,7 @@ export function isGemini2dot5ModelFamily(id: string): boolean {
export function isGrok4ModelFamily(id: string): boolean {
const modelId = normalize(id)
- return modelId.includes("grok-4")
+ return modelId.includes("grok-4") || modelId.includes("grok-code")
}
export function isGPT5ModelFamily(id: string): boolean {
@@ -62,7 +74,7 @@ export function isGLMModelFamily(id: string): boolean {
export function isNextGenModelFamily(id: string): boolean {
const modelId = normalize(id)
return (
- isClaude4ModelFamily(modelId) ||
+ isClaude4PlusModelFamily(modelId) ||
isGemini2dot5ModelFamily(modelId) ||
isGrok4ModelFamily(modelId) ||
isGPT5ModelFamily(modelId)