native tool calling (#6921)
* (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. <budget:token_budget>200000</budget:token_budget> * 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. <budget:token_budget>200000</budget:token_budget> * 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
This commit is contained in:
103 files changed
+4822
-604
No files matched your search
+1
-1
@@ -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",
|
||||
|
||||
@@ -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<ApiStreamUsageChunk | undefined>
|
||||
}
|
||||
|
||||
@@ -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<MessageParam> = 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) || ""
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 || [],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown>,
|
||||
},
|
||||
}
|
||||
case "tool_result":
|
||||
return {
|
||||
functionResponse: {
|
||||
name: block.tool_use_id,
|
||||
response: {
|
||||
result: block.content,
|
||||
},
|
||||
},
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported content block type: ${block.type}`)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<ChatCompletionTool>,
|
||||
) {
|
||||
// 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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<ApiStreamToolCallsChunk> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
"\\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<string, PendingToolUse>()
|
||||
|
||||
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<string, string> = {}
|
||||
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<string, any> {
|
||||
const result: Record<string, any> = {}
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<string, Anthropic.Messages.ToolResultBlockParam>()
|
||||
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<string>()
|
||||
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
|
||||
*/
|
||||
|
||||
@@ -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:
|
||||
|
||||
<tool_name>
|
||||
<parameter1_name>value1</parameter1_name>
|
||||
<parameter2_name>value2</parameter2_name>
|
||||
...
|
||||
</tool_name>
|
||||
|
||||
For example:
|
||||
|
||||
<attempt_completion>
|
||||
<result>
|
||||
I have completed the task...
|
||||
</result>
|
||||
</attempt_completion>
|
||||
|
||||
Always adhere to this format for all tool uses to ensure proper parsing and execution.`
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+98
@@ -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
|
||||
+96
@@ -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
|
||||
+79
@@ -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
|
||||
+98
@@ -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
|
||||
@@ -49,54 +49,69 @@ Usage:
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</read_file>
|
||||
|
||||
## 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:
|
||||
<write_to_file>
|
||||
<path>File path here</path>
|
||||
<content>Your file content here</content>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</write_to_file>
|
||||
## 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:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>Search and replace blocks here</diff>
|
||||
<apply_patch>
|
||||
<input></input>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</replace_in_file>
|
||||
</apply_patch>
|
||||
|
||||
## 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.
|
||||
|
||||
+58
-43
@@ -49,54 +49,69 @@ Usage:
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</read_file>
|
||||
|
||||
## 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:
|
||||
<write_to_file>
|
||||
<path>File path here</path>
|
||||
<content>Your file content here</content>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</write_to_file>
|
||||
## 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:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>Search and replace blocks here</diff>
|
||||
<apply_patch>
|
||||
<input></input>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</replace_in_file>
|
||||
</apply_patch>
|
||||
|
||||
## 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.
|
||||
|
||||
+58
-41
@@ -44,50 +44,67 @@ Usage:
|
||||
<path>File path here</path>
|
||||
</read_file>
|
||||
|
||||
## 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:
|
||||
<write_to_file>
|
||||
<path>File path here</path>
|
||||
<content>Your file content here</content>
|
||||
</write_to_file>
|
||||
## 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:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>Search and replace blocks here</diff>
|
||||
</replace_in_file>
|
||||
<apply_patch>
|
||||
<input></input>
|
||||
</apply_patch>
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -49,54 +49,69 @@ Usage:
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</read_file>
|
||||
|
||||
## 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:
|
||||
<write_to_file>
|
||||
<path>File path here</path>
|
||||
<content>Your file content here</content>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</write_to_file>
|
||||
## 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:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>Search and replace blocks here</diff>
|
||||
<apply_patch>
|
||||
<input></input>
|
||||
<task_progress>Checklist here (optional)</task_progress>
|
||||
</replace_in_file>
|
||||
</apply_patch>
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 }
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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<string> {
|
||||
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 }
|
||||
}
|
||||
@@ -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<string, any>).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,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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<typeof ClineToolSet.getTools> = []
|
||||
|
||||
// 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)))
|
||||
}
|
||||
|
||||
@@ -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<string, PromptVariant> = 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<string> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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<string, any>
|
||||
/**
|
||||
* 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<string, any> = {}
|
||||
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<string, any> = {}
|
||||
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<string, any> = {}
|
||||
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<string, any>
|
||||
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}`)
|
||||
}
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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 <response> 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 <plan_mode_respond> 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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -30,6 +30,7 @@ export interface PromptVariant {
|
||||
readonly labels: Readonly<Record<string, number>> // 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<string, number>
|
||||
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<string, number>): this
|
||||
matcher(matcherFn: (providerInfo: ApiProviderInfo) => boolean): this
|
||||
template(baseTemplate: string): this
|
||||
components(...sections: SystemPromptSection[]): this
|
||||
overrideComponent(section: SystemPromptSection, override: ConfigOverride): this
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(", ")}`)
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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(", ")}`)
|
||||
|
||||
@@ -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<string, number>): 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 || [])
|
||||
|
||||
@@ -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(", ")}`)
|
||||
|
||||
@@ -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<string, string> = new Map()
|
||||
|
||||
// Presentation locks
|
||||
presentAssistantMessageLocked = false
|
||||
|
||||
@@ -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<boolean> {
|
||||
// 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
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
+130
-29
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<void> {
|
||||
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<ToolResponse> {
|
||||
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
|
||||
|
||||
@@ -22,6 +22,7 @@ export class ToolResultUtils {
|
||||
_api: ApiHandler,
|
||||
markToolAsUsed: () => void,
|
||||
coordinator?: ToolExecutorCoordinator,
|
||||
toolUseIdMap?: Map<string, string>,
|
||||
): 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<feedback>\n${feedback}\n</feedback>`,
|
||||
images,
|
||||
fileContentString,
|
||||
)
|
||||
|
||||
// Build the feedback text only if we have meaningful feedback
|
||||
const feedbackText = hasMeaningfulFeedback
|
||||
? `The user provided the following feedback:\n<feedback>\n${feedback}\n</feedback>`
|
||||
: "The user provided additional content:"
|
||||
|
||||
const content = formatResponse.toolResult(feedbackText, images, hasMeaningfulFileContent ? fileContentString : undefined)
|
||||
if (typeof content === "string") {
|
||||
userMessageContent.push({
|
||||
type: "text",
|
||||
|
||||
@@ -224,6 +224,10 @@ export abstract class DiffViewProvider {
|
||||
}
|
||||
}
|
||||
|
||||
async showFile(absolutePath: string): Promise<void> {
|
||||
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()
|
||||
|
||||
@@ -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<void> {
|
||||
// No-op: No visual editor to show the file
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
protected async openDiffEditor(): Promise<void> {
|
||||
// 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<void> {
|
||||
await super.open(relPath, options)
|
||||
this.documentContent = this.originalContent || ""
|
||||
}
|
||||
|
||||
async replaceText(
|
||||
content: string,
|
||||
rangeToReplace: { startLine: number; endLine: number },
|
||||
_currentLine: number | undefined,
|
||||
): Promise<void> {
|
||||
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<void> {
|
||||
// No-op: No visual editor to scroll
|
||||
}
|
||||
|
||||
protected async scrollAnimation(_startLine: number, _endLine: number): Promise<void> {
|
||||
// No-op: No visual editor to animate
|
||||
}
|
||||
|
||||
protected async truncateDocument(lineNumber: number): Promise<void> {
|
||||
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<string | undefined> {
|
||||
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<string | undefined> {
|
||||
return this.getDocumentText()
|
||||
}
|
||||
|
||||
protected async saveDocument(): Promise<Boolean> {
|
||||
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<void> {
|
||||
// No-op: No visual diff views to close
|
||||
}
|
||||
|
||||
protected async resetDiffView(): Promise<void> {
|
||||
// Clean up the in-memory document content
|
||||
this.documentContent = undefined
|
||||
}
|
||||
}
|
||||
@@ -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<unknown> {
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
}
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user