chore: Prettier fix formatting

This commit is contained in:
Saoud Rizwan committed 2025-01-06 12:41:33 -08:00
1 parent 9de7253998
commit 25cd7cc8e2
106 files changed
+1624 -5278

No files matched your search

+435 -1499
View File
File diff suppressed because it is too large. Load diff
+10 -46
View File
@@ -6,11 +6,7 @@
*
* Returns [matchIndexStart, matchIndexEnd] if found, or false if not found.
*/
function lineTrimmedFallbackMatch(
originalContent: string,
searchContent: string,
startIndex: number,
): [number, number] | false {
function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
// Split both contents into lines
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
@@ -29,11 +25,7 @@ function lineTrimmedFallbackMatch(
}
// For each possible starting position in original content
for (
let i = startLineNum;
i <= originalLines.length - searchLines.length;
i++
) {
for (let i = startLineNum; i <= originalLines.length - searchLines.length; i++) {
let matches = true
// Try to match all search lines from this position
@@ -95,11 +87,7 @@ function lineTrimmedFallbackMatch(
* @param startIndex - The character index in originalContent where to start searching
* @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise
*/
function blockAnchorFallbackMatch(
originalContent: string,
searchContent: string,
startIndex: number,
): [number, number] | false {
function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
@@ -126,11 +114,7 @@ function blockAnchorFallbackMatch(
}
// Look for matching start and end anchors
for (
let i = startLineNum;
i <= originalLines.length - searchBlockSize;
i++
) {
for (let i = startLineNum; i <= originalLines.length - searchBlockSize; i++) {
// Check if first line matches
if (originalLines[i].trim() !== firstLineSearch) {
continue
@@ -216,11 +200,7 @@ function blockAnchorFallbackMatch(
* - If the search block cannot be matched using any of the available matching strategies,
* an error is thrown.
*/
export async function constructNewFileContent(
diffContent: string,
originalContent: string,
isFinal: boolean,
): Promise<string> {
export async function constructNewFileContent(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let result = ""
let lastProcessedIndex = 0
@@ -239,9 +219,7 @@ export async function constructNewFileContent(
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith("<") ||
lastLine.startsWith("=") ||
lastLine.startsWith(">")) &&
(lastLine.startsWith("<") || lastLine.startsWith("=") || lastLine.startsWith(">")) &&
lastLine !== "<<<<<<< SEARCH" &&
lastLine !== "=======" &&
lastLine !== ">>>>>>> REPLACE"
@@ -290,29 +268,18 @@ export async function constructNewFileContent(
// }
// Exact search match scenario
const exactIndex = originalContent.indexOf(
currentSearchContent,
lastProcessedIndex,
)
const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex)
if (exactIndex !== -1) {
searchMatchIndex = exactIndex
searchEndIndex = exactIndex + currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(
originalContent,
currentSearchContent,
lastProcessedIndex,
)
const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (lineMatch) {
;[searchMatchIndex, searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(
originalContent,
currentSearchContent,
lastProcessedIndex,
)
const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (blockMatch) {
;[searchMatchIndex, searchEndIndex] = blockMatch
} else {
@@ -325,10 +292,7 @@ export async function constructNewFileContent(
}
// Output everything up to the match location
result += originalContent.slice(
lastProcessedIndex,
searchMatchIndex,
)
result += originalContent.slice(lastProcessedIndex, searchMatchIndex)
continue
}
+4 -18
View File
@@ -60,9 +60,7 @@ export interface ToolUse {
export interface ExecuteCommandToolUse extends ToolUse {
name: "execute_command"
// Pick<Record<ToolParamName, string>, "command"> makes "command" required, but Partial<> makes it optional
params: Partial<
Pick<Record<ToolParamName, string>, "command" | "requires_approval">
>
params: Partial<Pick<Record<ToolParamName, string>, "command" | "requires_approval">>
}
export interface ReadFileToolUse extends ToolUse {
@@ -82,9 +80,7 @@ export interface ReplaceInFileToolUse extends ToolUse {
export interface SearchFilesToolUse extends ToolUse {
name: "search_files"
params: Partial<
Pick<Record<ToolParamName, string>, "path" | "regex" | "file_pattern">
>
params: Partial<Pick<Record<ToolParamName, string>, "path" | "regex" | "file_pattern">>
}
export interface ListFilesToolUse extends ToolUse {
@@ -99,22 +95,12 @@ export interface ListCodeDefinitionNamesToolUse extends ToolUse {
export interface BrowserActionToolUse extends ToolUse {
name: "browser_action"
params: Partial<
Pick<
Record<ToolParamName, string>,
"action" | "url" | "coordinate" | "text"
>
>
params: Partial<Pick<Record<ToolParamName, string>, "action" | "url" | "coordinate" | "text">>
}
export interface UseMcpToolToolUse extends ToolUse {
name: "use_mcp_tool"
params: Partial<
Pick<
Record<ToolParamName, string>,
"server_name" | "tool_name" | "arguments"
>
>
params: Partial<Pick<Record<ToolParamName, string>, "server_name" | "tool_name" | "arguments">>
}
export interface AccessMcpResourceToolUse extends ToolUse {
@@ -1,12 +1,4 @@
import {
AssistantMessageContent,
TextContent,
ToolUse,
ToolParamName,
toolParamNames,
toolUseNames,
ToolUseName,
} from "."
import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParamNames, toolUseNames, ToolUseName } from "."
export function parseAssistantMessage(assistantMessage: string) {
let contentBlocks: AssistantMessageContent[] = []
@@ -24,15 +16,11 @@ export function parseAssistantMessage(assistantMessage: string) {
// there should not be a param without a tool use
if (currentToolUse && currentParamName) {
const currentParamValue = accumulator.slice(
currentParamValueStartIndex,
)
const currentParamValue = accumulator.slice(currentParamValueStartIndex)
const paramClosingTag = `</${currentParamName}>`
if (currentParamValue.endsWith(paramClosingTag)) {
// end of param value
currentToolUse.params[currentParamName] = currentParamValue
.slice(0, -paramClosingTag.length)
.trim()
currentToolUse.params[currentParamName] = currentParamValue.slice(0, -paramClosingTag.length).trim()
currentParamName = undefined
continue
} else {
@@ -53,16 +41,11 @@ export function parseAssistantMessage(assistantMessage: string) {
currentToolUse = undefined
continue
} else {
const possibleParamOpeningTags = toolParamNames.map(
(name) => `<${name}>`,
)
const possibleParamOpeningTags = toolParamNames.map((name) => `<${name}>`)
for (const paramOpeningTag of possibleParamOpeningTags) {
if (accumulator.endsWith(paramOpeningTag)) {
// start of a new parameter
currentParamName = paramOpeningTag.slice(
1,
-1,
) as ToolParamName
currentParamName = paramOpeningTag.slice(1, -1) as ToolParamName
currentParamValueStartIndex = accumulator.length
break
}
@@ -72,28 +55,14 @@ export function parseAssistantMessage(assistantMessage: string) {
// special case for write_to_file where file contents could contain the closing tag, in which case the param would have closed and we end up with the rest of the file contents here. To work around this, we get the string between the starting content tag and the LAST content tag.
const contentParamName: ToolParamName = "content"
if (
currentToolUse.name === "write_to_file" &&
accumulator.endsWith(`</${contentParamName}>`)
) {
const toolContent = accumulator.slice(
currentToolUseStartIndex,
)
if (currentToolUse.name === "write_to_file" && accumulator.endsWith(`</${contentParamName}>`)) {
const toolContent = accumulator.slice(currentToolUseStartIndex)
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
const contentStartIndex =
toolContent.indexOf(contentStartTag) +
contentStartTag.length
const contentEndIndex =
toolContent.lastIndexOf(contentEndTag)
if (
contentStartIndex !== -1 &&
contentEndIndex !== -1 &&
contentEndIndex > contentStartIndex
) {
currentToolUse.params[contentParamName] = toolContent
.slice(contentStartIndex, contentEndIndex)
.trim()
const contentStartIndex = toolContent.indexOf(contentStartTag) + contentStartTag.length
const contentEndIndex = toolContent.lastIndexOf(contentEndTag)
if (contentStartIndex !== -1 && contentEndIndex !== -1 && contentEndIndex > contentStartIndex) {
currentToolUse.params[contentParamName] = toolContent.slice(contentStartIndex, contentEndIndex).trim()
}
}
@@ -105,9 +74,7 @@ export function parseAssistantMessage(assistantMessage: string) {
// no currentToolUse
let didStartToolUse = false
const possibleToolUseOpeningTags = toolUseNames.map(
(name) => `<${name}>`,
)
const possibleToolUseOpeningTags = toolUseNames.map((name) => `<${name}>`)
for (const toolUseOpeningTag of possibleToolUseOpeningTags) {
if (accumulator.endsWith(toolUseOpeningTag)) {
// start of a new tool use
@@ -151,9 +118,7 @@ export function parseAssistantMessage(assistantMessage: string) {
// stream did not complete tool call, add it as partial
if (currentParamName) {
// tool call has a parameter that was not completed
currentToolUse.params[currentParamName] = accumulator
.slice(currentParamValueStartIndex)
.trim()
currentToolUse.params[currentParamName] = accumulator.slice(currentParamValueStartIndex).trim()
}
contentBlocks.push(currentToolUse)
}
+12 -38
View File
@@ -15,18 +15,13 @@ export function openMention(mention?: string): void {
if (mention.startsWith("/")) {
const relPath = mention.slice(1)
const cwd = vscode.workspace.workspaceFolders
?.map((folder) => folder.uri.fsPath)
.at(0)
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
if (!cwd) {
return
}
const absPath = path.resolve(cwd, relPath)
if (mention.endsWith("/")) {
vscode.commands.executeCommand(
"revealInExplorer",
vscode.Uri.file(absPath),
)
vscode.commands.executeCommand("revealInExplorer", vscode.Uri.file(absPath))
// vscode.commands.executeCommand("vscode.openFolder", , { forceNewWindow: false }) opens in new window
} else {
openFile(absPath)
@@ -38,11 +33,7 @@ export function openMention(mention?: string): void {
}
}
export async function parseMentions(
text: string,
cwd: string,
urlContentFetcher: UrlContentFetcher,
): Promise<string> {
export async function parseMentions(text: string, cwd: string, urlContentFetcher: UrlContentFetcher): Promise<string> {
const mentions: Set<string> = new Set()
let parsedText = text.replace(mentionRegexGlobal, (match, mention) => {
mentions.add(mention)
@@ -59,18 +50,14 @@ export async function parseMentions(
return match
})
const urlMention = Array.from(mentions).find((mention) =>
mention.startsWith("http"),
)
const urlMention = Array.from(mentions).find((mention) => mention.startsWith("http"))
let launchBrowserError: Error | undefined
if (urlMention) {
try {
await urlContentFetcher.launchBrowser()
} catch (error) {
launchBrowserError = error
vscode.window.showErrorMessage(
`Error fetching content for ${urlMention}: ${error.message}`,
)
vscode.window.showErrorMessage(`Error fetching content for ${urlMention}: ${error.message}`)
}
}
@@ -81,13 +68,10 @@ export async function parseMentions(
result = `Error fetching content: ${launchBrowserError.message}`
} else {
try {
const markdown =
await urlContentFetcher.urlToMarkdown(mention)
const markdown = await urlContentFetcher.urlToMarkdown(mention)
result = markdown
} catch (error) {
vscode.window.showErrorMessage(
`Error fetching content for ${mention}: ${error.message}`,
)
vscode.window.showErrorMessage(`Error fetching content for ${mention}: ${error.message}`)
result = `Error fetching content: ${error.message}`
}
}
@@ -129,10 +113,7 @@ export async function parseMentions(
return parsedText
}
async function getFileOrFolderContent(
mentionPath: string,
cwd: string,
): Promise<string> {
async function getFileOrFolderContent(mentionPath: string, cwd: string): Promise<string> {
const absPath = path.resolve(cwd, mentionPath)
try {
@@ -160,14 +141,11 @@ async function getFileOrFolderContent(
fileContentPromises.push(
(async () => {
try {
const isBinary = await isBinaryFile(
absoluteFilePath,
).catch(() => false)
const isBinary = await isBinaryFile(absoluteFilePath).catch(() => false)
if (isBinary) {
return undefined
}
const content =
await extractTextFromFile(absoluteFilePath)
const content = await extractTextFromFile(absoluteFilePath)
return `<file_content path="${filePath.toPosix()}">\n${content}\n</file_content>`
} catch (error) {
return undefined
@@ -181,17 +159,13 @@ async function getFileOrFolderContent(
folderContent += `${linePrefix}${entry.name}\n`
}
})
const fileContents = (
await Promise.all(fileContentPromises)
).filter((content) => content)
const fileContents = (await Promise.all(fileContentPromises)).filter((content) => content)
return `${folderContent}\n${fileContents.join("\n\n")}`.trim()
} else {
return `(Failed to read contents of ${mentionPath})`
}
} catch (error) {
throw new Error(
`Failed to access path "${mentionPath}": ${error.message}`,
)
throw new Error(`Failed to access path "${mentionPath}": ${error.message}`)
}
}
+9 -35
View File
@@ -8,8 +8,7 @@ export const formatResponse = {
toolDeniedWithFeedback: (feedback?: string) =>
`The user denied this operation and provided the following feedback:\n<feedback>\n${feedback}\n</feedback>`,
toolError: (error?: string) =>
`The tool execution failed with the following error:\n<error>\n${error}\n</error>`,
toolError: (error?: string) => `The tool execution failed with the following error:\n<error>\n${error}\n</error>`,
noToolsUsed: () =>
`[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
@@ -32,14 +31,10 @@ Otherwise, if you have not completed the task and do not need additional informa
invalidMcpToolArgumentError: (serverName: string, toolName: string) =>
`Invalid JSON argument used with ${serverName} for ${toolName}. Please retry with a properly formatted JSON argument.`,
toolResult: (
text: string,
images?: string[],
): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
toolResult: (text: string, images?: string[]): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
if (images && images.length > 0) {
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
const imageBlocks: Anthropic.ImageBlockParam[] =
formatImagesIntoBlocks(images)
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
// Placing images after text leads to better results
return [textBlock, ...imageBlocks]
} else {
@@ -51,11 +46,7 @@ Otherwise, if you have not completed the task and do not need additional informa
return formatImagesIntoBlocks(images)
},
formatFilesList: (
absolutePath: string,
files: string[],
didHitLimit: boolean,
): string => {
formatFilesList: (absolutePath: string, files: string[], didHitLimit: boolean): string => {
const sorted = files
.map((file) => {
// convert absolute path to relative path
@@ -66,11 +57,7 @@ Otherwise, if you have not completed the task and do not need additional informa
.sort((a, b) => {
const aParts = a.split("/") // only works if we use toPosix first
const bParts = b.split("/")
for (
let i = 0;
i < Math.min(aParts.length, bParts.length);
i++
) {
for (let i = 0; i < Math.min(aParts.length, bParts.length); i++) {
if (aParts[i] !== bParts[i]) {
// If one is a directory and the other isn't at this level, sort the directory first
if (i + 1 === aParts.length && i + 1 < bParts.length) {
@@ -94,27 +81,16 @@ Otherwise, if you have not completed the task and do not need additional informa
return `${sorted.join(
"\n",
)}\n\n(File list truncated. Use list_files on specific subdirectories if you need to explore further.)`
} else if (
sorted.length === 0 ||
(sorted.length === 1 && sorted[0] === "")
) {
} else if (sorted.length === 0 || (sorted.length === 1 && sorted[0] === "")) {
return "No files found."
} else {
return sorted.join("\n")
}
},
createPrettyPatch: (
filename = "file",
oldStr?: string,
newStr?: string,
) => {
createPrettyPatch: (filename = "file", oldStr?: string, newStr?: string) => {
// strings cannot be undefined or diff throws exception
const patch = diff.createPatch(
filename.toPosix(),
oldStr || "",
newStr || "",
)
const patch = diff.createPatch(filename.toPosix(), oldStr || "", newStr || "")
const lines = patch.split("\n")
const prettyPatchLines = lines.slice(4)
return prettyPatchLines.join("\n")
@@ -122,9 +98,7 @@ Otherwise, if you have not completed the task and do not need additional informa
}
// to avoid circular dependency
const formatImagesIntoBlocks = (
images?: string[],
): Anthropic.ImageBlockParam[] => {
const formatImagesIntoBlocks = (images?: string[]): Anthropic.ImageBlockParam[] => {
return images
? images.map((dataUrl) => {
// data:image/png;base64,base64string
+5 -18
View File
@@ -362,17 +362,11 @@ ${
.join("\n\n")
const templates = server.resourceTemplates
?.map(
(template) =>
`- ${template.uriTemplate} (${template.name}): ${template.description}`,
)
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
.join("\n")
const resources = server.resources
?.map(
(resource) =>
`- ${resource.uri} (${resource.name}): ${resource.description}`,
)
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
.join("\n")
const config = JSON.parse(server.config)
@@ -380,12 +374,8 @@ ${
return (
`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
(tools ? `\n\n### Available Tools\n${tools}` : "") +
(templates
? `\n\n### Resource Templates\n${templates}`
: "") +
(resources
? `\n\n### Direct Resources\n${resources}`
: "")
(templates ? `\n\n### Resource Templates\n${templates}` : "") +
(resources ? `\n\n### Direct Resources\n${resources}` : "")
)
})
.join("\n\n")}`
@@ -899,10 +889,7 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
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. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
export function addUserInstructions(
settingsCustomInstructions?: string,
clineRulesFileInstructions?: string,
) {
export function addUserInstructions(settingsCustomInstructions?: string, clineRulesFileInstructions?: string) {
let customInstructions = ""
if (settingsCustomInstructions) {
customInstructions += settingsCustomInstructions + "\n\n"
+103 -344
View File
@@ -16,19 +16,13 @@ import { ApiProvider, ModelInfo } from "../../shared/api"
import { findLast } from "../../shared/array"
import { ExtensionMessage, ExtensionState } from "../../shared/ExtensionMessage"
import { HistoryItem } from "../../shared/HistoryItem"
import {
ClineCheckpointRestore,
WebviewMessage,
} from "../../shared/WebviewMessage"
import { ClineCheckpointRestore, WebviewMessage } from "../../shared/WebviewMessage"
import { fileExistsAtPath } from "../../utils/fs"
import { Cline } from "../Cline"
import { openMention } from "../mentions"
import { getNonce } from "./getNonce"
import { getUri } from "./getUri"
import {
AutoApprovalSettings,
DEFAULT_AUTO_APPROVAL_SETTINGS,
} from "../../shared/AutoApprovalSettings"
import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "../../shared/AutoApprovalSettings"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@@ -125,10 +119,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
public static getVisibleInstance(): ClineProvider | undefined {
return findLast(
Array.from(this.activeInstances),
(instance) => instance.view?.visible === true,
)
return findLast(Array.from(this.activeInstances), (instance) => instance.view?.visible === true)
}
resolveWebviewView(
@@ -219,22 +210,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async initClineWithTask(task?: string, images?: string[]) {
await this.clearTask() // ensures that an exising task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
const { apiConfiguration, customInstructions, autoApprovalSettings } =
await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
autoApprovalSettings,
customInstructions,
task,
images,
)
const { apiConfiguration, customInstructions, autoApprovalSettings } = await this.getState()
this.cline = new Cline(this, apiConfiguration, autoApprovalSettings, customInstructions, task, images)
}
async initClineWithHistoryItem(historyItem: HistoryItem) {
await this.clearTask()
const { apiConfiguration, customInstructions, autoApprovalSettings } =
await this.getState()
const { apiConfiguration, customInstructions, autoApprovalSettings } = await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
@@ -267,21 +249,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// then convert it to a uri we can use in the webview.
// The CSS file from the React build output
const stylesUri = getUri(webview, this.context.extensionUri, [
"webview-ui",
"build",
"static",
"css",
"main.css",
])
const stylesUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "css", "main.css"])
// The JS file from the React build output
const scriptUri = getUri(webview, this.context.extensionUri, [
"webview-ui",
"build",
"static",
"js",
"main.js",
])
const scriptUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "js", "main.js"])
// The codicon font from the React build output
// https://github.com/microsoft/vscode-extension-samples/blob/main/webview-codicons-sample/src/extension.ts
@@ -369,25 +339,19 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// gui relies on model info to be up-to-date to provide the most accurate pricing, so we need to fetch the latest details on launch.
// we do this for all users since many users switch between api providers and if they were to switch back to openrouter it would be showing outdated model info if we hadn't retrieved the latest at this point
// (see normalizeApiConfiguration > openrouter)
this.refreshOpenRouterModels().then(
async (openRouterModels) => {
if (openRouterModels) {
// update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration } =
await this.getState()
if (apiConfiguration.openRouterModelId) {
await this.updateGlobalState(
"openRouterModelInfo",
openRouterModels[
apiConfiguration
.openRouterModelId
],
)
await this.postStateToWebview()
}
this.refreshOpenRouterModels().then(async (openRouterModels) => {
if (openRouterModels) {
// update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration } = await this.getState()
if (apiConfiguration.openRouterModelId) {
await this.updateGlobalState(
"openRouterModelInfo",
openRouterModels[apiConfiguration.openRouterModelId],
)
await this.postStateToWebview()
}
},
)
}
})
break
case "newTask":
// Code that should run in response to the hello message command
@@ -398,10 +362,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// Could also do this in extension .ts
//this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
// initializing new instance of Cline will make sure that any agentically running promises in old instance don't affect our new task. this essentially creates a fresh slate for the new task
await this.initClineWithTask(
message.text,
message.images,
)
await this.initClineWithTask(message.text, message.images)
break
case "apiConfiguration":
if (message.apiConfiguration) {
@@ -432,92 +393,33 @@ export class ClineProvider implements vscode.WebviewViewProvider {
openRouterModelId,
openRouterModelInfo,
} = message.apiConfiguration
await this.updateGlobalState(
"apiProvider",
apiProvider,
)
await this.updateGlobalState(
"apiModelId",
apiModelId,
)
await this.updateGlobalState("apiProvider", apiProvider)
await this.updateGlobalState("apiModelId", apiModelId)
await this.storeSecret("apiKey", apiKey)
await this.storeSecret(
"openRouterApiKey",
openRouterApiKey,
)
await this.storeSecret("openRouterApiKey", openRouterApiKey)
await this.storeSecret("awsAccessKey", awsAccessKey)
await this.storeSecret("awsSecretKey", awsSecretKey)
await this.storeSecret(
"awsSessionToken",
awsSessionToken,
)
await this.storeSecret("awsSessionToken", awsSessionToken)
await this.updateGlobalState("awsRegion", awsRegion)
await this.updateGlobalState(
"awsUseCrossRegionInference",
awsUseCrossRegionInference,
)
await this.updateGlobalState(
"vertexProjectId",
vertexProjectId,
)
await this.updateGlobalState(
"vertexRegion",
vertexRegion,
)
await this.updateGlobalState(
"openAiBaseUrl",
openAiBaseUrl,
)
await this.updateGlobalState("awsUseCrossRegionInference", awsUseCrossRegionInference)
await this.updateGlobalState("vertexProjectId", vertexProjectId)
await this.updateGlobalState("vertexRegion", vertexRegion)
await this.updateGlobalState("openAiBaseUrl", openAiBaseUrl)
await this.storeSecret("openAiApiKey", openAiApiKey)
await this.updateGlobalState(
"openAiModelId",
openAiModelId,
)
await this.updateGlobalState(
"ollamaModelId",
ollamaModelId,
)
await this.updateGlobalState(
"ollamaBaseUrl",
ollamaBaseUrl,
)
await this.updateGlobalState(
"lmStudioModelId",
lmStudioModelId,
)
await this.updateGlobalState(
"lmStudioBaseUrl",
lmStudioBaseUrl,
)
await this.updateGlobalState(
"anthropicBaseUrl",
anthropicBaseUrl,
)
await this.updateGlobalState("openAiModelId", openAiModelId)
await this.updateGlobalState("ollamaModelId", ollamaModelId)
await this.updateGlobalState("ollamaBaseUrl", ollamaBaseUrl)
await this.updateGlobalState("lmStudioModelId", lmStudioModelId)
await this.updateGlobalState("lmStudioBaseUrl", lmStudioBaseUrl)
await this.updateGlobalState("anthropicBaseUrl", anthropicBaseUrl)
await this.storeSecret("geminiApiKey", geminiApiKey)
await this.storeSecret(
"openAiNativeApiKey",
openAiNativeApiKey,
)
await this.storeSecret(
"deepSeekApiKey",
deepSeekApiKey,
)
await this.updateGlobalState(
"azureApiVersion",
azureApiVersion,
)
await this.updateGlobalState(
"openRouterModelId",
openRouterModelId,
)
await this.updateGlobalState(
"openRouterModelInfo",
openRouterModelInfo,
)
await this.storeSecret("openAiNativeApiKey", openAiNativeApiKey)
await this.storeSecret("deepSeekApiKey", deepSeekApiKey)
await this.updateGlobalState("azureApiVersion", azureApiVersion)
await this.updateGlobalState("openRouterModelId", openRouterModelId)
await this.updateGlobalState("openRouterModelInfo", openRouterModelInfo)
if (this.cline) {
this.cline.api = buildApiHandler(
message.apiConfiguration,
)
this.cline.api = buildApiHandler(message.apiConfiguration)
}
}
await this.postStateToWebview()
@@ -527,23 +429,15 @@ export class ClineProvider implements vscode.WebviewViewProvider {
break
case "autoApprovalSettings":
if (message.autoApprovalSettings) {
await this.updateGlobalState(
"autoApprovalSettings",
message.autoApprovalSettings,
)
await this.updateGlobalState("autoApprovalSettings", message.autoApprovalSettings)
if (this.cline) {
this.cline.autoApprovalSettings =
message.autoApprovalSettings
this.cline.autoApprovalSettings = message.autoApprovalSettings
}
await this.postStateToWebview()
}
break
case "askResponse":
this.cline?.handleWebviewAskResponse(
message.askResponse!,
message.text,
message.images,
)
this.cline?.handleWebviewAskResponse(message.askResponse!, message.text, message.images)
break
case "clearTask":
// newTask will start a new task with a given task text, while clear task resets the current session and allows for a new task to be started
@@ -551,10 +445,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.postStateToWebview()
break
case "didShowAnnouncement":
await this.updateGlobalState(
"lastShownAnnouncementId",
this.latestAnnouncementId,
)
await this.updateGlobalState("lastShownAnnouncementId", this.latestAnnouncementId)
await this.postStateToWebview()
break
case "selectImages":
@@ -583,18 +474,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.resetState()
break
case "requestOllamaModels":
const ollamaModels = await this.getOllamaModels(
message.text,
)
const ollamaModels = await this.getOllamaModels(message.text)
this.postMessageToWebview({
type: "ollamaModels",
ollamaModels,
})
break
case "requestLmStudioModels":
const lmStudioModels = await this.getLmStudioModels(
message.text,
)
const lmStudioModels = await this.getLmStudioModels(message.text)
this.postMessageToWebview({
type: "lmStudioModels",
lmStudioModels,
@@ -614,10 +501,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
break
case "checkpointDiff": {
if (message.number) {
await this.cline?.presentMultifileDiff(
message.number,
false,
)
await this.cline?.presentMultifileDiff(message.number, false)
}
break
}
@@ -626,30 +510,19 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// cancel task waits for any open editor to be reverted and starts a new cline instance
if (message.number) {
// wait for messages to be loaded
await pWaitFor(
() => this.cline?.isInitialized === true,
{
timeout: 3_000,
},
).catch(() => {
console.error(
"Failed to init new cline instance",
)
await pWaitFor(() => this.cline?.isInitialized === true, {
timeout: 3_000,
}).catch(() => {
console.error("Failed to init new cline instance")
})
// NOTE: cancelTask awaits abortTask, which awaits diffViewProvider.revertChanges, which reverts any edited files, allowing us to reset to a checkpoint rather than running into a state where the revertChanges function is called alongside or after the checkpoint reset
await this.cline?.restoreCheckpoint(
message.number,
message.text! as ClineCheckpointRestore,
)
await this.cline?.restoreCheckpoint(message.number, message.text! as ClineCheckpointRestore)
}
break
}
case "taskCompletionViewChanges": {
if (message.number) {
await this.cline?.presentMultifileDiff(
message.number,
true,
)
await this.cline?.presentMultifileDiff(message.number, true)
}
break
}
@@ -657,8 +530,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.cancelTask()
break
case "openMcpSettings": {
const mcpSettingsFilePath =
await this.mcpHub?.getMcpSettingsFilePath()
const mcpSettingsFilePath = await this.mcpHub?.getMcpSettingsFilePath()
if (mcpSettingsFilePath) {
openFile(mcpSettingsFilePath)
}
@@ -668,10 +540,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
try {
await this.mcpHub?.restartConnection(message.text!)
} catch (error) {
console.error(
`Failed to retry connection for ${message.text}:`,
error,
)
console.error(`Failed to retry connection for ${message.text}:`, error)
}
break
}
@@ -693,10 +562,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
console.error("Failed to abort task", error)
}
await pWaitFor(
() =>
this.cline === undefined ||
this.cline.isStreaming === false ||
this.cline.didFinishAbortingStream,
() => this.cline === undefined || this.cline.isStreaming === false || this.cline.didFinishAbortingStream,
{
timeout: 3_000,
},
@@ -714,10 +580,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async updateCustomInstructions(instructions?: string) {
// User may be clearing the field
await this.updateGlobalState(
"customInstructions",
instructions || undefined,
)
await this.updateGlobalState("customInstructions", instructions || undefined)
if (this.cline) {
this.cline.customInstructions = instructions || undefined
}
@@ -727,12 +590,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// MCP
async ensureMcpServersDirectoryExists(): Promise<string> {
const mcpServersDir = path.join(
os.homedir(),
"Documents",
"Cline",
"MCP",
)
const mcpServersDir = path.join(os.homedir(), "Documents", "Cline", "MCP")
try {
await fs.mkdir(mcpServersDir, { recursive: true })
} catch (error) {
@@ -742,10 +600,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async ensureSettingsDirectoryExists(): Promise<string> {
const settingsDir = path.join(
this.context.globalStorageUri.fsPath,
"settings",
)
const settingsDir = path.join(this.context.globalStorageUri.fsPath, "settings")
await fs.mkdir(settingsDir, { recursive: true })
return settingsDir
}
@@ -761,8 +616,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return []
}
const response = await axios.get(`${baseUrl}/api/tags`)
const modelsArray =
response.data?.models?.map((model: any) => model.name) || []
const modelsArray = response.data?.models?.map((model: any) => model.name) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
@@ -781,8 +635,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return []
}
const response = await axios.get(`${baseUrl}/v1/models`)
const modelsArray =
response.data?.data?.map((model: any) => model.id) || []
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
@@ -795,10 +648,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async handleOpenRouterCallback(code: string) {
let apiKey: string
try {
const response = await axios.post(
"https://openrouter.ai/api/v1/auth/keys",
{ code },
)
const response = await axios.post("https://openrouter.ai/api/v1/auth/keys", { code })
if (response.data && response.data.key) {
apiKey = response.data.key
} else {
@@ -823,43 +673,27 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
private async ensureCacheDirectoryExists(): Promise<string> {
const cacheDir = path.join(
this.context.globalStorageUri.fsPath,
"cache",
)
const cacheDir = path.join(this.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
async readOpenRouterModels(): Promise<
Record<string, ModelInfo> | undefined
> {
const openRouterModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.openRouterModels,
)
async readOpenRouterModels(): Promise<Record<string, ModelInfo> | undefined> {
const openRouterModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.openRouterModels)
const fileExists = await fileExistsAtPath(openRouterModelsFilePath)
if (fileExists) {
const fileContents = await fs.readFile(
openRouterModelsFilePath,
"utf8",
)
const fileContents = await fs.readFile(openRouterModelsFilePath, "utf8")
return JSON.parse(fileContents)
}
return undefined
}
async refreshOpenRouterModels() {
const openRouterModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.openRouterModels,
)
const openRouterModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.openRouterModels)
let models: Record<string, ModelInfo> = {}
try {
const response = await axios.get(
"https://openrouter.ai/api/v1/models",
)
const response = await axios.get("https://openrouter.ai/api/v1/models")
/*
{
"id": "anthropic/claude-3.5-sonnet",
@@ -898,8 +732,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const modelInfo: ModelInfo = {
maxTokens: rawModel.top_provider?.max_completion_tokens,
contextWindow: rawModel.context_length,
supportsImages:
rawModel.architecture?.modality?.includes("image"),
supportsImages: rawModel.architecture?.modality?.includes("image"),
supportsPromptCache: false,
inputPrice: parsePrice(rawModel.pricing?.prompt),
outputPrice: parsePrice(rawModel.pricing?.completion),
@@ -981,32 +814,15 @@ export class ClineProvider implements vscode.WebviewViewProvider {
uiMessagesFilePath: string
apiConversationHistory: Anthropic.MessageParam[]
}> {
const history =
((await this.getGlobalState("taskHistory")) as
| HistoryItem[]
| undefined) || []
const history = ((await this.getGlobalState("taskHistory")) as HistoryItem[] | undefined) || []
const historyItem = history.find((item) => item.id === id)
if (historyItem) {
const taskDirPath = path.join(
this.context.globalStorageUri.fsPath,
"tasks",
id,
)
const apiConversationHistoryFilePath = path.join(
taskDirPath,
GlobalFileNames.apiConversationHistory,
)
const uiMessagesFilePath = path.join(
taskDirPath,
GlobalFileNames.uiMessages,
)
const fileExists = await fileExistsAtPath(
apiConversationHistoryFilePath,
)
const taskDirPath = path.join(this.context.globalStorageUri.fsPath, "tasks", id)
const apiConversationHistoryFilePath = path.join(taskDirPath, GlobalFileNames.apiConversationHistory)
const uiMessagesFilePath = path.join(taskDirPath, GlobalFileNames.uiMessages)
const fileExists = await fileExistsAtPath(apiConversationHistoryFilePath)
if (fileExists) {
const apiConversationHistory = JSON.parse(
await fs.readFile(apiConversationHistoryFilePath, "utf8"),
)
const apiConversationHistory = JSON.parse(await fs.readFile(apiConversationHistoryFilePath, "utf8"))
return {
historyItem,
taskDirPath,
@@ -1035,8 +851,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async exportTaskWithId(id: string) {
const { historyItem, apiConversationHistory } =
await this.getTaskWithId(id)
const { historyItem, apiConversationHistory } = await this.getTaskWithId(id)
await downloadTask(historyItem.ts, apiConversationHistory)
}
@@ -1045,18 +860,12 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.clearTask()
}
const {
taskDirPath,
apiConversationHistoryFilePath,
uiMessagesFilePath,
} = await this.getTaskWithId(id)
const { taskDirPath, apiConversationHistoryFilePath, uiMessagesFilePath } = await this.getTaskWithId(id)
await this.deleteTaskFromState(id)
// Delete the task files
const apiConversationHistoryFileExists = await fileExistsAtPath(
apiConversationHistoryFilePath,
)
const apiConversationHistoryFileExists = await fileExistsAtPath(apiConversationHistoryFilePath)
if (apiConversationHistoryFileExists) {
await fs.unlink(apiConversationHistoryFilePath)
}
@@ -1064,10 +873,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
if (uiMessagesFileExists) {
await fs.unlink(uiMessagesFilePath)
}
const legacyMessagesFilePath = path.join(
taskDirPath,
"claude_messages.json",
)
const legacyMessagesFilePath = path.join(taskDirPath, "claude_messages.json")
if (await fileExistsAtPath(legacyMessagesFilePath)) {
await fs.unlink(legacyMessagesFilePath)
}
@@ -1078,10 +884,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
try {
await fs.rm(checkpointsDir, { recursive: true, force: true })
} catch (error) {
console.error(
`Failed to delete checkpoints directory for task ${id}:`,
error,
)
console.error(`Failed to delete checkpoints directory for task ${id}:`, error)
// Continue with deletion of task directory - don't throw since this is a cleanup operation
}
}
@@ -1091,10 +894,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async deleteTaskFromState(id: string) {
// Remove the task from history
const taskHistory =
((await this.getGlobalState("taskHistory")) as
| HistoryItem[]
| undefined) || []
const taskHistory = ((await this.getGlobalState("taskHistory")) as HistoryItem[] | undefined) || []
const updatedTaskHistory = taskHistory.filter((task) => task.id !== id)
await this.updateGlobalState("taskHistory", updatedTaskHistory)
@@ -1108,31 +908,18 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async getStateToPostToWebview(): Promise<ExtensionState> {
const {
apiConfiguration,
lastShownAnnouncementId,
customInstructions,
taskHistory,
autoApprovalSettings,
} = await this.getState()
const { apiConfiguration, lastShownAnnouncementId, customInstructions, taskHistory, autoApprovalSettings } =
await this.getState()
return {
version: this.context.extension?.packageJSON?.version ?? "",
apiConfiguration,
customInstructions,
uriScheme: vscode.env.uriScheme,
currentTaskItem: this.cline?.taskId
? (taskHistory || []).find(
(item) => item.id === this.cline?.taskId,
)
: undefined,
checkpointTrackerErrorMessage:
this.cline?.checkpointTrackerErrorMessage,
currentTaskItem: this.cline?.taskId ? (taskHistory || []).find((item) => item.id === this.cline?.taskId) : undefined,
checkpointTrackerErrorMessage: this.cline?.checkpointTrackerErrorMessage,
clineMessages: this.cline?.clineMessages || [],
taskHistory: (taskHistory || [])
.filter((item) => item.ts && item.task)
.sort((a, b) => b.ts - a.ts),
shouldShowAnnouncement:
lastShownAnnouncementId !== this.latestAnnouncementId,
taskHistory: (taskHistory || []).filter((item) => item.ts && item.task).sort((a, b) => b.ts - a.ts),
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
autoApprovalSettings,
}
}
@@ -1220,9 +1007,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory,
autoApprovalSettings,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<
ApiProvider | undefined
>,
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
this.getSecret("apiKey") as Promise<string | undefined>,
this.getSecret("openRouterApiKey") as Promise<string | undefined>,
@@ -1230,51 +1015,27 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getSecret("awsSecretKey") as Promise<string | undefined>,
this.getSecret("awsSessionToken") as Promise<string | undefined>,
this.getGlobalState("awsRegion") as Promise<string | undefined>,
this.getGlobalState("awsUseCrossRegionInference") as Promise<
boolean | undefined
>,
this.getGlobalState("vertexProjectId") as Promise<
string | undefined
>,
this.getGlobalState("awsUseCrossRegionInference") as Promise<boolean | undefined>,
this.getGlobalState("vertexProjectId") as Promise<string | undefined>,
this.getGlobalState("vertexRegion") as Promise<string | undefined>,
this.getGlobalState("openAiBaseUrl") as Promise<string | undefined>,
this.getSecret("openAiApiKey") as Promise<string | undefined>,
this.getGlobalState("openAiModelId") as Promise<string | undefined>,
this.getGlobalState("ollamaModelId") as Promise<string | undefined>,
this.getGlobalState("ollamaBaseUrl") as Promise<string | undefined>,
this.getGlobalState("lmStudioModelId") as Promise<
string | undefined
>,
this.getGlobalState("lmStudioBaseUrl") as Promise<
string | undefined
>,
this.getGlobalState("anthropicBaseUrl") as Promise<
string | undefined
>,
this.getGlobalState("lmStudioModelId") as Promise<string | undefined>,
this.getGlobalState("lmStudioBaseUrl") as Promise<string | undefined>,
this.getGlobalState("anthropicBaseUrl") as Promise<string | undefined>,
this.getSecret("geminiApiKey") as Promise<string | undefined>,
this.getSecret("openAiNativeApiKey") as Promise<string | undefined>,
this.getSecret("deepSeekApiKey") as Promise<string | undefined>,
this.getGlobalState("azureApiVersion") as Promise<
string | undefined
>,
this.getGlobalState("openRouterModelId") as Promise<
string | undefined
>,
this.getGlobalState("openRouterModelInfo") as Promise<
ModelInfo | undefined
>,
this.getGlobalState("lastShownAnnouncementId") as Promise<
string | undefined
>,
this.getGlobalState("customInstructions") as Promise<
string | undefined
>,
this.getGlobalState("taskHistory") as Promise<
HistoryItem[] | undefined
>,
this.getGlobalState("autoApprovalSettings") as Promise<
AutoApprovalSettings | undefined
>,
this.getGlobalState("azureApiVersion") as Promise<string | undefined>,
this.getGlobalState("openRouterModelId") as Promise<string | undefined>,
this.getGlobalState("openRouterModelInfo") as Promise<ModelInfo | undefined>,
this.getGlobalState("lastShownAnnouncementId") as Promise<string | undefined>,
this.getGlobalState("customInstructions") as Promise<string | undefined>,
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
this.getGlobalState("autoApprovalSettings") as Promise<AutoApprovalSettings | undefined>,
])
let apiProvider: ApiProvider
@@ -1322,14 +1083,12 @@ export class ClineProvider implements vscode.WebviewViewProvider {
lastShownAnnouncementId,
customInstructions,
taskHistory,
autoApprovalSettings:
autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
}
}
async updateTaskHistory(item: HistoryItem): Promise<HistoryItem[]> {
const history =
((await this.getGlobalState("taskHistory")) as HistoryItem[]) || []
const history = ((await this.getGlobalState("taskHistory")) as HistoryItem[]) || []
const existingItemIndex = history.findIndex((h) => h.id === item.id)
if (existingItemIndex !== -1) {
history[existingItemIndex] = item
+1 -2
View File
@@ -8,8 +8,7 @@
*/
export function getNonce() {
let text = ""
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
+1 -5
View File
@@ -10,10 +10,6 @@ import { Uri, Webview } from "vscode"
* @param pathList An array of strings representing the path to a file/resource
* @returns A URI pointing to the file/resource
*/
export function getUri(
webview: Webview,
extensionUri: Uri,
pathList: string[],
) {
export function getUri(webview: Webview, extensionUri: Uri, pathList: string[]) {
return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList))
}