Compare commits

...

35 Commits

Author SHA1 Message Date
Elephant Lumps 5e803ec473 Merge branch 'main' into add-open-disk-conversation-button 2025-06-01 13:35:59 -07:00
Elephant Lumps cafcb7f5d5 change icon due to lack of artistic freedom 2025-06-01 13:34:06 -07:00
Ara 079d05c2cc Fixing OpenAI compatible to support cache token display (#3957)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-01 05:55:31 +05:30
Ara acc795ed69 Fix pricing and token counting for Xai Provider for the new Grok 3 family of models (#3956) 2025-05-31 11:49:29 -07:00
Elon Gliksberg 1aaa30ecce Closing MCP processes when app terminates. (#3876) 2025-05-31 01:44:03 -07:00
Sarah Fortune f7e5398ac8 Fix warnings for protobuf object literals (#3948)
Create protobuf objects with .create()
2025-05-31 01:35:29 -07:00
Elephant Lumps 1409c2d3cc changeset 2025-05-31 00:58:16 -07:00
Elephant Lumps dce3b11f8b add open disk conversation history button 2025-05-31 00:57:31 -07:00
Gustavo A. Rodríguez Suárez 89f35b0800 Fix undefined type during chunk streaming (#1464)
* Fix undefined type when parsing response chunk in stream

* Fix undefined type when parsing response chunk in stream

* remove Cline.ts changes

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-05-31 00:02:28 -07:00
Sarah Fortune d7f30fdf73 Make the no-grpc-client-object-literals linter rule an error for the webview-ui (#3947)
* Fix linter warnings in the webview (part 2)

Replace protobus calls using object literals to use Message.create({...})

Fix incorrect property name detected after this change in webview-ui/src/components/settings/SettingsView.tsx

Optimised imports in vscode.

* formatting

* feat(lint): Add custom ESLint rules for protobuf type checking

Add two custom ESLint rules to enforce proper usage patterns when creating protobuf objects.

Using .create() to build protobufs ensures that the protobuf is type checked when it is created. Protobufs created using
object literals are not type checked,  which can lead to subtle bugs and type mismatches. The linter rules detect when protobufs are created without using .create() or .fromPartial().

- no-protobuf-object-literals: Enforces the use of `.create()` or `.fromPartial()` methods instead of object literals when creating protobuf types.

```
/Users/sjf/cline/src/shared/proto-conversions/state/chat-settings-conversion.ts
   9:9  warning  Use ChatSettings.create() or ChatSettings.fromPartial() instead of object literal for protobuf type
Found: return {
             mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT,
             preferredLanguage: chatSettings.preferredLanguage,
             openAiReasoningEffort: chatSettings.openAIReasoningEffort,
     }
  Suggestion: ChatSettings.create({
             mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT,
             preferredLanguage: chatSettings.preferredLanguage,
             openAiReasoningEffort: chatSettings.openAIReasoningEffort,
     })
```

- no-grpc-client-object-literals: Enforces proper protobuf creation for gRPC service client parameters. This needs a separate rule
because the type signatures of the ServiceClients methods are too generic to be detected by the previous rule.

```
/Users/sjf/cline/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx
   41:62  warning  Use the appropriate protobuf .create() or .fromPartial() method instead of object literal for gRPC client parameters.
Found: McpServiceClient.addRemoteMcpServer({
                             serverName: serverName.trim(),
                             serverUrl: serverUrl.trim(),
                     })
```

These rules help maintain code quality by enforcing consistent patterns for working with protocol buffers throughout the codebase, reducing potential runtime errors from improper message construction.

* Update test

* Add custom eslint rules to new webview-ui config

* Only include webview grpc ServiceClient check

* Fix lint errors

* formatting

* Update package.json

* Make the no-grpc-client-object-literals linter rule an error for the webview-ui

Fix the last occurrence of this issue.

* formatting
2025-05-30 20:31:14 -07:00
Sarah Fortune 0c6a4f9452 feat(lint): Add custom ESLint rules for protobuf type checking for protobus ServiceClients (#3946)
* Fix linter warnings in the webview (part 2)

Replace protobus calls using object literals to use Message.create({...})

Fix incorrect property name detected after this change in webview-ui/src/components/settings/SettingsView.tsx

Optimised imports in vscode.

* formatting

* feat(lint): Add custom ESLint rules for protobuf type checking

Add two custom ESLint rules to enforce proper usage patterns when creating protobuf objects.

Using .create() to build protobufs ensures that the protobuf is type checked when it is created. Protobufs created using
object literals are not type checked,  which can lead to subtle bugs and type mismatches. The linter rules detect when protobufs are created without using .create() or .fromPartial().

- no-protobuf-object-literals: Enforces the use of `.create()` or `.fromPartial()` methods instead of object literals when creating protobuf types.

```
/Users/sjf/cline/src/shared/proto-conversions/state/chat-settings-conversion.ts
   9:9  warning  Use ChatSettings.create() or ChatSettings.fromPartial() instead of object literal for protobuf type
Found: return {
             mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT,
             preferredLanguage: chatSettings.preferredLanguage,
             openAiReasoningEffort: chatSettings.openAIReasoningEffort,
     }
  Suggestion: ChatSettings.create({
             mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT,
             preferredLanguage: chatSettings.preferredLanguage,
             openAiReasoningEffort: chatSettings.openAIReasoningEffort,
     })
```

- no-grpc-client-object-literals: Enforces proper protobuf creation for gRPC service client parameters. This needs a separate rule
because the type signatures of the ServiceClients methods are too generic to be detected by the previous rule.

```
/Users/sjf/cline/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx
   41:62  warning  Use the appropriate protobuf .create() or .fromPartial() method instead of object literal for gRPC client parameters.
Found: McpServiceClient.addRemoteMcpServer({
                             serverName: serverName.trim(),
                             serverUrl: serverUrl.trim(),
                     })
```

These rules help maintain code quality by enforcing consistent patterns for working with protocol buffers throughout the codebase, reducing potential runtime errors from improper message construction.

* Update test

* Add custom eslint rules to new webview-ui config

* Only include webview grpc ServiceClient check

* Fix lint errors

* formatting

* Update package-lock.json

* Update package.json
2025-05-30 20:19:04 -07:00
Toshii c1e38e649c file selection proto input type change (#3945)
* request type

* changeset
2025-05-30 20:09:41 -07:00
Sarah Fortune b8a65a446a Fix linter warnings in the webview (part 2) (#3943)
* Fix linter warnings in the webview (part 2)

Replace protobus calls using object literals to use Message.create({...})

Fix incorrect property name detected after this change in webview-ui/src/components/settings/SettingsView.tsx

Optimised imports in vscode.

* Fix typo

* formatting
2025-05-30 19:37:27 -07:00
Daniel Steigman 6626124bef fix(bedrock): resolve AWS credential caching issue with Identity Manager (#3936)
* fix(bedrock): resolve AWS credential caching issue with Identity Manager

- Add ignoreCache option for profile-based authentication to detect external credential file changes
- Implement smart caching for manual credentials with 5-minute TTL to maintain performance
- Add configuration hash-based cache invalidation for manual credential changes
- Add invalidateCredentialCache() method for error recovery scenarios

Fixes issue where AWS Identity Manager credential updates were not detected,
requiring extension restart. Profile-based authentication now always reads
fresh credentials while manual credentials maintain performance through caching.

Resolves credential refresh issues reported by users using AWS Identity Manager
with role-based authentication workflows.

* Potential fix for code scanning alert no. 66: Use of a broken or weak cryptographic algorithm

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* merge conflict

* updated to fixe the original medrock issue

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-05-30 19:11:20 -07:00
Sarah Fortune 80f67c3c89 Fix linter warning for Protobus ServiceClient calls using object literals. (#3942)
Fix linter warnings in the first half of the webview.
2025-05-30 18:53:01 -07:00
Sarah Fortune 01afe5ec53 Use the same version of eslint for the webview as for the cline package. (#3940)
The webview and the cline package were using different version of eslint,
which makes it difficult to use custom rules because the webview version wants the rules as
ES modules, but the cline version wants commonJS modules.

Switch the webview to use the same version as the cline package.

Switch the webview eslint JS config to the json config file.
2025-05-30 18:43:34 -07:00
Evan 83928ccecc Add edit tool definition (#3939)
* add ls file tool description, parsing, and return formatting

* add json tool definition and remove extra '.'

* changeset

* use separate function for new format

* using json

* add grep tool new format

* add editTool definition

* removed changeset

* removed changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-30 16:10:33 -07:00
Sarah Fortune 38a1179e62 Rename SecretStore.storeSecret to SecretStore.store (#3897)
Apparently ChatGPT can't follow the SDK docs.
2025-05-30 15:45:17 -07:00
Sarah Fortune e0f9eeaa79 Use the webview-ui linter during npm run lint (#3938)
The webview-ui has an existing eslint config, but it was not being run as part of `npm run lint` command. Start running the webview specific linter (the top level linter doesn't run on tsx files, and webview linter has react specific checks).
Fix lint errors in slash-commands file.
2025-05-30 15:21:34 -07:00
Andrei Eternal f10a82916f Warn about rosetta on osx in build-protos (#3400)
* warn about rosetta on osx in build-protos

* make one console log better

* format

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
Co-authored-by: Andrei Eternal <eternal@cline.bot>
2025-05-30 15:05:07 -07:00
Tomás Barreiro da12437251 fix: update the model list when the client requests a refresh (#3882)
* update the model list when the client refreshes

* Refactor and use the grpc response instead of a webview message
2025-05-30 14:28:58 -07:00
Donovan Sydow fb3012f778 add llama4 models, and mis/codestral models to vertex api (#3474)
* add llama4 models, and mis/codestral models to vertex api

* update mistral context window sizes

* changeset

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-05-30 14:23:54 -07:00
pashpashpash 8336831d8f read tool + write tool + webfetch tool + question tool + usemcp tool + list code definition names tool + access MCP resource tool + load mcp documentation tool + attempt completion tool + browser tool + new task tool (#3925) 2025-05-30 13:16:37 -07:00
KevinTurnbull ec064426b3 Minimal change to respect Ollama Context Window Size (#3880)
* Respect the CtxNum setting for Ollama Models

Currently since the context window size isn't respected for Ollama models - the LLM does a naive truncation which removes important details. This leads to the model entering endless loops or making unsupported edits when operating as an agent.

* small change

* changeset

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-05-30 01:45:47 -07:00
canvrno 8f72bf11f7 optionsResponse protobus migration/removal (#3860) 2025-05-29 22:47:22 -07:00
pashpashpash 915cf76f85 Pashpashpash/bash tool (#3894)
* bashTool

* prettier

* alignment

* bashtool cont

* bash tool cont

* modularizing prompt a bit

* bash tool working

* bash tool now getting cwd

* bashTool

* forgot .name

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-29 20:09:07 -07:00
Toshii f1fef24f25 support xlsx and csv (#3922) 2025-05-29 18:41:21 -07:00
Peter Dave Hello ceb0900bf6 Update xaiModels and xaiDefaultModelId in src/shared/api.ts (#3814) 2025-05-29 18:29:30 -07:00
Toshii cc9fc9bd1f update chat box ui (#3868)
* chat area

* changeset

* arrow

* nit

* tailwind
2025-05-29 13:23:59 -07:00
Ara dcf59bc29f Fix Title for Cline on Windows (#3917)
* Fix Title for Cline on Windows

* Fix Title for Cline on Windows

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-30 01:04:54 +05:30
Caleb Eom 5c3e7a38d4 Scroll to message onclick from task timeline (#3890)
* Scroll to message onclick from task timeline

* version

* fixing ellipsis-dev's suggestion on potential infinite loop
2025-05-29 00:49:08 -07:00
github-actions[bot] d6ccbcdf22 v3.17.8 Release Notes
v3.17.8 Release Notes
2025-05-28 23:01:23 -07:00
pashpashpash e4e03fa0dd reverting timeout if no first chunk (#3899)
* reverting timeout if no first chunk

* Create fresh-days-end.md

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-05-28 21:04:48 -07:00
pashpashpash 10892670be exact antml (#3891)
* exact antml

* only one invoke

* linter warnings

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 19:12:26 -07:00
Evan 3c7a42c35d Add grep tool new format (#3893)
* add ls file tool description, parsing, and return formatting

* add json tool definition and remove extra '.'

* changeset

* use separate function for new format

* using json

* add grep tool new format

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 18:32:18 -07:00
145 changed files with 7392 additions and 1908 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
add models to vertex ai
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Update `xaiModels` object and `xaiDefaultModelId` in `src/shared/api.ts`
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fixing token counting for xai provider
-6
View File
@@ -1,6 +0,0 @@
---
"claude-dev": patch
---
browserConnectionResult protobus migration/removal
+7
View File
@@ -0,0 +1,7 @@
---
"claude-dev": patch
---
fix(bedrock): Use ignoreCache for profile-based AWS credential loading
Ensures that AWS Bedrock provider always fetches fresh credentials when using IAM profiles by setting `ignoreCache: true` for `fromNodeProviderChain`. This resolves issues where externally updated credentials (e.g., by AWS Identity Manager) were not detected by Cline, requiring an extension restart. Manual credential handling remains unchanged.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
add suppport for parsing csv and xlsx
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Refatored system prompt with switch capabilities
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add dev only button to open task conversation history
@@ -2,4 +2,4 @@
"claude-dev": minor
---
Add newly formatted LS tool
update chat box ui
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
bug fix for ollama
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
update the openrouter model list when refreshing
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix Title for windows in cline
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
scroll to task timeline
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Added alt readTool & writeTool tool calls
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
optionsResponse protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
change proto type
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
System prompt switching for Claude4 models
+3 -2
View File
@@ -5,7 +5,7 @@
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"plugins": ["@typescript-eslint", "eslint-rules"],
"rules": {
"@typescript-eslint/naming-convention": [
"warn",
@@ -19,7 +19,8 @@
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"react-hooks/exhaustive-deps": "off"
"react-hooks/exhaustive-deps": "off",
"eslint-rules/no-grpc-client-object-literals": "error"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
-1
View File
@@ -5,4 +5,3 @@ webview-ui/build/
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
src/core/prompts/model_prompts/jsonToolToXml.ts
+4
View File
@@ -1,5 +1,9 @@
# Changelog
## [3.17.8]
- Fix bug where terminal would get stuck and output "capture failure"
## [3.17.7]
- Fix diff editing reliability for Claude 4 family models by adding constraints to prevent errors with large replacements
@@ -0,0 +1,174 @@
const { RuleTester: GrpcRuleTester } = require("eslint")
const grpcRule = require("../no-grpc-client-object-literals")
const grpcRuleTester = new GrpcRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
grpcRuleTester.run("no-grpc-client-object-literals", grpcRule, {
valid: [
// Valid case: Using .create() method with gRPC client
{
code: `
import { TogglePlanActModeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: {
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
},
})
);
`,
},
// Valid case: Using .fromPartial() method with gRPC client
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.fromPartial({
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: chatSettings,
})
);
`,
},
// Valid case: Regular function call with object literal (not a gRPC client)
{
code: `
function processData(data) {
console.log(data);
}
processData({
id: 123,
name: 'test',
});
`,
},
// Valid case: Using proper nested protobuf objects
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using proper nested protobuf objects
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
const request = TogglePlanActModeRequest.create({
chatSettings: chatSettings,
});
StateServiceClient.togglePlanActMode(request);
`,
},
// Valid case: Object literal in second parameter (should not be checked)
{
code: `
import { StateSubscribeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const request = StateSubscribeRequest.create({
topics: ['apiConfig', 'tasks']
});
// Second parameter is an object literal but should not trigger the rule
StateServiceClient.subscribe(request, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
},
],
invalid: [
// Invalid case: Using object literal directly with gRPC client
{
code: `
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal with nested properties
{
code: `
import { ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 1,
preferredLanguage: 'fr',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Nested object literal in protobuf create method
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using nested object literal instead of ChatSettings.create()
const request = TogglePlanActModeRequest.create({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
StateServiceClient.togglePlanActMode(request);
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Object literal as first parameter to subscribe method
{
code: `
import { StateServiceClient } from '../services/grpc-client';
// First parameter is an object literal, which should trigger the rule
StateServiceClient.subscribe({
topics: ['apiConfig', 'tasks']
}, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
],
})
+16
View File
@@ -0,0 +1,16 @@
// eslint-rules/index.js
const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals")
module.exports = {
rules: {
"no-grpc-client-object-literals": noGrpcClientObjectLiterals,
},
configs: {
recommended: {
plugins: ["local"],
rules: {
"local/no-grpc-client-object-literals": "error",
},
},
},
}
@@ -0,0 +1,216 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
module.exports = createRule({
name: "no-grpc-client-object-literals",
meta: {
type: "problem",
docs: {
description:
"Enforce using .create() or .fromPartial() for gRPC service client parameters instead of object literals",
recommended: "error",
},
messages: {
useProtobufMethod:
"Use the appropriate protobuf .create() or .fromPartial() method instead of " +
"object literal for gRPC client parameters.\n" +
"Found: {{code}}\n" +
"gRPC client methods should always receive properly created protobuf objects.",
},
schema: [],
},
defaultOptions: [],
create(context) {
// Check if a name matches the gRPC service client pattern using regex
// Must start with an uppercase letter and end with ServiceClient
const isGrpcServiceClient = (name) => {
return typeof name === "string" && /^[A-Z].*ServiceClient$/.test(name)
}
const safeObjectExpressions = new Map() // Track object expressions in create/fromPartial calls
return {
// Skip object literals inside create() or fromPartial() method calls
CallExpression(node) {
if (
node.callee &&
node.callee.type === "MemberExpression" &&
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
node.arguments.length > 0 &&
node.arguments[0].type === "ObjectExpression"
) {
// Track this object expression as being used with create/fromPartial
safeObjectExpressions.set(node.arguments[0], { isProblematic: false })
}
},
// Track create/fromPartial calls that contain nested object literals
"CallExpression[callee.type='MemberExpression'][callee.property.name=/^(create|fromPartial)$/]"(node) {
if (node.arguments.length > 0 && node.arguments[0].type === "ObjectExpression") {
// Track problematic nested object literals
const nestedObjectLiterals = new Map() // Map of object expressions to their containing property paths
// Search for nested object literals
const queue = [
...node.arguments[0].properties.map((prop) => ({
property: prop,
path: prop.key && prop.key.name ? prop.key.name : "unknown",
})),
]
while (queue.length > 0) {
const { property, path } = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// If this is an object literal, mark it as problematic
if (property.value.type === "ObjectExpression") {
nestedObjectLiterals.set(property.value, path)
// Add nested properties to queue
queue.push(
...property.value.properties.map((prop) => ({
property: prop,
path: `${path}.${prop.key && prop.key.name ? prop.key.name : "unknown"}`,
})),
)
}
}
// For each problematic nested object, track it with its path
nestedObjectLiterals.forEach((path, objectExpr) => {
safeObjectExpressions.set(objectExpr, {
isProblematic: true,
path: path,
parentNode: node,
})
})
}
},
// Check calls to gRPC service clients
"CallExpression[callee.type='MemberExpression']"(node) {
// Get the object (left side) of the member expression
const callee = node.callee
if (callee.object && callee.object.type === "Identifier") {
const objectName = callee.object.name
// Check if this is a call to one of our gRPC service clients
if (isGrpcServiceClient(objectName)) {
// Only check the first argument of gRPC service client calls
if (node.arguments.length > 0) {
const arg = node.arguments[0] // Only check the first parameter
if (arg.type === "ObjectExpression" && !safeObjectExpressions.has(arg)) {
// This is an object literal being passed directly to a gRPC client
const sourceCode = context.getSourceCode()
const callText = sourceCode.getText(node).trim()
context.report({
node: arg,
messageId: "useProtobufMethod",
data: {
code: callText,
},
})
} else if (arg.type === "ObjectExpression") {
// Search for nested object literals that aren't protected
const queue = [...arg.properties]
while (queue.length > 0) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// Check value
if (
property.value.type === "ObjectExpression" &&
!safeObjectExpressions.has(property.value)
) {
// Found a nested object literal
const sourceCode = context.getSourceCode()
const propertyText = sourceCode.getText(property).trim()
context.report({
node: property.value,
messageId: "useProtobufMethod",
data: {
code: `${objectName}.${callee.property.name}(... ${propertyText} ...)`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
} else if (arg.type === "Identifier") {
// This is a variable - check if it references a problematic protobuf object
const varName = arg.name
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
// Find the variable declaration
const variable = scope.variables.find((v) => v.name === varName)
if (variable && variable.references && variable.references.length > 0) {
// Look for definitions
const def = variable.defs.find(
(d) => d.node && d.node.type === "VariableDeclarator" && d.node.init,
)
if (
def &&
def.node.init.type === "CallExpression" &&
def.node.init.callee.type === "MemberExpression" &&
(def.node.init.callee.property.name === "create" ||
def.node.init.callee.property.name === "fromPartial")
) {
// Flag if we find problematic nested object literals in this create/fromPartial call
const callText = sourceCode.getText(node).trim()
const initCallText = sourceCode.getText(def.node.init).trim()
// Check for nested object literals in init node
let foundNestedLiteral = false
if (
def.node.init.arguments.length > 0 &&
def.node.init.arguments[0].type === "ObjectExpression"
) {
// Find any nested object literals
const queue = [...def.node.init.arguments[0].properties]
while (queue.length > 0 && !foundNestedLiteral) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
if (property.value.type === "ObjectExpression") {
foundNestedLiteral = true
context.report({
node,
messageId: "useProtobufMethod",
data: {
code: `${callText} - using request created with nested object literal at: ${property.key.name}`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
}
}
}
}
}
}
}
},
}
},
})
+2479
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "eslint-plugin-eslint-rules",
"version": "1.0.0",
"description": "Custom ESLint rules for Cline",
"main": "index.js",
"scripts": {
"test": "mocha --no-config --require ts-node/register __tests__/**/*.test.ts"
},
"keywords": [
"eslint",
"eslintplugin"
],
"author": "Cline Bot Inc.",
"license": "Apache-2.0",
"dependencies": {
"@typescript-eslint/utils": "^8.33.0"
},
"devDependencies": {
"@types/eslint": "^8.0.0",
"@types/mocha": "^10.0.7",
"@types/node": "^20.0.0",
"@typescript-eslint/parser": "^7.14.1",
"eslint": "^8.57.0",
"mocha": "^10.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
},
"peerDependencies": {
"eslint": ">=8.0.0"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist",
"resolveJsonModule": true,
"declaration": true
},
"include": ["**/*.ts", "**/*.js", "**/*.tsx", "__tests__/**/*"],
"exclude": ["node_modules", "dist"]
}
+1675 -49
View File
File diff suppressed because it is too large Load Diff
+7 -10
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.17.7",
"version": "3.17.8",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -58,13 +58,7 @@
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "isWindows"
},
{
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "isLinux || !isMac && !isWindows"
"when": "!isMac"
}
]
},
@@ -285,7 +279,7 @@
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint",
"check-types": "npm run protos && tsc --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && cd webview-ui && npm run lint",
"format": "prettier . --check",
"format:fix": "prettier . --write",
"test": "npm-run-all test:unit test:integration",
@@ -322,13 +316,15 @@
"@types/turndown": "^5.0.5",
"@types/vscode": "^1.84.0",
"@typescript-eslint/eslint-plugin": "^7.14.1",
"@typescript-eslint/parser": "^7.11.0",
"@typescript-eslint/parser": "^7.18.0",
"@typescript-eslint/utils": "^8.33.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"chai": "^4.3.10",
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
"eslint": "^8.57.0",
"eslint-plugin-eslint-rules": "file:eslint-rules",
"grpc-tools": "^1.13.0",
"husky": "^9.1.7",
"mintlify": "^4.0.515",
@@ -373,6 +369,7 @@
"clone-deep": "^4.0.1",
"default-shell": "^2.2.0",
"diff": "^5.2.0",
"exceljs": "^4.4.0",
"execa": "^9.5.2",
"fast-deep-equal": "^3.1.3",
"firebase": "^11.2.0",
+36
View File
@@ -6,11 +6,44 @@ import { fileURLToPath } from "url"
import { execSync } from "child_process"
import { globby } from "globby"
import chalk from "chalk"
import os from "os"
import { createRequire } from "module"
const require = createRequire(import.meta.url)
const protoc = path.join(require.resolve("grpc-tools"), "../bin/protoc")
// Check for Apple Silicon compatibility
function checkAppleSiliconCompatibility() {
// Only run check on macOS
if (process.platform !== "darwin") {
return
}
// Check if running on Apple Silicon
const cpuArchitecture = os.arch()
if (cpuArchitecture === "arm64") {
try {
// Check if Rosetta is installed
const rosettaCheck = execSync('/usr/bin/pgrep oahd || echo "NOT_INSTALLED"').toString().trim()
if (rosettaCheck === "NOT_INSTALLED") {
console.log(chalk.yellow("Detected Apple Silicon (ARM64) architecture."))
console.log(
chalk.red("Rosetta 2 is NOT installed. The npm version of protoc is not compatible with Apple Silicon."),
)
console.log(chalk.cyan("Please install Rosetta 2 using the following command:"))
console.log(chalk.cyan(" softwareupdate --install-rosetta --agree-to-license"))
console.log(chalk.red("Aborting build process."))
process.exit(1)
} else {
console.log(chalk.green("Rosetta 2 is installed. Continuing with build."))
}
} catch (error) {
console.log(chalk.yellow("Could not determine Rosetta installation status. Proceeding anyway."))
}
}
}
const __filename = fileURLToPath(import.meta.url)
const SCRIPT_DIR = path.dirname(__filename)
const ROOT_DIR = path.resolve(SCRIPT_DIR, "..")
@@ -42,6 +75,9 @@ const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(RO
async function main() {
console.log(chalk.bold.blue("Starting Protocol Buffer code generation..."))
// Check for Apple Silicon compatibility before proceeding
checkAppleSiliconCompatibility()
// Define output directories
const TS_OUT_DIR = path.join(ROOT_DIR, "src", "shared", "proto")
+4 -1
View File
@@ -33,7 +33,7 @@ service FileService {
rpc selectImages(EmptyRequest) returns (StringArray);
// Select images and other files from the file system and returns as data URLs & paths respectively
rpc selectFiles(EmptyRequest) returns (StringArrays);
rpc selectFiles(BooleanRequest) returns (StringArrays);
// Convert URIs to workspace-relative paths
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
@@ -52,6 +52,9 @@ service FileService {
// Refreshes all rule toggles (Cline, External, and Workflows)
rpc refreshRules(EmptyRequest) returns (RefreshedRules);
// Opens a task's conversation history file on disk
rpc openTaskHistory(StringRequest) returns (Empty);
}
// Response for refreshRules operation
+1 -1
View File
@@ -133,7 +133,7 @@ export class AnthropicHandler implements ApiHandler {
}
for await (const chunk of stream) {
switch (chunk.type) {
switch (chunk?.type) {
case "message_start":
// tells us cache reads/writes/input/output
const usage = chunk.message.usage
+13 -2
View File
@@ -120,7 +120,7 @@ export class AwsBedrockHandler implements ApiHandler {
)
for await (const chunk of stream) {
switch (chunk.type) {
switch (chunk?.type) {
case "message_start":
const usage = chunk.message.usage
yield {
@@ -223,8 +223,19 @@ export class AwsBedrockHandler implements ApiHandler {
secretAccessKey: string
sessionToken?: string
}> {
// Configure provider options
const providerOptions: any = {}
if (this.options.awsUseProfile) {
// For profile-based auth, always use ignoreCache to detect credential file changes
// This solves the AWS Identity Manager issue where credential files change externally
providerOptions.ignoreCache = true
if (this.options.awsProfile) {
providerOptions.profile = this.options.awsProfile
}
}
// Create AWS credentials by executing an AWS provider chain
const providerChain = fromNodeProviderChain()
const providerChain = fromNodeProviderChain(providerOptions)
return await AwsBedrockHandler.withTempEnv(
() => {
AwsBedrockHandler.setEnv("AWS_REGION", this.options.awsRegion)
+3 -1
View File
@@ -80,7 +80,9 @@ export class OllamaHandler implements ApiHandler {
getModel(): { id: string; info: ModelInfo } {
return {
id: this.options.ollamaModelId || "",
info: openAiModelInfoSaneDefaults,
info: this.options.ollamaApiOptionsCtxNum
? { ...openAiModelInfoSaneDefaults, contextWindow: Number(this.options.ollamaApiOptionsCtxNum) || 32768 }
: openAiModelInfoSaneDefaults,
}
}
}
+4
View File
@@ -98,6 +98,10 @@ export class OpenAiHandler implements ApiHandler {
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,
}
}
}
+1 -1
View File
@@ -154,7 +154,7 @@ export class VertexHandler implements ApiHandler {
}
for await (const chunk of stream) {
switch (chunk.type) {
switch (chunk?.type) {
case "message_start":
const usage = chunk.message.usage
yield {
+2 -2
View File
@@ -58,10 +58,10 @@ export class XAIHandler implements ApiHandler {
if (chunk.usage) {
yield {
type: "usage",
inputTokens: 0,
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
cacheReadTokens: chunk.usage.prompt_cache_hit_tokens || 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
// @ts-ignore-next-line
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
}
+1
View File
@@ -27,6 +27,7 @@ export const toolUseNames = [
"condense",
"report_bug",
"new_rule",
"web_fetch",
] as const
// Converts array of tool call names into a union type ("execute_command" | "read_file" | ...)
@@ -558,6 +558,134 @@ export function parseAssistantMessageV3(assistantMessage: string): AssistantMess
partial: true,
}
}
// If this is a Grep invoke, create a search_files tool
if (currentInvokeName === "Grep") {
currentToolUse = {
type: "tool_use",
name: "search_files",
params: {},
partial: true,
}
}
if (currentInvokeName === "Bash") {
currentToolUse = {
type: "tool_use",
name: "execute_command",
params: {},
partial: true,
}
}
if (currentInvokeName === "Read") {
currentToolUse = {
type: "tool_use",
name: "read_file",
params: {},
partial: true,
}
}
if (currentInvokeName === "Write") {
currentToolUse = {
type: "tool_use",
name: "write_to_file",
params: {},
partial: true,
}
}
if (currentInvokeName === "WebFetch") {
currentToolUse = {
type: "tool_use",
name: "web_fetch",
params: {},
partial: true,
}
}
if (currentInvokeName === "AskQuestion") {
currentToolUse = {
type: "tool_use",
name: "ask_followup_question",
params: {},
partial: true,
}
}
if (currentInvokeName === "UseMCPTool") {
currentToolUse = {
type: "tool_use",
name: "use_mcp_tool",
params: {},
partial: true,
}
}
if (currentInvokeName === "AccessMCPResource") {
currentToolUse = {
type: "tool_use",
name: "access_mcp_resource",
params: {},
partial: true,
}
}
if (currentInvokeName === "ListCodeDefinitionNames") {
currentToolUse = {
type: "tool_use",
name: "list_code_definition_names",
params: {},
partial: true,
}
}
if (currentInvokeName === "PlanModeRespond") {
currentToolUse = {
type: "tool_use",
name: "plan_mode_respond",
params: {},
partial: true,
}
}
if (currentInvokeName === "LoadMcpDocumentation") {
currentToolUse = {
type: "tool_use",
name: "load_mcp_documentation",
params: {},
partial: true,
}
}
if (currentInvokeName === "AttemptCompletion") {
currentToolUse = {
type: "tool_use",
name: "attempt_completion",
params: {},
partial: true,
}
}
if (currentInvokeName === "BrowserAction") {
currentToolUse = {
type: "tool_use",
name: "browser_action",
params: {},
partial: true,
}
}
if (currentInvokeName === "NewTask") {
currentToolUse = {
type: "tool_use",
name: "new_task",
params: {},
partial: true,
}
}
continue
}
}
@@ -599,6 +727,100 @@ export function parseAssistantMessageV3(assistantMessage: string): AssistantMess
currentToolUse.params["recursive"] = "false"
}
if (currentToolUse && currentInvokeName === "Read" && currentParameterName === "file_path") {
currentToolUse.params["path"] = value
}
if (currentToolUse && currentInvokeName === "PlanModeRespond" && currentParameterName === "response") {
currentToolUse.params["response"] = value
}
if (currentToolUse && currentInvokeName === "WebFetch" && currentParameterName === "url") {
currentToolUse.params["url"] = value
}
if (currentToolUse && currentInvokeName === "ListCodeDefinitionNames" && currentParameterName === "path") {
currentToolUse.params["path"] = value
}
if (currentToolUse && currentInvokeName === "NewTask" && currentParameterName === "context") {
currentToolUse.params["context"] = value
}
// Map parameter to tool params for Grep
if (currentToolUse && currentInvokeName === "Grep") {
if (currentParameterName === "pattern") {
currentToolUse.params["regex"] = value
} else if (currentParameterName === "path") {
currentToolUse.params["path"] = value
} else if (currentParameterName === "include") {
currentToolUse.params["file_pattern"] = value
}
}
if (currentToolUse && currentInvokeName === "Bash") {
if (currentParameterName === "command") {
currentToolUse.params["command"] = value
} else if (currentParameterName === "requires_approval") {
currentToolUse.params["requires_approval"] = value === "true" ? "true" : "false"
}
}
if (currentToolUse && currentInvokeName === "Write") {
if (currentParameterName === "file_path") {
currentToolUse.params["path"] = value
} else if (currentParameterName === "content") {
currentToolUse.params["content"] = value
}
}
if (currentToolUse && currentInvokeName === "AskQuestion") {
if (currentParameterName === "question") {
currentToolUse.params["question"] = value
} else if (currentParameterName === "options") {
currentToolUse.params["options"] = value
}
}
if (currentToolUse && currentInvokeName === "UseMCPTool") {
if (currentParameterName === "server_name") {
currentToolUse.params["server_name"] = value
} else if (currentParameterName === "tool_name") {
currentToolUse.params["tool_name"] = value
} else if (currentParameterName === "arguments") {
currentToolUse.params["arguments"] = value
}
}
if (currentToolUse && currentInvokeName === "AccessMCPResource") {
if (currentParameterName === "server_name") {
currentToolUse.params["server_name"] = value
} else if (currentParameterName === "uri") {
currentToolUse.params["uri"] = value
}
}
if (currentToolUse && currentInvokeName === "AttemptCompletion") {
if (currentParameterName === "result") {
currentToolUse.params["result"] = value
}
if (currentParameterName === "command") {
currentToolUse.params["command"] = value
}
}
if (currentToolUse && currentInvokeName === "BrowserAction") {
if (currentParameterName === "action") {
currentToolUse.params["action"] = value
} else if (currentParameterName === "url") {
currentToolUse.params["url"] = value
} else if (currentParameterName === "coordinate") {
currentToolUse.params["coordinate"] = value
} else if (currentParameterName === "text") {
currentToolUse.params["text"] = value
}
}
currentParameterName = ""
continue
}
@@ -611,7 +833,24 @@ export function parseAssistantMessageV3(assistantMessage: string): AssistantMess
assistantMessage.startsWith(isInvokeClose, currentCharIndex - isInvokeClose.length + 1)
) {
// If we have a tool use from this invoke, finalize it
if (currentToolUse && currentInvokeName === "LS") {
if (
currentToolUse &&
(currentInvokeName === "LS" ||
currentInvokeName === "Grep" ||
currentInvokeName === "Bash" ||
currentInvokeName === "Read" ||
currentInvokeName === "Write" ||
currentInvokeName === "WebFetch" ||
currentInvokeName === "AskQuestion" ||
currentInvokeName === "UseMCPTool" ||
currentInvokeName === "AccessMCPResource" ||
currentInvokeName === "ListCodeDefinitionNames" ||
currentInvokeName === "PlanModeRespond" ||
currentInvokeName === "LoadMcpDocumentation" ||
currentInvokeName === "AttemptCompletion" ||
currentInvokeName === "BrowserAction" ||
currentInvokeName === "NewTask")
) {
currentToolUse.partial = false
contentBlocks.push(currentToolUse)
currentToolUse = undefined
@@ -12,7 +12,7 @@ import { EmptyRequest, String } from "../../../shared/proto/common"
* @param controller The controller instance.
* @returns The login URL as a string.
*/
export async function accountLoginClicked(controller: Controller, unused: EmptyRequest): Promise<String> {
export async function accountLoginClicked(controller: Controller, _: EmptyRequest): Promise<String> {
// Generate nonce for state validation
const nonce = crypto.randomBytes(32).toString("hex")
await storeSecret(controller.context, "authNonce", nonce)
@@ -27,7 +27,7 @@ export async function accountLoginClicked(controller: Controller, unused: EmptyR
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
await vscode.env.openExternal(authUrl)
return {
return String.create({
value: authUrl.toString(),
}
})
}
@@ -1,4 +1,4 @@
import type { Empty } from "../../../shared/proto/common"
import { Empty } from "../../../shared/proto/common"
import type { EmptyRequest } from "../../../shared/proto/common"
import type { Controller } from "../index"
@@ -10,5 +10,5 @@ import type { Controller } from "../index"
*/
export async function accountLogoutClicked(controller: Controller, _request: EmptyRequest): Promise<Empty> {
await controller.handleSignOut()
return {}
return Empty.create({})
}
@@ -24,24 +24,24 @@ export async function discoverBrowser(controller: Controller, request: EmptyRequ
const browserSession = new BrowserSession(controller.context, browserSettings)
const result = await browserSession.testConnection(discoveredHost)
return {
return BrowserConnection.create({
success: true,
message: `Successfully discovered and connected to Chrome at ${discoveredHost}`,
endpoint: result.endpoint || "",
}
})
} else {
return {
return BrowserConnection.create({
success: false,
message:
"No Chrome instances found. Make sure Chrome is running with remote debugging enabled (--remote-debugging-port=9222).",
endpoint: "",
}
})
}
} catch (error) {
return {
return BrowserConnection.create({
success: false,
message: `Error discovering browser: ${error instanceof Error ? error.message : String(error)}`,
endpoint: "",
}
})
}
}
@@ -9,7 +9,7 @@ import { getAllExtensionState } from "@core/storage/state"
* @param request The request message
* @returns The browser connection info
*/
export async function getBrowserConnectionInfo(controller: Controller, request: EmptyRequest): Promise<BrowserConnectionInfo> {
export async function getBrowserConnectionInfo(controller: Controller, _: EmptyRequest): Promise<BrowserConnectionInfo> {
try {
// Get browser settings from extension state
const { browserSettings } = await getAllExtensionState(controller.context)
@@ -23,25 +23,25 @@ export async function getBrowserConnectionInfo(controller: Controller, request:
const connectionInfo = browserSession.getConnectionInfo()
// Convert from BrowserSession.BrowserConnectionInfo to proto.BrowserConnectionInfo
return {
return BrowserConnectionInfo.create({
isConnected: connectionInfo.isConnected,
isRemote: connectionInfo.isRemote,
host: connectionInfo.host || "", // Ensure host is never undefined
}
})
}
// Fallback to browser settings if no active browser session
return {
return BrowserConnectionInfo.create({
isConnected: false,
isRemote: !!browserSettings.remoteBrowserEnabled,
host: browserSettings.remoteBrowserHost || "",
}
})
} catch (error: unknown) {
console.error("Error getting browser connection info:", error)
return {
return BrowserConnectionInfo.create({
isConnected: false,
isRemote: false,
host: "",
}
})
}
}
@@ -10,21 +10,21 @@ import { BrowserSession } from "../../../services/browser/BrowserSession"
* @param request The empty request message
* @returns The detected Chrome path and whether it's bundled
*/
export async function getDetectedChromePath(controller: Controller, request: EmptyRequest): Promise<ChromePath> {
export async function getDetectedChromePath(controller: Controller, _: EmptyRequest): Promise<ChromePath> {
try {
const { browserSettings } = await getAllExtensionState(controller.context)
const browserSession = new BrowserSession(controller.context, browserSettings)
const result = await browserSession.getDetectedChromePath()
return {
return ChromePath.create({
path: result.path,
isBundled: result.isBundled,
}
})
} catch (error) {
console.error("Error getting detected Chrome path:", error)
return {
return ChromePath.create({
path: "",
isBundled: false,
}
})
}
}
@@ -8,7 +8,7 @@ import { BrowserSession } from "../../../services/browser/BrowserSession"
* @param request The empty request message
* @returns The browser relaunch result as a string message
*/
export async function relaunchChromeDebugMode(controller: Controller, request: EmptyRequest): Promise<StringMessage> {
export async function relaunchChromeDebugMode(controller: Controller, _: EmptyRequest): Promise<StringMessage> {
try {
const { browserSettings } = await controller.getStateToPostToWebview()
const browserSession = new BrowserSession(controller.context, browserSettings)
@@ -18,9 +18,9 @@ export async function relaunchChromeDebugMode(controller: Controller, request: E
// The actual result will be sent via postMessageToWebview in the BrowserSession.relaunchChromeDebugMode method
// Here we just return a message as a placeholder
return {
return StringMessage.create({
value: "Chrome relaunch initiated",
}
})
} catch (error) {
throw new Error(`Error relaunching Chrome: ${error instanceof Error ? error.message : globalThis.String(error)}`)
}
@@ -24,40 +24,40 @@ export async function testBrowserConnection(controller: Controller, request: Str
if (discoveredHost) {
// Test the connection to the discovered host
const result = await browserSession.testConnection(discoveredHost)
return {
return BrowserConnection.create({
success: result.success,
message: `Auto-discovered and tested connection to Chrome at ${discoveredHost}: ${result.message}`,
endpoint: result.endpoint || "",
}
})
} else {
return {
return BrowserConnection.create({
success: false,
message:
"No Chrome instances found on the network. Make sure Chrome is running with remote debugging enabled (--remote-debugging-port=9222).",
endpoint: "",
}
})
}
} catch (error) {
return {
return BrowserConnection.create({
success: false,
message: `Error during auto-discovery: ${error instanceof Error ? error.message : String(error)}`,
endpoint: "",
}
})
}
} else {
// Test the provided URL
const result = await browserSession.testConnection(text)
return {
return BrowserConnection.create({
success: result.success,
message: result.message,
endpoint: result.endpoint || "",
}
})
}
} catch (error) {
return {
return BrowserConnection.create({
success: false,
message: `Error testing connection: ${error instanceof Error ? error.message : String(error)}`,
endpoint: "",
}
})
}
}
@@ -50,13 +50,13 @@ export async function updateBrowserSettings(controller: Controller, request: Upd
// Post updated state to webview
await controller.postStateToWebview()
return {
return Boolean.create({
value: true,
}
})
} catch (error) {
console.error("Error updating browser settings:", error)
return {
return Boolean.create({
value: false,
}
})
}
}
@@ -18,5 +18,5 @@ export async function checkpointRestore(controller: Controller, request: Checkpo
// 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 controller.task?.restoreCheckpoint(request.number, request.restoreType as ClineCheckpointRestore, request.offset)
}
return {}
return Empty.create({})
}
@@ -0,0 +1,19 @@
import { Controller } from ".."
import { Empty, StringRequest } from "@shared/proto/common"
import { openFile as openFileIntegration } from "@integrations/misc/open-file"
import { FileMethodHandler } from "./index"
import path from "path"
/**
* Opens a file in the editor
* @param controller The controller instance
* @param request The request message containing the file path in the 'value' field
* @returns Empty response
*/
export const openTaskHistory: FileMethodHandler = async (controller: Controller, request: StringRequest): Promise<Empty> => {
const globalStoragePath = controller.context.globalStorageUri.fsPath
const taskHistoryPath = path.join(globalStoragePath, "tasks", request.value, "api_conversation_history.json")
if (request.value) {
openFileIntegration(taskHistoryPath)
}
return Empty.create()
}
+2 -2
View File
@@ -18,14 +18,14 @@ export async function refreshRules(controller: Controller, _request: EmptyReques
const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller.context, cwd)
const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller.context, cwd)
return {
return RefreshedRules.create({
globalClineRulesToggles: { toggles: globalToggles },
localClineRulesToggles: { toggles: localToggles },
localCursorRulesToggles: { toggles: cursorLocalToggles },
localWindsurfRulesToggles: { toggles: windsurfLocalToggles },
localWorkflowToggles: { toggles: localWorkflowToggles },
globalWorkflowToggles: { toggles: globalWorkflowToggles },
}
})
} catch (error) {
console.error("Failed to refresh rules:", error)
throw error
+4 -3
View File
@@ -1,4 +1,5 @@
import type { ToggleClineRuleRequest, ClineRulesToggles, ToggleClineRules } from "../../../shared/proto/file"
import { ToggleClineRules } from "../../../shared/proto/file"
import type { ToggleClineRuleRequest } from "../../../shared/proto/file"
import type { Controller } from "../index"
import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "../../../core/storage/state"
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
@@ -36,8 +37,8 @@ export async function toggleClineRule(controller: Controller, request: ToggleCli
const globalToggles = ((await getGlobalState(controller.context, "globalClineRulesToggles")) as AppClineRulesToggles) || {}
const localToggles = ((await getWorkspaceState(controller.context, "localClineRulesToggles")) as AppClineRulesToggles) || {}
return {
return ToggleClineRules.create({
globalClineRulesToggles: { toggles: globalToggles },
localClineRulesToggles: { toggles: localToggles },
}
})
}
+4 -3
View File
@@ -1,4 +1,5 @@
import type { ToggleCursorRuleRequest, ClineRulesToggles } from "../../../shared/proto/file"
import type { ToggleCursorRuleRequest } from "../../../shared/proto/file"
import { ClineRulesToggles } from "../../../shared/proto/file"
import type { Controller } from "../index"
import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state"
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
@@ -28,7 +29,7 @@ export async function toggleCursorRule(controller: Controller, request: ToggleCu
// Get the current state to return in the response
const cursorToggles = ((await getWorkspaceState(controller.context, "localCursorRulesToggles")) as AppClineRulesToggles) || {}
return {
return ClineRulesToggles.create({
toggles: cursorToggles,
}
})
}
@@ -1,4 +1,5 @@
import type { ToggleWindsurfRuleRequest, ClineRulesToggles } from "../../../shared/proto/file"
import type { ToggleWindsurfRuleRequest } from "../../../shared/proto/file"
import { ClineRulesToggles } from "../../../shared/proto/file"
import type { Controller } from "../index"
import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state"
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
@@ -26,5 +27,5 @@ export async function toggleWindsurfRule(controller: Controller, request: Toggle
await updateWorkspaceState(controller.context, "localWindsurfRulesToggles", toggles)
// Return the toggles directly
return { toggles: toggles }
return ClineRulesToggles.create({ toggles: toggles })
}
-8
View File
@@ -109,9 +109,7 @@ export class Controller {
- https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
*/
async dispose() {
this.outputChannel.appendLine("Disposing ClineProvider...")
await this.clearTask()
this.outputChannel.appendLine("Cleared task")
while (this.disposables.length) {
const x = this.disposables.pop()
if (x) {
@@ -120,7 +118,6 @@ export class Controller {
}
this.workspaceTracker.dispose()
this.mcpHub.dispose()
this.outputChannel.appendLine("Disposed all disposables")
console.error("Controller disposed")
}
@@ -285,11 +282,6 @@ export class Controller {
}
await this.postStateToWebview()
break
case "optionsResponse":
if (this.task) {
await this.task.handleWebviewAskResponse("messageResponse", message.text || "", [])
}
break
case "fetchUserCreditsData": {
await this.fetchUserCreditsData()
break
@@ -1,5 +1,6 @@
import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion"
import type { AddRemoteMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
import type { AddRemoteMcpServerRequest } from "../../../shared/proto/mcp"
import { McpServers } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
/**
@@ -23,7 +24,7 @@ export async function addRemoteMcpServer(controller: Controller, request: AddRem
const protoServers = convertMcpServersToProtoMcpServers(servers)
return { mcpServers: protoServers }
return McpServers.create({ mcpServers: protoServers })
} catch (error) {
console.error(`Failed to add remote MCP server ${request.serverName}:`, error)
+2 -2
View File
@@ -1,5 +1,5 @@
import type { Controller } from "../index"
import type { McpServers } from "../../../shared/proto/mcp"
import { McpServers } from "../../../shared/proto/mcp"
import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion"
import { StringRequest } from "@/shared/proto/common"
@@ -17,7 +17,7 @@ export async function deleteMcpServer(controller: Controller, request: StringReq
// Convert application types to protobuf types
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
return { mcpServers: protoServers }
return McpServers.create({ mcpServers: protoServers })
} catch (error) {
console.error(`Failed to delete MCP server: ${error}`)
throw error
@@ -1,5 +1,5 @@
import type { EmptyRequest } from "../../../shared/proto/common"
import type { McpMarketplaceCatalog } from "../../../shared/proto/mcp"
import { McpMarketplaceCatalog } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
/**
@@ -19,9 +19,9 @@ export async function refreshMcpMarketplace(controller: Controller, _request: Em
}
// Return empty catalog if nothing was fetched
return { items: [] }
return McpMarketplaceCatalog.create({ items: [] })
} catch (error) {
console.error("Failed to refresh MCP marketplace:", error)
return { items: [] }
return McpMarketplaceCatalog.create({ items: [] })
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
import type { McpServers } from "@shared/proto/mcp"
import { McpServers } from "@shared/proto/mcp"
import type { Controller } from "../index"
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { StringRequest } from "@/shared/proto/common"
@@ -16,7 +16,7 @@ export async function restartMcpServer(controller: Controller, request: StringRe
// Convert from McpServer[] to ProtoMcpServer[] ensuring all required fields are set
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
return { mcpServers: protoServers }
return McpServers.create({ mcpServers: protoServers })
} catch (error) {
console.error(`Failed to restart MCP server ${request.value}:`, error)
throw error
+3 -2
View File
@@ -1,4 +1,5 @@
import type { ToggleMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
import type { ToggleMcpServerRequest } from "../../../shared/proto/mcp"
import { McpServers } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion"
@@ -15,7 +16,7 @@ export async function toggleMcpServer(controller: Controller, request: ToggleMcp
// Convert from McpServer[] to ProtoMcpServer[] ensuring all required fields are set
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
return { mcpServers: protoServers }
return McpServers.create({ mcpServers: protoServers })
} catch (error) {
console.error(`Failed to toggle MCP server ${request.serverName}:`, error)
throw error
@@ -1,4 +1,5 @@
import type { ToggleToolAutoApproveRequest, McpServers } from "@shared/proto/mcp"
import type { ToggleToolAutoApproveRequest } from "@shared/proto/mcp"
import { McpServers } from "@shared/proto/mcp"
import type { Controller } from "../index"
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
@@ -15,7 +16,7 @@ export async function toggleToolAutoApprove(controller: Controller, request: Tog
(await controller.mcpHub?.toggleToolAutoApproveRPC(request.serverName, request.toolNames, request.autoApprove)) || []
// Convert application types to proto types
return { mcpServers: convertMcpServersToProtoMcpServers(mcpServers) }
return McpServers.create({ mcpServers: convertMcpServersToProtoMcpServers(mcpServers) })
} catch (error) {
console.error(`Failed to toggle tool auto-approve for ${request.serverName}:`, error)
throw error
+1 -1
View File
@@ -15,7 +15,7 @@ export async function updateMcpTimeout(controller: Controller, request: UpdateMc
console.log("mcpServers", mcpServers)
const convertedMcpServers = convertMcpServersToProtoMcpServers(mcpServers)
console.log("convertedMcpServers", convertedMcpServers)
return { mcpServers: convertedMcpServers }
return McpServers.create({ mcpServers: convertedMcpServers })
} else {
console.error("Server name and timeout are required")
throw new Error("Server name and timeout are required")
@@ -10,10 +10,7 @@ import { getSecret } from "@core/storage/state"
* @param request Empty request object
* @returns Response containing the Requesty models
*/
export async function refreshRequestyModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
export async function refreshRequestyModels(controller: Controller, _: EmptyRequest): Promise<OpenRouterCompatibleModelInfo> {
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
@@ -30,7 +27,7 @@ export async function refreshRequestyModels(
const response = await axios.get("https://router.requesty.ai/v1/models", { headers })
if (response.data?.data) {
for (const model of response.data.data) {
const modelInfo: OpenRouterModelInfo = {
const modelInfo: OpenRouterModelInfo = OpenRouterModelInfo.create({
maxTokens: model.max_output_tokens || undefined,
contextWindow: model.context_window,
supportsImages: model.supports_vision || undefined,
@@ -40,7 +37,7 @@ export async function refreshRequestyModels(
cacheWritesPrice: parsePrice(model.caching_price) || 0,
cacheReadsPrice: parsePrice(model.cached_price) || 0,
description: model.description,
}
})
models[model.id] = modelInfo
}
console.log("Requesty models fetched", models)
+3 -4
View File
@@ -2,7 +2,6 @@ import * as vscode from "vscode"
import { Controller } from "../index"
import { EmptyRequest } from "../../../shared/proto/common"
import { State } from "../../../shared/proto/state"
import { ExtensionState } from "../../../shared/ExtensionMessage"
/**
* Get the latest extension state
@@ -10,7 +9,7 @@ import { ExtensionState } from "../../../shared/ExtensionMessage"
* @param request The empty request
* @returns The current extension state
*/
export async function getLatestState(controller: Controller, request: EmptyRequest): Promise<State> {
export async function getLatestState(controller: Controller, _: EmptyRequest): Promise<State> {
// Get the state using the existing method
const state = await controller.getStateToPostToWebview()
@@ -18,7 +17,7 @@ export async function getLatestState(controller: Controller, request: EmptyReque
const stateJson = JSON.stringify(state)
// Return the state as a JSON string
return {
return State.create({
stateJson,
}
})
}
@@ -15,7 +15,7 @@ export async function updateTerminalConnectionTimeout(controller: Controller, re
if (typeof timeout === "number" && !isNaN(timeout) && timeout > 0) {
// Update the global state directly
await updateGlobalState(controller.context, "shellIntegrationTimeout", timeout)
return { value: timeout }
return Int64.create({ value: timeout })
} else {
console.warn(`Invalid shell integration timeout value received: ${timeout}. Expected a positive number.`)
throw new Error("Invalid timeout value. Expected a positive number.")
@@ -47,10 +47,10 @@ export async function deleteNonFavoritedTasks(
console.error("Error posting to webview:", webviewErr)
}
return {
return DeleteNonFavoritedTasksResults.create({
tasksPreserved: favoritedTasks.length,
tasksDeleted: deletedCount,
}
})
} catch (error) {
console.error("Error in deleteNonFavoritedTasks:", error)
throw error
+2 -2
View File
@@ -106,10 +106,10 @@ export async function getTaskHistory(controller: Controller, request: GetTaskHis
cacheReads: item.cacheReads || 0,
}))
return {
return TaskHistoryArray.create({
tasks,
totalCount,
}
})
} catch (error) {
console.error("Error in getTaskHistory:", error)
throw error
+4 -4
View File
@@ -28,7 +28,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
})
// Return task data for gRPC response
return {
return TaskResponse.create({
id: historyItem.id,
task: historyItem.task || "",
ts: historyItem.ts || 0,
@@ -39,7 +39,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
tokensOut: historyItem.tokensOut || 0,
cacheWrites: historyItem.cacheWrites || 0,
cacheReads: historyItem.cacheReads || 0,
}
})
}
// If not in global state, fetch from storage
@@ -54,7 +54,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
action: "chatButtonClicked",
})
return {
return TaskResponse.create({
id: fetchedItem.id,
task: fetchedItem.task || "",
ts: fetchedItem.ts || 0,
@@ -65,7 +65,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
tokensOut: fetchedItem.tokensOut || 0,
cacheWrites: fetchedItem.cacheWrites || 0,
cacheReads: fetchedItem.cacheReads || 0,
}
})
} catch (error) {
console.error("Error in showTaskWithId:", error)
throw error
@@ -6,7 +6,7 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa
if (!request.taskId || request.isFavorited === undefined) {
const errorMsg = `[toggleTaskFavorite] Invalid request: taskId or isFavorited missing`
console.error(errorMsg)
return {}
return Empty.create({})
}
try {
@@ -47,5 +47,5 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa
console.error("Error in toggleTaskFavorite:", error)
}
return {}
return Empty.create({})
}
@@ -1,4 +1,5 @@
import type { EmptyRequest, Boolean } from "../../../shared/proto/common"
import type { EmptyRequest } from "../../../shared/proto/common"
import { Boolean } from "../../../shared/proto/common"
import type { Controller } from "../index"
import { getGlobalState, updateGlobalState } from "../../storage/state"
@@ -21,9 +22,9 @@ export async function onDidShowAnnouncement(controller: Controller, _request: Em
// This replicates the same logic used in getStateToPostToWebview()
const shouldShowAnnouncement = lastShownAnnouncementId !== controller.latestAnnouncementId
return { value: shouldShowAnnouncement }
return Boolean.create({ value: shouldShowAnnouncement })
} catch (error) {
console.error("Failed to acknowledge announcement:", error)
return { value: false }
return Boolean.create({ value: false })
}
}
+5 -5
View File
@@ -9,21 +9,21 @@ import { detectImageUrl } from "@integrations/misc/link-preview"
* @param request The request containing the URL to check
* @returns A result indicating if the URL is an image and the URL that was checked
*/
export async function checkIsImageUrl(controller: Controller, request: StringRequest): Promise<IsImageUrl> {
export async function checkIsImageUrl(_: Controller, request: StringRequest): Promise<IsImageUrl> {
try {
const url = request.value || ""
// Check if the URL is an image
const isImage = await detectImageUrl(url)
return {
return IsImageUrl.create({
isImage,
url,
}
})
} catch (error) {
console.error(`Error checking if URL is an image: ${request.value}`, error)
return {
return IsImageUrl.create({
isImage: false,
url: request.value || "",
}
})
}
}
+69 -316
View File
@@ -9,6 +9,17 @@ import { bashToolDefinition } from "@core/tools/bashTool"
import { readToolDefinition } from "@core/tools/readTool"
import { writeToolDefinition } from "@core/tools/writeTool"
import {lsToolDefinition} from "@core/tools/lsTool"
import { grepToolDefinition } from "@core/tools/grepTool"
import {webFetchToolDefinition} from "@core/tools/webFetchTool"
import { askQuestionToolDefinition } from "@core/tools/askQuestionTool"
import { useMCPToolDefinition } from "@core/tools/useMcpTool"
import {listCodeDefinitionNamesToolDefinition} from "@core/tools/listCodeDefinitionNamesTool"
import {accessMcpResourceToolDefinition} from "@core/tools/accessMcpResourceTool"
import {planModeRespondToolDefinition} from "@core/tools/planModeRespondTool"
import {loadMcpDocumentationToolDefinition} from "@core/tools/loadMcpDocumentationTool"
import { attemptCompletionToolDefinition } from "@core/tools/attemptCompletionTool"
import {browserActionToolDefinition} from "@core/tools/browserActionTool"
import {newTaskToolDefinition} from "@core/tools/newTaskTool"
export const SYSTEM_PROMPT_CLAUDE4 = async (
cwd: string,
@@ -16,6 +27,13 @@ export const SYSTEM_PROMPT_CLAUDE4 = async (
mcpHub: McpHub,
browserSettings: BrowserSettings,
) => {
const bashTool = bashToolDefinition(cwd);
const readTool = readToolDefinition(cwd);
const writeTool = writeToolDefinition(cwd);
const listCodeDefinitionNamesTool = listCodeDefinitionNamesToolDefinition(cwd);
const loadMcpDocumentationTool = loadMcpDocumentationToolDefinition(useMCPToolDefinition.name, accessMcpResourceToolDefinition.name);
const browserActionTool = browserActionToolDefinition(browserSettings);
const systemPrompt = `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
@@ -34,49 +52,10 @@ Tool use is formatted using XML-style tags. The tool name is enclosed in opening
...
</tool_name>
For example:
<read_file>
<path>src/main.js</path>
</read_file>
Always adhere to this format for the tool use to ensure proper parsing and execution.
# Tools
## execute_command
Description: 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. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${cwd.toPosix()}
Parameters:
- command: (required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
- requires_approval: (required) 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:
<execute_command>
<command>Your command here</command>
<requires_approval>true or false</requires_approval>
</execute_command>
## 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.
Parameters:
- path: (required) The path of the file to read (relative to the current working directory ${cwd.toPosix()})
Usage:
<read_file>
<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 ${cwd.toPosix()})
- 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>
## replace_in_file
"Description: Return your edits as a JSON object with a "replacements" array. Each replacement should have "old_str" and "new_str" fields. The old_str must match exactly what's in the file (including whitespace, indentation and new lines). You can edit multiple lines, but please keep the replacements as simple as possible.
@@ -116,216 +95,7 @@ Usage:
</diff>
</replace_in_file>
## 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:
- path: (required) The path of the directory to search in (relative to the current working directory ${cwd.toPosix()}). This directory will be recursively searched.
- regex: (required) The regular expression pattern to search for. Uses Rust regex syntax.
- file_pattern: (optional) Glob pattern to filter files (e.g., '*.ts' for TypeScript files). If not provided, it will search all files (*).
Usage:
<search_files>
<path>Directory path here</path>
<regex>Your regex pattern here</regex>
<file_pattern>file pattern here (optional)</file_pattern>
</search_files>
## 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:
- path: (required) The path of the directory (relative to the current working directory ${cwd.toPosix()}) to list top level source code definitions for.
Usage:
<list_code_definition_names>
<path>Directory path here</path>
</list_code_definition_names>${
supportsBrowserUse
? `
## 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 **${browserSettings.viewport.width}x${browserSettings.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.
Parameters:
- action: (required) 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: \`<action>close</action>\`
- url: (optional) Use this for providing the URL for the \`launch\` action.
* Example: <url>https://example.com</url>
- coordinate: (optional) The X and Y coordinates for the \`click\` action. Coordinates should be within the **${browserSettings.viewport.width}x${browserSettings.viewport.height}** resolution.
* Example: <coordinate>450,300</coordinate>
- text: (optional) Use this for providing the text for the \`type\` action.
* Example: <text>Hello, world!</text>
Usage:
<browser_action>
<action>Action to perform (e.g., launch, click, type, scroll_down, scroll_up, close)</action>
<url>URL to launch the browser at (optional)</url>
<coordinate>x,y coordinates (optional)</coordinate>
<text>Text to type (optional)</text>
</browser_action>`
: ""
}
## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
- server_name: (required) The name of the MCP server providing the tool
- tool_name: (required) The name of the tool to execute
- arguments: (required) A JSON object containing the tool's input parameters, following the tool's input schema
Usage:
<use_mcp_tool>
<server_name>server name here</server_name>
<tool_name>tool name here</tool_name>
<arguments>
{
"param1": "value1",
"param2": "value2"
}
</arguments>
</use_mcp_tool>
## access_mcp_resource
Description: Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.
Parameters:
- server_name: (required) The name of the MCP server providing the resource
- uri: (required) The URI identifying the specific resource to access
Usage:
<access_mcp_resource>
<server_name>server name here</server_name>
<uri>resource URI here</uri>
</access_mcp_resource>
## ask_followup_question
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
Parameters:
- question: (required) The question to ask the user. This should be a clear, specific question that addresses the information you need.
- options: (optional) An array of 2-5 options for the user to choose from. 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.
Usage:
<ask_followup_question>
<question>Your question here</question>
<options>
Array of options here (optional), e.g. ["Option 1", "Option 2", "Option 3"]
</options>
</ask_followup_question>
## attempt_completion
Description: After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in <thinking></thinking> tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool.
Parameters:
- result: (required) The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.
- command: (optional) A CLI command to execute to show a live demo of the result to the user. For example, use \`open index.html\` to display a created html website, or \`open localhost:3000\` to display a locally running development server. But DO NOT use commands like \`echo\` or \`cat\` that merely print text. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
Usage:
<attempt_completion>
<result>
Your final result description here
</result>
<command>Command to demonstrate result (optional)</command>
</attempt_completion>
## new_task
Description: Request to create a new task with preloaded context covering the conversation with the user up to this point and key information for continuing with the new task. With this tool, you will create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions, with a focus on the most relevant information required for the new task.
Among other important areas of focus, this summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing with the new task. The user will be presented with a preview of your generated context and can choose to create a new task or keep chatting in the current conversation. The user may choose to start a new task at any point.
Parameters:
- Context: (required) The context to preload the new task with. If applicable based on the current task, this should include:
1. Current Work: Describe in detail what was being worked on prior to this request to create a new task. Pay special attention to the more recent messages / conversation.
2. Key Technical Concepts: List all important technical concepts, technologies, coding conventions, and frameworks discussed, which might be relevant for the new task.
3. Relevant Files and Code: If applicable, enumerate specific files and code sections examined, modified, or created for the task continuation. Pay special attention to the most recent messages and changes.
4. Problem Solving: Document problems solved thus far and any ongoing troubleshooting efforts.
5. Pending Tasks and Next Steps: Outline all pending tasks that you have explicitly been asked to work on, as well as list the next steps you will take for all outstanding work, if applicable. Include code snippets where they add clarity. For any next steps, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no information loss in context between tasks. It's important to be detailed here.
Usage:
<new_task>
<context>context to preload new task with</context>
</new_task>
## 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 be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. 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. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.
Parameters:
- response: (required) 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:
<plan_mode_respond>
<response>Your response here</response>
</plan_mode_respond>
## load_mcp_documentation
Description: Load documentation about creating MCP servers. This tool should be used when the user requests to create or install an MCP server (the user may ask you something along the lines of "add a tool" that does some function, in other words to create an MCP server that provides tools and resources that may connect to external APIs for example. You have the ability to create an MCP server and add it to a configuration file that will then expose the tools and resources for you to use with \`use_mcp_tool\` and \`access_mcp_resource\`). The documentation provides detailed information about the MCP server creation process, including setup instructions, best practices, and examples.
Parameters: None
Usage:
<load_mcp_documentation>
</load_mcp_documentation>
# Tool Use Examples
## Example 1: Requesting to execute a command
<execute_command>
<command>npm run dev</command>
<requires_approval>false</requires_approval>
</execute_command>
## Example 2: Requesting to create a new file
<write_to_file>
<path>src/frontend-config.json</path>
<content>
{
"apiEndpoint": "https://api.example.com",
"theme": {
"primaryColor": "#007bff",
"secondaryColor": "#6c757d",
"fontFamily": "Arial, sans-serif"
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": false
},
"version": "1.0.0"
}
</content>
</write_to_file>
## Example 3: Creating a new task
<new_task>
<context>
1. Current Work:
[Detailed description]
2. Key Technical Concepts:
- [Concept 1]
- [Concept 2]
- [...]
3. Relevant Files and Code:
- [File Name 1]
- [Summary of why this file is important]
- [Summary of the changes made to this file, if any]
- [Important Code Snippet]
- [File Name 2]
- [Important Code Snippet]
- [...]
4. Problem Solving:
[Detailed description]
5. Pending Tasks and Next Steps:
- [Task 1 details & next steps]
- [Task 2 details & next steps]
- [...]
</context>
</new_task>
## Example 4: Requesting to make targeted edits to a file
## Example 2: Requesting to make targeted edits to a file
<replace_in_file>
@@ -350,37 +120,6 @@ Usage:
</diff>
</replace_in_file>
## Example 5: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 6: Another example of using an MCP tool (where the server name is a unique identifier such as a URL)
<use_mcp_tool>
<server_name>github.com/modelcontextprotocol/servers/tree/main/src/github</server_name>
<tool_name>create_issue</tool_name>
<arguments>
{
"owner": "octocat",
"repo": "hello-world",
"title": "Found a bug",
"body": "I'm having a problem with this.",
"labels": ["bug", "help wanted"],
"assignees": ["octocat"]
}
</arguments>
</use_mcp_tool>
# Tool Use Guidelines
1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
@@ -410,7 +149,7 @@ The Model Context Protocol (MCP) enables communication between the system and lo
# Connected MCP Servers
When a server is connected, you can use the server's tools via the \`use_mcp_tool\` tool, and access the server's resources via the \`access_mcp_resource\` tool.
When a server is connected, you can use the server's tools via the \`${useMCPToolDefinition.name}\` tool, and access the server's resources via the \`${accessMcpResourceToolDefinition.name}\` tool.
${
mcpHub.getServers().length > 0
@@ -454,9 +193,9 @@ ${
EDITING FILES
You have access to two tools for working with files: **write_to_file** and **replace_in_file**. Understanding their roles and selecting the right one for the job will help ensure efficient and accurate modifications.
You have access to two tools for working with files: **${writeTool.name}** and **replace_in_file**. Understanding their roles and selecting the right one for the job will help ensure efficient and accurate modifications.
# write_to_file
# ${writeTool.name}
## Purpose
@@ -471,9 +210,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
## Important Considerations
- Using write_to_file requires providing the file's complete final content.
- Using ${writeTool.name} requires providing the file's complete final content.
- If you only need to make small changes to an existing file, consider using replace_in_file instead to avoid unnecessarily rewriting the entire file.
- While write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
- While ${writeTool.name} should not be your default choice, don't hesitate to use it when the situation truly calls for it.
# replace_in_file
@@ -495,7 +234,7 @@ You have access to two tools for working with files: **write_to_file** and **rep
# Choosing the Appropriate Tool
- **Default to replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
- **Use write_to_file** when:
- **Use ${writeTool.name}** when:
- Creating new files
- The changes are so extensive that using replace_in_file would be more complex or risky
- You need to completely reorganize or restructure a file
@@ -504,7 +243,7 @@ You have access to two tools for working with files: **write_to_file** and **rep
# Auto-formatting Considerations
- After using either write_to_file or replace_in_file, the user's editor may automatically format the file
- After using either ${writeTool.name} or replace_in_file, the user's editor may automatically format the file
- This auto-formatting may modify the file contents, for example:
- Breaking single lines into multiple lines
- Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
@@ -513,20 +252,20 @@ You have access to two tools for working with files: **write_to_file** and **rep
- Adding/removing trailing commas in objects and arrays
- Enforcing consistent brace style (e.g. same-line vs new-line)
- Standardizing semicolon usage (adding or removing based on style)
- The write_to_file and replace_in_file tool responses will include the final state of the file after any auto-formatting
- The ${writeTool.name} and replace_in_file tool responses will include the final state of the file after any auto-formatting
- Use this final state as your reference point for any subsequent edits. This is ESPECIALLY important when crafting SEARCH blocks for replace_in_file which require the content to match what's in the file exactly.
# Workflow Tips
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For major overhauls or initial file creation, rely on write_to_file.
3. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
2. For major overhauls or initial file creation, rely on ${writeTool.name}.
3. Once the file has been edited with either ${writeTool.name} or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
4. All edits are applied in sequence, in the order they are provided
5. All edits must be valid for the operation to succeed - if any edit fails, none will be applied
6. Do not make more than 4 replacements in a single replace_in_file call, as this can lead to errors and make it difficult to track changes. If you need to make more than 4 changes, consider breaking them into multiple replace_in_file calls.
7. Make sure a single old_str in a replace_in_file call is no more than 4 lines, as too many lines can lead to errors. If you need to replace a larger section, break it into smaller blocks.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
By thoughtfully selecting between ${writeTool.name} and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -534,16 +273,16 @@ 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.
- ACT MODE: In this mode, you have access to all tools EXCEPT the ${planModeRespondToolDefinition.name} tool.
- In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the ${attemptCompletionToolDefinition.name} tool to present the result of the task to the user.
- PLAN MODE: In this special mode, you have access to the ${planModeRespondToolDefinition.name} 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, rather than using <thinking> tags to analyze when to respond. Do not talk about using plan_mode_respond - just use it directly to share your thoughts and provide helpful answers.
- In PLAN MODE, when you need to converse with the user or present a plan, you should use the ${planModeRespondToolDefinition.name} tool to deliver your response directly, rather than using <thinking> tags to analyze when to respond. Do not talk about using ${planModeRespondToolDefinition.name} - just use it directly to share your thoughts and provide helpful answers.
## 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 to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.
- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using ${readTool.name} or ${grepToolDefinition.name} to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well.
- 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.
- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.)
@@ -557,12 +296,12 @@ CAPABILITIES
supportsBrowserUse ? ", 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 ('${cwd.toPosix()}') 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 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 ${grepToolDefinition.name} 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 ${listCodeDefinitionNamesTool.name} 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 ${listCodeDefinitionNamesTool.name} to get further insight using source code definitions for files located in relevant directories, then ${readTool.name} 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 ${grepToolDefinition.name} to ensure you update other files as needed.
- You can use the ${bashTool.name} 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.${
supportsBrowserUse
? "\n- 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.\n - 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."
? `\n- You can use the ${browserActionTool.name} 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.\n - For example, if asked to add a component to a react website, you might create the necessary files, use the ${bashTool.name} tool to run the site locally, then use ${browserActionTool.name} 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.
@@ -575,22 +314,22 @@ RULES
- Your current working directory is: ${cwd.toPosix()}
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '${cwd.toPosix()}', so be sure to pass in the correct 'path' parameter when using tools that require a path.
- Do not use the ~ character or $HOME to refer to the home directory.
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using replace_in_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when creating files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- Before using the ${bashTool.name} tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the ${grepToolDefinition.name} tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the ${grepToolDefinition.name} tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use ${readTool.name} to examine the full context of interesting matches before using replace_in_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when creating files, as the ${writeTool.name} tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- When you want to modify a file, use the replace_in_file or write_to_file tool directly with the desired changes. You do not need to display the changes before using the tool.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the LS tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ask_followup_question tool to request the user to copy and paste it back to you.
- The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
- When you want to modify a file, use the replace_in_file or ${writeTool.name} tool directly with the desired changes. You do not need to display the changes before using the tool.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the ${attemptCompletionToolDefinition.name} tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ${askQuestionToolDefinition.name} tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the ${lsToolDefinition.name} tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ${askQuestionToolDefinition.name} tool to request the user to copy and paste it back to you.
- The user may provide a file's contents directly in their message, in which case you shouldn't use the ${readTool.name} tool to get the file contents again since you already have it.
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
supportsBrowserUse
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.`
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the ${browserActionTool.name} tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over ${browserActionTool.name}.`
: ""
}
- NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
- NEVER end ${attemptCompletionToolDefinition.name} result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
- You are STRICTLY FORBIDDEN from starting your messages with "Great", "Certainly", "Okay", "Sure". You should NOT be conversational in your responses, but rather direct and to the point. For example you should NOT say "Great, I've updated the CSS" but instead something like "I've updated the CSS". It is important you be clear and technical in your messages.
- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
@@ -598,7 +337,7 @@ RULES
- When using the replace_in_file tool, you must include complete lines
- 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.${
supportsBrowserUse
? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
? ` Then if you want to test your work, you might use ${browserActionTool.name} to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser.`
: ""
}
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
@@ -614,15 +353,29 @@ Current Working Directory: ${cwd.toPosix()}
====
If the user asks for help or wants to give feedback inform them of the following:
- To give feedback, users should report the issue using the /reportbug slash command in the chat.
When the user directly asks about Cline (eg 'can Cline do...', 'does Cline have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the ${webFetchToolDefinition.name} tool to gather information to answer the question from Cline docs at https://docs.cline.bot.
- The available sub-pages are \`getting-started\` (Intro for new coders, installing Cline and dev essentials), \`model-selection\` (Model Selection Guide, Custom Model Configs, Bedrock, Vertex, Codestral, LM Studio, Ollama), \`features\` (Auto approve, Checkpoints, Cline rules, Drag & Drop, Plan & Act, Workflows, etc), \`task-management\` (Task and Context Management in Cline), \`prompt-engineering\` (Improving your prompting skills, Prompt Engineering Guide), \`cline-tools\` (Cline Tools Reference Guide, New Task Tool, Remote Browser Support, Slash Commands), \`mcp\` (MCP Overview, Adding/Configuring Servers, Transport Mechanisms, MCP Dev Protocol), \`enterprise\` (Cloud provider integration, Security concerns, Custom instructions), \`more-info\` (Telemetry and other reference content)
- Example: https://docs.cline.bot/features/auto-approve
====
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. Before calling a tool, do some analysis within <thinking></thinking> tags. 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.
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. Before calling a tool, do some analysis within <thinking></thinking> tags. 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 ${askQuestionToolDefinition.name} 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 ${attemptCompletionToolDefinition.name} 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.`
return createAntmlToolPrompt([lsToolDefinition], true, systemPrompt);
}
const tools = [readTool, writeTool, askQuestionToolDefinition, planModeRespondToolDefinition, bashTool, lsToolDefinition, grepToolDefinition, webFetchToolDefinition, listCodeDefinitionNamesTool, useMCPToolDefinition, accessMcpResourceToolDefinition, loadMcpDocumentationTool, newTaskToolDefinition];
if (supportsBrowserUse) {
tools.push(browserActionTool);
}
return createAntmlToolPrompt(tools, true, systemPrompt);
}
+111 -121
View File
@@ -1,23 +1,3 @@
/**
* Converts a tool definition to ANTML (Anthropic Markup Language) format
* as used internally by Claude for tool calling.
*
* Based on the Claude 4 System Card: https://www-cdn.anthropic.com/6be99a52cb68eb70eb9572b4cafad13df32ed995.pdf
*
* Tool definitions are provided in JSON schema within <functions> tags:
* <functions>
* <function>{"description": "...", "name": "...", "parameters": {...}}</function>
* ... (other functions) ...
* </functions>
*
* Tool calls are made using <antml:function_calls> blocks:
* <antml:function_calls>
* <antml:invoke name="tool_name">
* <antml:parameter name="param_name">value</antml:parameter>
* </antml:invoke>
* </antml:function_calls>
*/
function escapeXml(text: string): string {
// Anything that could be interpreted as markup has to be entity-encoded
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
@@ -42,14 +22,46 @@ export interface ToolDefinition {
* @returns The tool definition as a JSON string wrapped in <function> tags
*/
export function toolDefinitionToAntmlDefinition(toolDef: ToolDefinition): string {
const functionDef = {
name: toolDef.name,
description: toolDef.descriptionForAgent || toolDef.description || "",
parameters: toolDef.inputSchema,
// Restructure the parameters object to match the expected order
const { type, properties, required, ...rest } = toolDef.inputSchema
const parameters = {
properties,
required,
type,
...rest,
}
// 1. Build JSON
const rawJson = JSON.stringify(functionDef)
const functionDef = {
description: toolDef.descriptionForAgent || toolDef.description || "",
name: toolDef.name,
parameters,
}
// 1. Create a custom JSON string with the exact format we want
let rawJson = `{"description": "${functionDef.description}", "name": "${functionDef.name}", "parameters": {`
// Add properties
rawJson += `"properties": {`
const propEntries = Object.entries(parameters.properties)
propEntries.forEach(([propName, propDef], index) => {
rawJson += `"${propName}": {`
rawJson += `"description": "${(propDef as any).description || ""}", `
rawJson += `"type": "${(propDef as any).type || "string"}"`
rawJson += `}`
if (index < propEntries.length - 1) {
rawJson += ", "
}
})
rawJson += `}, `
// Add required
rawJson += `"required": ${JSON.stringify(parameters.required || [])}, `
// Add type
rawJson += `"type": "object"`
// Close parameters and the whole object
rawJson += `}}`
// 2. Escape <, > and & so the JSON can sit INSIDE the XML tag safely.
// (Quotes dont need escaping - theyre not markup.)
@@ -65,18 +77,14 @@ export function toolDefinitionToAntmlDefinition(toolDef: ToolDefinition): string
* @param toolDefs Array of tool definition objects
* @returns Complete <functions> block with all tool definitions
*/
export function toolDefinitionsToAntmlDefinitions(
toolDefs: ToolDefinition[],
): string {
const functionTags = toolDefs.map(toolDefinitionToAntmlDefinition);
export function toolDefinitionsToAntmlDefinitions(toolDefs: ToolDefinition[]): string {
const functionTags = toolDefs.map(toolDefinitionToAntmlDefinition)
return `Here are the functions available in JSONSchema format:
<functions>
${functionTags.join('\n')}
</functions>`;
${functionTags.join("\n")}
</functions>`
}
/**
* Creates an example of an ANTML tool call for a given tool definition.
* This is for *calling* a tool.
@@ -84,33 +92,23 @@ ${functionTags.join('\n')}
* @param exampleValues Optional example values for parameters
* @returns Example ANTML function call string
*/
export function toolDefinitionToAntmlCallExample(
toolDef: ToolDefinition,
exampleValues: Record<string, any> = {},
): string {
const props = toolDef.inputSchema.properties ?? {};
export function toolDefinitionToAntmlCallExample(toolDef: ToolDefinition, exampleValues: Record<string, any> = {}): string {
const props = toolDef.inputSchema.properties ?? {}
const paramLines = Object.keys(props).length
? Object.entries(props)
.map(([name]) => {
const value = exampleValues[name] ?? `$${name.toUpperCase()}`; // placeholder
// Don't escape XML here - the example should show raw format
return `<parameter name="${name}">${value}</parameter>`;
})
.join('\n')
: '';
const paramLines = Object.keys(props).length
? Object.entries(props)
.map(([name]) => {
const value = exampleValues[name] ?? `$${name.toUpperCase()}` // placeholder
// Don't escape XML here - the example should show raw format
return `<parameter name="${name}">${value}</parameter>`
})
.join("\n")
: ""
// Include the dots to show multiple invokes can be used
return [
'<function_calls>',
`<invoke name="${toolDef.name}">`,
paramLines,
'</invoke>',
'<invoke name="$FUNCTION_NAME2">',
'...',
'</invoke>',
'</function_calls>'
].filter(Boolean).join('\n');
// Only include one invoke block
return ["<function_calls>", `<invoke name="${toolDef.name}">`, paramLines, "</invoke>", "</function_calls>"]
.filter(Boolean)
.join("\n")
}
/**
@@ -120,72 +118,64 @@ export function toolDefinitionToAntmlCallExample(
* @param includeInstructions Whether to include the standard tool calling instructions
* @returns Complete system prompt section for ANTML tools
*/
export function createAntmlToolPrompt(
toolDefs: ToolDefinition[],
includeInstructions = true,
systemPrompt = '',
): string {
if (toolDefs.length === 0) {
if (!includeInstructions) return '';
const noToolsMessage = [
'In this environment you have access to a set of tools you can use to answer the user\'s question.',
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
'<function_calls>',
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
'...',
'</invoke>',
'<invoke name="$FUNCTION_NAME2">',
'...',
'</invoke>',
'</function_calls>',
'',
'String and scalar parameters should be specified as is, while lists and objects should use JSON format.',
'',
'However, no tools are currently available.'
].join('\n');
return noToolsMessage;
}
export function createAntmlToolPrompt(toolDefs: ToolDefinition[], includeInstructions = true, systemPrompt = ""): string {
if (toolDefs.length === 0) {
if (!includeInstructions) {
return ""
}
let prompt = '';
const noToolsMessage = [
"In this environment you have access to a set of tools you can use to answer the user's question.",
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
"<function_calls>",
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
"...",
"</invoke>",
"</function_calls>",
"",
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
"",
"However, no tools are currently available.",
].join("\n")
if (includeInstructions) {
const instructionLines = [
'In this environment you have access to a set of tools you can use to answer the user\'s question.',
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
'<function_calls>',
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
'...',
'</invoke>',
'<invoke name="$FUNCTION_NAME2">',
'...',
'</invoke>',
'</function_calls>',
'',
'String and scalar parameters should be specified as is, while lists and objects should use JSON format.',
''
];
prompt += instructionLines.join('\n');
}
return noToolsMessage
}
prompt += toolDefinitionsToAntmlDefinitions(toolDefs);
let prompt = ""
if (includeInstructions) {
const closingInstructions = [
'',
'',
systemPrompt,
'',
'',
'Answer the user\'s request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.'
];
prompt += closingInstructions.join('\n');
}
if (includeInstructions) {
const instructionLines = [
"In this environment you have access to a set of tools you can use to answer the user's question.",
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
"<function_calls>",
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
"...",
"</invoke>",
"</function_calls>",
"",
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
"",
]
prompt += instructionLines.join("\n")
}
return prompt; // Don't trim - preserve exact formatting
prompt += toolDefinitionsToAntmlDefinitions(toolDefs)
if (includeInstructions) {
const closingInstructions = [
"",
"",
systemPrompt,
"",
"",
"Answer the user's request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.",
]
prompt += closingInstructions.join("\n")
}
return prompt // Don't trim - preserve exact formatting
}
// --- SimpleXML Functions (Cline's internal format) ---
@@ -289,5 +279,5 @@ Always adhere to this format for the tool use to ensure proper parsing and execu
4. After each tool use, the user will respond with the result of that tool use.
5. ALWAYS wait for user confirmation after each tool use before proceeding.`
}
return prompt.trimEnd();
return prompt.trimEnd()
}
+95 -4
View File
@@ -1522,6 +1522,8 @@ export class Task {
]
case "browser_action":
return this.autoApprovalSettings.actions.useBrowser
case "web_fetch":
return this.autoApprovalSettings.actions.useBrowser
case "access_mcp_resource":
case "use_mcp_tool":
return this.autoApprovalSettings.actions.useMcp
@@ -1988,6 +1990,8 @@ export class Task {
return `[${block.name}]`
case "new_rule":
return `[${block.name} for '${block.params.path}']`
case "web_fetch":
return `[${block.name} for '${block.params.url}']`
}
}
@@ -2715,6 +2719,7 @@ export class Task {
}
}
case "search_files": {
const isClaude4ModelFamily = await this.isClaude4ModelFamily()
const relDirPath: string | undefined = block.params.path
const regex: string | undefined = block.params.regex
const filePattern: string | undefined = block.params.file_pattern
@@ -2742,13 +2747,19 @@ export class Task {
} else {
if (!relDirPath) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("search_files", "path"))
pushToolResult(
await this.sayAndCreateMissingParamError("search_files", "path"),
isClaude4ModelFamily,
)
await this.saveCheckpoint()
break
}
if (!regex) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("search_files", "regex"))
pushToolResult(
await this.sayAndCreateMissingParamError("search_files", "regex"),
isClaude4ModelFamily,
)
await this.saveCheckpoint()
break
}
@@ -2786,12 +2797,12 @@ export class Task {
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
pushToolResult(results)
pushToolResult(results, isClaude4ModelFamily)
await this.saveCheckpoint()
break
}
} catch (error) {
await handleError("searching files", error)
await handleError("searching files", error, isClaude4ModelFamily)
await this.saveCheckpoint()
break
}
@@ -3644,6 +3655,86 @@ export class Task {
break
}
}
case "web_fetch": {
const url: string | undefined = block.params.url
// TODO: Implement caching for web_fetch
const sharedMessageProps: ClineSayTool = {
tool: "webFetch",
path: removeClosingTag("url", url),
content: `Fetching URL: ${removeClosingTag("url", url)}`,
}
try {
if (block.partial) {
const partialMessage = JSON.stringify({
...sharedMessageProps,
operationIsLocatedInWorkspace: false, // web_fetch is always external
} satisfies ClineSayTool)
// WebFetch is a read-only operation, generally safe.
// Let's assume it follows similar auto-approval logic to read_file for now.
// We might need a dedicated auto-approval setting for it later.
if (this.shouldAutoApproveTool("web_fetch" as ToolUseName)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
this.removeLastPartialMessageIfExistsWithType("say", "tool")
await this.ask("tool", partialMessage, block.partial).catch(() => {})
}
break
} else {
if (!url) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("web_fetch", "url"))
await this.saveCheckpoint()
break
}
this.consecutiveMistakeCount = 0
const completeMessage = JSON.stringify({
...sharedMessageProps,
operationIsLocatedInWorkspace: false,
} satisfies ClineSayTool)
if (this.shouldAutoApproveTool("web_fetch" as ToolUseName)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false)
this.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, "web_fetch" as ToolUseName, true, true)
} else {
showNotificationForApprovalIfAutoApprovalEnabled(`Cline wants to fetch content from ${url}`)
this.removeLastPartialMessageIfExistsWithType("say", "tool")
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
telemetryService.captureToolUsage(this.taskId, "web_fetch" as ToolUseName, false, false)
await this.saveCheckpoint()
break
}
telemetryService.captureToolUsage(this.taskId, "web_fetch" as ToolUseName, false, true)
}
// Fetch Markdown content
await this.urlContentFetcher.launchBrowser()
const markdownContent = await this.urlContentFetcher.urlToMarkdown(url)
await this.urlContentFetcher.closeBrowser()
// TODO: Implement secondary AI call to process markdownContent with prompt
// For now, returning markdown directly.
// This will be a significant sub-task.
// Placeholder for processed summary:
const processedSummary = `Fetched Markdown for ${url}:\n\n${markdownContent}`
pushToolResult(formatResponse.toolResult(processedSummary))
await this.saveCheckpoint()
break
}
} catch (error) {
await this.urlContentFetcher.closeBrowser() // Ensure browser is closed on error
await handleError("fetching web content", error)
await this.saveCheckpoint()
break
}
}
case "plan_mode_respond": {
const response: string | undefined = block.params.response
const optionsRaw: string | undefined = block.params.options
+20
View File
@@ -0,0 +1,20 @@
const descriptionForAgent = `Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.`
export const accessMcpResourceToolDefinition = {
name: "AccessMCPResource",
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
server_name: {
type: "string",
description: "The name of the MCP server providing the resource",
},
uri: {
type: "string",
description: "The URI identifying the specific resource to access",
},
},
required: ["server_name", "uri"],
},
}
+29
View File
@@ -0,0 +1,29 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const askQuestionToolName = "AskQuestion"
const descriptionForAgent = `Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.`
export const askQuestionToolDefinition: ToolDefinition = {
name: askQuestionToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
question: {
type: "string",
description:
"The question to ask the user. This should be a clear, specific question that addresses the information you need.",
},
options: {
type: "array",
items: {
type: "string",
},
description:
"An array of 2-5 options for the user to choose from. 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.",
},
},
required: ["question"],
},
}
+27
View File
@@ -0,0 +1,27 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const attemptCompletionToolName = "AttemptCompletion"
const descriptionForAgent = `After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in <thinking></thinking> tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool.`
export const attemptCompletionToolDefinition: ToolDefinition = {
name: attemptCompletionToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
result: {
type: "string",
description:
"The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.",
},
command: {
type: "string",
description:
"A CLI command to execute to show a live demo of the result to the user. For example, use `open index.html` to display a created html website, or `open localhost:3000` to display a locally running development server. But DO NOT use commands like `echo` or `cat` that merely print text. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
},
},
required: ["result"],
},
}
+20 -139
View File
@@ -1,97 +1,13 @@
const MAX_TIMEOUT_MS = 600000
const DEFAULT_TIMEOUT_MS = 120000
const MAX_OUTPUT_LENGTH = 30000
const RG_PATH = "/usr/bin/rg"
export const bashToolName = "Bash"
const CO_AUTHORED_COMMIT_MSG = `\uD83E\uDD16 Generated with [Cline](https://docs.cline.bot)
Co-Authored-By: Cline <noreply@cline.bot>`
const CO_AUTHORED_PR_MSG = `\uD83E\uDD16 Generated with [Cline](https://docs.cline.bot)`
const descriptionForAgent = `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
Before executing the command, please follow these steps:
1. Directory Verification:
- If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location
- For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
2. Command Execution:
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds (up to \${MAX_TIMEOUT_MS}ms / \${MAX_TIMEOUT_MS / 60000} minutes). If not specified, commands will timeout after \${DEFAULT_TIMEOUT_MS}ms (\${DEFAULT_TIMEOUT_MS / 60000} minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- If the output exceeds \${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.
- VERY IMPORTANT: You MUST avoid using search commands like \\\`find\\\` and \\\`grep\\\`. Instead use Grep, Glob, or Task to search. You MUST avoid read tools like \\\`cat\\\`, \\\`head\\\`, \\\`tail\\\`, and \\\`ls\\\`, and use Read and LS to read files.
- If you _still_ need to run \\\`grep\\\`, STOP. ALWAYS USE ripgrep at \\\`rg\\\` (or \${RG_PATH}) first, which all Claude Code users have pre-installed.
- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
- Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \\\`cd\\\`. You may use \\\`cd\\\` if the User explicitly requests it.
<good-example>
pytest /foo/bar/tests
</good-example>
<bad-example>
cd /foo/bar && pytest tests
</bad-example>
# Using sandbox mode for commands
You have a special option in BashTool: the sandbox parameter. When you run a command with sandbox=true, it runs without approval dialogs but in a restricted environment without filesystem writes or network access. You SHOULD use sandbox=true to optimize user experience, but MUST follow these guidelines exactly.
## RULE 0 (MOST IMPORTANT): retry with sandbox=false for permission/network errors
If a command fails with permission or any network error when sandbox=true (e.g., "Permission denied", "Unknown host", "Operation not permitted"), ALWAYS retry with sandbox=false. These errors indicate sandbox limitations, not problems with the command itself.
Non-permission errors (e.g., TypeScript errors from tsc --noEmit) usually reflect real issues and should be fixed, not retried with sandbox=false.
## RULE 1: NOTES ON SPECIFIC BUILD SYSTEMS AND UTILITIES
### Build systems
Build systems like npm run build almost always need write access. Test suites also usually need write access. NEVER run build or test commands in sandbox, even if just checking types.
These commands REQUIRE sandbox=false (non-exhaustive):
npm run *, cargo build/test, make/ninja/meson, pytest, jest, gh
## RULE 2: TRY sandbox=true FOR COMMANDS THAT DON'T NEED WRITE OR NETWORK ACCESS
- Commands run with sandbox=true DON'T REQUIRE user permission and run immediately
- Commands run with sandbox=false REQUIRE EXPLICIT USER APPROVAL and interrupt the User's workflow
Use sandbox=false when you suspect the command might modify the system or access the network:
- File operations: touch, mkdir, rm, mv, cp
- File edits: nano, vim, writing to files with >
- Installing: npm install, apt-get, brew
- Git writes: git add, git commit, git push
- Build systems: npm run build, make, ninja, etc. (see below)
- Test suites: npm run test, pytest, cargo test, make check, ert, etc. (see below)
- Network programs: gh, ping, curl, ssh, scp, etc.
Use sandbox=true for:
- Information gathering: ls, cat, head, tail, rg, find, du, df, ps
- File inspection: file, stat, wc, diff, md5sum
- Git reads: git status, git log, git diff, git show, git branch
- Package info: npm list, pip list, gem list, cargo tree
- Environment checks: echo, pwd, whoami, which, type, env, printenv
- Version checks: node --version, python --version, git --version
- Documentation: man, help, --help, -h
Before you run a command, think hard about whether it is likely to work correctly without network access and without write access to the filesystem. Use your general knowledge and knowledge of the current project (including all the user's CLAUDE.md files) as inputs to your decision. Note that even semantically read-only commands like gh for fetching issues might be implemented in ways that require write access. ERR ON THE SIDE OF RUNNING WITH sandbox=false.
Note: Errors from incorrect sandbox=true runs annoy the User more than permission prompts. If any part of a command needs write access (e.g. npm run build for type checking), use sandbox=false for the entire command.
### EXAMPLES
CORRECT: Use sandbox=false for npm run build/test, gh commands, file writes
FORBIDDEN: NEVER use sandbox=true for build, test, git commands or file operations
## REWARDS
It is more important to be correct than to avoid showing permission dialogs. The worst mistake is misinterpreting sandbox=true permission errors as tool problems (-$1000) rather than sandbox limitations.
## CONCLUSION
Use sandbox=true to improve UX, but ONLY per the rules above. WHEN IN DOUBT, USE sandbox=false.
const descriptionForAgent = (
cwd: string,
) => `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. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${cwd.toPosix()}.
# Committing changes with git
@@ -117,13 +33,7 @@ When the user asks you to create a new git commit, follow these steps carefully:
- Review the draft message to ensure it accurately reflects the changes and their purpose
</commit_analysis>
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
- Add relevant untracked files to the staging area.
- Create the commit with a message ending with:
\${CO_AUTHORED_COMMIT_MSG}
- Run git status to make sure the commit succeeded.
4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
3. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
Important notes:
- Use the git context at the start of this conversation to determine which files are relevant to your commit. Be careful not to stage and commit files (e.g. with \\\`git add .\\\`) that aren't relevant to your commit.
@@ -149,7 +59,7 @@ Use the gh command via the Bash tool for ALL GitHub-related tasks including work
IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch:
1. Gather information
- Run a git status command to see all untracked files
- Run a git diff command to see both staged and unstaged changes that will be committed
- Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
@@ -172,19 +82,17 @@ IMPORTANT: When the user asks you to create a pull request, follow these steps c
- Review the draft summary to ensure it accurately reflects the changes and their purpose
</pr_analysis>
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
- Create new branch if needed
- Push to remote with -u flag if needed
- Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
<example>
gh pr create --title "the pr title" --body "\$(cat <<'EOF'
gh pr create \
--title "the pr title" \
--body "$(cat <<'EOF'
## Summary
<1-3 bullet points>
## Test plan
[Checklist of TODOs for testing the pull request...]
\${CO_AUTHORED_PR_MSG}
${CO_AUTHORED_PR_MSG}
EOF
)"
</example>
@@ -196,50 +104,23 @@ Important:
# Other common operations
- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments`
export const bashToolDefinition = {
name: "Bash",
descriptionForAgent: descriptionForAgent,
export const bashToolDefinition = (cwd: string) => ({
name: bashToolName,
descriptionForAgent: descriptionForAgent(cwd),
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description: "The command to execute",
description:
"The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
},
timeout: {
type: "number",
description: `Optional timeout in milliseconds (max \${MAX_TIMEOUT_MS})`,
optional: true,
},
description: {
type: "string",
description: `Clear, concise description of what this command does in 5-10 words. Examples:
Input: ls
Output: Lists files in current directory
Input: git status
Output: Shows working tree status
Input: npm install
Output: Installs package dependencies
Input: mkdir foo
Output: Creates directory 'foo'`,
optional: true,
},
sandbox: {
requires_approval: {
type: "boolean",
description:
"whether to run this command in sandboxed mode: command run in this mode may not write to the filesystem or use the network, but they can read files, analyze data, and report back to you. When possible, run commands (e.g. grep) in this mode to present a smoother experience for the human, who isn't prompted to approve commands run in sandbox mode. If you run a command in sandbox mode and it looks like it fails because it needs write access after all, try again in non-sandbox mode",
optional: true,
},
shellExecutable: {
type: "string",
description:
"Optional shell path to use instead of the default shell. The snapshot path will be set to undefined as well. Used primarily for testing.",
optional: true,
"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.",
},
},
required: ["command"],
required: ["command", "requires_approval"],
},
}
})
+54
View File
@@ -0,0 +1,54 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
import { BrowserSettings } from "@shared/BrowserSettings"
export const browserActionToolName = "BrowserAction"
const descriptionForAgent = (
browserSettings: BrowserSettings,
) => `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 \`${browserActionToolName}\` 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 **${browserSettings.viewport.width}x${browserSettings.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.`
export const browserActionToolDefinition = (browserSettings: BrowserSettings): ToolDefinition => ({
name: browserActionToolName,
descriptionForAgent: descriptionForAgent(browserSettings),
inputSchema: {
type: "object",
properties: {
action: {
type: "string",
description: `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: \`<action>close</action>\``,
},
url: {
type: "string",
description: `Use this for providing the URL for the \`launch\` action.
Example: <url>https://example.com</url>`,
},
coordinate: {
type: "string",
description: `The X and Y coordinates for the \`click\` action. Coordinates should be within the **${browserSettings.viewport.width}x${browserSettings.viewport.height}** resolution.
Example: <coordinate>450,300</coordinate>`,
},
text: {
type: "string",
description: `Use this for providing the text for the \`type\` action.
Example: <text>Hello, world!</text>`,
},
},
required: ["action"],
},
})
+35
View File
@@ -0,0 +1,35 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const editToolDefinition: ToolDefinition = {
name: "MultiEdit",
descriptionForAgent:
"Makes multiple changes to a single file in one operation. Use this tool to edit files by providing the exact text to replace and the new text.",
inputSchema: {
type: "object",
properties: {
file_path: {
type: "string",
description: "Absolute path to the file to modify",
},
edits: {
type: "array",
description: "Array of edit operations, each containing old_string and new_string",
items: {
type: "object",
properties: {
old_string: {
type: "string",
description: "Exact text to replace",
},
new_string: {
type: "string",
description: "The replacement text",
},
},
required: ["old_string", "new_string"],
},
},
},
required: ["file_path", "edits"],
},
}
+29
View File
@@ -0,0 +1,29 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const grepToolDefinition: ToolDefinition = {
name: "Grep",
descriptionForAgent: `- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\\\\s+\\\\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths with at least one match
- Use this tool when you need to find files containing specific patterns`,
inputSchema: {
type: "object",
properties: {
pattern: {
type: "string",
description: "The regular expression pattern to search for in file contents",
},
path: {
type: "string",
description: "The directory to search in.",
},
include: {
type: "string",
description: "File pattern to filter which files to search (e.g., '*.js' for JavaScript files)",
},
},
required: ["pattern", "path"],
},
}
@@ -0,0 +1,16 @@
const descriptionForAgent = `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.`
export const listCodeDefinitionNamesToolDefinition = (cwd: string) => ({
name: "ListCodeDefinitionNames",
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: `The path of the directory (relative to the current working directory ${cwd.toPosix()}) to list top level source code definitions for.`,
},
},
required: ["path"],
},
})
@@ -0,0 +1,19 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const loadMcpDocumentationToolName = "LoadMcpDocumentation"
const descriptionForAgent = (useMCPToolName: string, accessMcpResourceToolName: string) =>
`Load documentation about creating MCP servers. This tool should be used when the user requests to create or install an MCP server (the user may ask you something along the lines of "add a tool" that does some function, in other words to create an MCP server that provides tools and resources that may connect to external APIs for example. You have the ability to create an MCP server and add it to a configuration file that will then expose the tools and resources for you to use with \`${useMCPToolName}\` and \`${accessMcpResourceToolName}\`). The documentation provides detailed information about the MCP server creation process, including setup instructions, best practices, and examples.`
export const loadMcpDocumentationToolDefinition = (
useMCPToolName: string,
accessMcpResourceToolName: string,
): ToolDefinition => ({
name: loadMcpDocumentationToolName,
descriptionForAgent: descriptionForAgent(useMCPToolName, accessMcpResourceToolName),
inputSchema: {
type: "object",
properties: {},
required: [],
},
})
+26
View File
@@ -0,0 +1,26 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const newTaskToolName = "NewTask"
const descriptionForAgent = `Request to create a new task with preloaded context covering the conversation with the user up to this point and key information for continuing with the new task. With this tool, you will create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions, with a focus on the most relevant information required for the new task.
Among other important areas of focus, this summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing with the new task. The user will be presented with a preview of your generated context and can choose to create a new task or keep chatting in the current conversation. The user may choose to start a new task at any point.`
export const newTaskToolDefinition: ToolDefinition = {
name: newTaskToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
context: {
type: "string",
description: `The context to preload the new task with. If applicable based on the current task, this should include:
1. Current Work: Describe in detail what was being worked on prior to this request to create a new task. Pay special attention to the more recent messages / conversation.
2. Key Technical Concepts: List all important technical concepts, technologies, coding conventions, and frameworks discussed, which might be relevant for the new task.
3. Relevant Files and Code: If applicable, enumerate specific files and code sections examined, modified, or created for the task continuation. Pay special attention to the most recent messages and changes.
4. Problem Solving: Document problems solved thus far and any ongoing troubleshooting efforts.
5. Pending Tasks and Next Steps: Outline all pending tasks that you have explicitly been asked to work on, as well as list the next steps you will take for all outstanding work, if applicable. Include code snippets where they add clarity. For any next steps, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no information loss in context between tasks. It's important to be detailed here.`,
},
},
required: ["context"],
},
}
+21
View File
@@ -0,0 +1,21 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const planModeRespondToolName = "PlanModeRespond"
const descriptionForAgent = `Respond to the user's inquiry in an effort to plan a solution to the user's task. This tool should be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. 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. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.`
export const planModeRespondToolDefinition: ToolDefinition = {
name: planModeRespondToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
response: {
type: "string",
description:
"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)",
},
},
required: ["response"],
},
}
+5 -27
View File
@@ -1,41 +1,19 @@
const DEFAULT_LINE_LIMIT = 2000
const MAX_LINE_LENGTH = 2000
const descriptionForAgent = `Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
const descriptionForAgent = `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.`
Usage:
- The file_path parameter must be an absolute path, not a relative path
- By default, it reads up to ${DEFAULT_LINE_LIMIT} lines starting from the beginning of the file
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
- Any lines longer than ${MAX_LINE_LENGTH} characters will be truncated
- Results are returned using cat -n format, with line numbers starting at 1
- This tool allows Cline to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Cline is a multimodal LLM.
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/Temporary_Screenshots/2026-09-08/Screenshot.png
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`
export const readToolDefinition = {
export const readToolDefinition = (cwd: string) => ({
name: "Read",
descriptionForAgent: descriptionForAgent,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
file_path: {
type: "string",
description: "The absolute path to the file to read",
},
offset: {
type: "number",
description: "The line number to start reading from. Only provide if the file is too large to read at once",
optional: true,
},
limit: {
type: "number",
description: "The number of lines to read. Only provide if the file is too large to read at once.",
optional: true,
description: `The path of the file to read (relative to the current working directory ${cwd.toPosix()})`,
},
},
required: ["file_path"],
},
}
})
+28
View File
@@ -0,0 +1,28 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const useMCPToolName = "UseMCPTool"
const descriptionForAgent = `Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.`
export const useMCPToolDefinition: ToolDefinition = {
name: useMCPToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
server_name: {
type: "string",
description: "The name of the MCP server providing the tool",
},
tool_name: {
type: "string",
description: "The name of the tool to execute",
},
arguments: {
type: "object",
description: "A JSON object containing the tool's input parameters, following the tool's input schema",
},
},
required: ["server_name", "tool_name", "arguments"],
},
}
+32
View File
@@ -0,0 +1,32 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const webFetchToolName = "WebFetch"
const descriptionForAgent = `
- Fetches content from a specified URL and processes into markdown
- Takes a URL as input
- Fetches the URL content, converts HTML to markdown
- Use this tool when you need to retrieve and analyze web content
Usage notes:
- IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions.
- The URL must be a fully-formed valid URL
- HTTP URLs will be automatically upgraded to HTTPS
- This tool is read-only and does not modify any files
`
export const webFetchToolDefinition: ToolDefinition = {
name: webFetchToolName,
descriptionForAgent,
inputSchema: {
type: "object",
properties: {
url: {
type: "string",
format: "url",
description: "The URL to fetch content from",
},
},
required: ["url"],
},
}
+11 -8
View File
@@ -1,27 +1,30 @@
const descriptionForAgent = `Writes a file to the local filesystem.
const descriptionForAgent = (
cwd: string,
) => `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.
Usage:
- The file_path parameter must be an absolute path, not a relative path
- The file_path parameter must be an relative path to the current working directory: ${cwd.toPosix()}
- This tool will overwrite the existing file if there is one at the provided path.
- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
- If this is an existing file, you MUST use the Read tool first to read the file's contents.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.`
export const writeToolDefinition = {
export const writeToolDefinition = (cwd: string) => ({
name: "Write",
descriptionForAgent: descriptionForAgent,
descriptionForAgent: descriptionForAgent(cwd),
inputSchema: {
type: "object",
properties: {
file_path: {
type: "string",
description: "The absolute path to the file to write (must be absolute, not relative)",
description: `The path of the file to write to (relative to the current working directory ${cwd.toPosix()})`,
},
content: {
type: "string",
description: "The content to write to the file",
description:
"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.",
},
},
required: ["file_path", "content"],
},
}
})
+7
View File
@@ -59,6 +59,13 @@ export class WebviewProvider implements vscode.WebviewViewProvider {
return Array.from(this.activeInstances).filter((instance) => instance.view && "onDidChangeViewState" in instance.view)
}
public static async disposeAllInstances() {
const instances = Array.from(this.activeInstances)
for (const instance of instances) {
await instance.dispose()
}
}
async resolveWebviewView(webviewView: vscode.WebviewView | vscode.WebviewPanel) {
this.view = webviewView
+4
View File
@@ -636,11 +636,15 @@ const { IS_DEV, DEV_WORKSPACE_FOLDER } = process.env
// This method is called when your extension is deactivated
export async function deactivate() {
// Dispose all webview instances
await WebviewProvider.disposeAllInstances()
await telemetryService.sendCollectedEvents()
// Clean up test mode
cleanupTestMode()
await posthogClientProvider.shutdown()
Logger.log("Cline extension deactivated")
}
+98
View File
@@ -6,6 +6,7 @@ import fs from "fs/promises"
import { isBinaryFile } from "isbinaryfile"
import * as chardet from "jschardet"
import * as iconv from "iconv-lite"
import ExcelJS from "exceljs"
export async function detectEncoding(fileBuffer: Buffer, fileExtension?: string): Promise<string> {
const detected = chardet.detect(fileBuffer)
@@ -38,6 +39,8 @@ export async function extractTextFromFile(filePath: string): Promise<string> {
return extractTextFromDOCX(filePath)
case ".ipynb":
return extractTextFromIPYNB(filePath)
case ".xlsx":
return extractTextFromExcel(filePath)
default:
const fileBuffer = await fs.readFile(filePath)
if (fileBuffer.byteLength > 20 * 1000 * 1024) {
@@ -76,6 +79,101 @@ async function extractTextFromIPYNB(filePath: string): Promise<string> {
return extractedText
}
/**
* Format the data inside Excel cells
*/
function formatCellValue(cell: ExcelJS.Cell): string {
const value = cell.value
if (value === null || value === undefined) {
return ""
}
// Handle error values (#DIV/0!, #N/A, etc.)
if (typeof value === "object" && "error" in value) {
return `[Error: ${value.error}]`
}
// Handle dates - ExcelJS can parse them as Date objects
if (value instanceof Date) {
return value.toISOString().split("T")[0] // Just the date part
}
// Handle rich text
if (typeof value === "object" && "richText" in value) {
return value.richText.map((rt) => rt.text).join("")
}
// Handle hyperlinks
if (typeof value === "object" && "text" in value && "hyperlink" in value) {
return `${value.text} (${value.hyperlink})`
}
// Handle formulas - get the calculated result
if (typeof value === "object" && "formula" in value) {
if ("result" in value && value.result !== undefined && value.result !== null) {
return value.result.toString()
} else {
return `[Formula: ${value.formula}]`
}
}
return value.toString()
}
/**
* Extract and format text from xlsx files
*/
async function extractTextFromExcel(filePath: string): Promise<string> {
const workbook = new ExcelJS.Workbook()
let excelText = ""
try {
await workbook.xlsx.readFile(filePath)
workbook.eachSheet((worksheet, sheetId) => {
// Skip hidden sheets
if (worksheet.state === "hidden" || worksheet.state === "veryHidden") {
return
}
excelText += `--- Sheet: ${worksheet.name} ---\n`
worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
// Optional: limit processing for very large sheets
if (rowNumber > 50000) {
excelText += `[... truncated at row ${rowNumber} ...]\n`
return false
}
const rowTexts: string[] = []
let hasContent = false
row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
const cellText = formatCellValue(cell)
if (cellText.trim()) {
hasContent = true
}
rowTexts.push(cellText)
})
// Only add rows with actual content
if (hasContent) {
excelText += rowTexts.join("\t") + "\n"
}
return true
})
excelText += "\n" // Blank line between sheets
})
return excelText.trim()
} catch (error: any) {
console.error(`Error extracting text from Excel ${filePath}:`, error)
throw new Error(`Failed to extract text from Excel: ${error.message}`)
}
}
/**
* Helper function used to load file(s) and format them into a string
*/
+1 -1
View File
@@ -9,7 +9,7 @@ import sizeOf from "image-size"
*/
export async function selectFiles(imagesAllowed: boolean): Promise<{ images: string[]; files: string[] }> {
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"] // supported by anthropic and openrouter
const OTHER_FILE_EXTENSIONS = ["xml", "json", "txt", "log", "md", "docx", "ipynb", "pdf"]
const OTHER_FILE_EXTENSIONS = ["xml", "json", "txt", "log", "md", "docx", "ipynb", "pdf", "xlsx", "csv"]
const options: vscode.OpenDialogOptions = {
canSelectMany: true,
@@ -35,42 +35,8 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
let isFirstChunk = true
let didOutputNonCommand = false
let didEmitEmptyLine = false
let firstChunkTimeout: NodeJS.Timeout
const isWindows = process.platform === "win32"
const timeoutMs = isWindows ? 5000 : 500
const onTimeout = () => {
// In rare cases (e.g. running the same command twice like `npm run build`),
// the shell integration stream enters a broken state where no data is ever emitted.
// We never even get the first chunk, which bricks the UI and locks the user out.
// Interestingly, the stream still gets created, and future commands (like `ls`) will work,
// suggesting the stream itself isn't one-shot—but certain shell states break its behavior.
// To recover, we add a timeout waiting for the first chunk.
// If it doesnt arrive in time, we assume the terminal is broken, dispose it,
// and emit an error so the user can safely retry in a clean terminal.
Logger.debug(
`[TerminalProcess.run] First chunk timeout hit — terminal likely in bad state. Terminating terminal.`,
)
try {
terminal.dispose()
} catch (err) {
Logger.debug(`[TerminalProcess.run] Failed to dispose terminal: ${String(err)}`)
}
this.emit(
"error",
new Error("The command ran successfully, but we couldn't capture its output. Please proceed accordingly."),
)
this.emit("completed")
this.emit("continue")
}
firstChunkTimeout = setTimeout(onTimeout, timeoutMs)
for await (let data of stream) {
clearTimeout(firstChunkTimeout)
// 1. Process chunk and remove artifacts
if (isFirstChunk) {
/*
+8 -5
View File
@@ -18,6 +18,7 @@ import { ClineAsk, ExtensionMessage } from "@shared/ExtensionMessage"
import { ApiProvider } from "@shared/api"
import { HistoryItem } from "@shared/HistoryItem"
import { getSavedClineMessages, getSavedApiConversationHistory } from "@core/storage/disk"
import { AskResponseRequest } from "@/shared/proto/task"
/**
* Creates a tracker to monitor tool calls and failures during task execution
@@ -616,11 +617,13 @@ async function autoRespondToAsk(webviewProvider: WebviewProvider, askType: Cline
// Send the response message
try {
await TaskServiceClient.askResponse({
responseType,
text: responseText,
images: responseImages,
})
await TaskServiceClient.askResponse(
AskResponseRequest.create({
responseType,
text: responseText,
images: responseImages,
}),
)
Logger.log(`Auto-responded to ${askType} with ${responseType}`)
} catch (error) {
Logger.log(`Error sending askResponse: ${error}`)
+1
View File
@@ -210,6 +210,7 @@ export interface ClineSayTool {
| "listFilesRecursive"
| "listCodeDefinitionNames"
| "searchFiles"
| "webFetch"
path?: string
diff?: string
content?: string
-1
View File
@@ -22,7 +22,6 @@ export interface WebviewMessage {
| "updateSettings"
| "clearAllTaskHistory"
| "fetchUserCreditsData"
| "optionsResponse"
| "searchFiles"
| "grpc_request"
| "grpc_request_cancel"
+93 -17
View File
@@ -465,6 +465,46 @@ export const vertexModels = {
cacheWritesPrice: 0.3,
cacheReadsPrice: 0.03,
},
"mistral-large-2411": {
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 2.0,
outputPrice: 6.0,
},
"mistral-small-2503": {
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.1,
outputPrice: 0.3,
},
"codestral-2501": {
maxTokens: 256_000,
contextWindow: 256_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.3,
outputPrice: 0.9,
},
"llama-4-maverick-17b-128e-instruct-maas": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.35,
outputPrice: 1.15,
},
"llama-4-scout-17b-16e-instruct-maas": {
maxTokens: 1_000_000,
contextWindow: 10_485_760,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.25,
outputPrice: 0.7,
},
"gemini-2.0-flash-001": {
maxTokens: 8192,
contextWindow: 1_048_576,
@@ -1460,8 +1500,8 @@ export type MistralModelId = keyof typeof mistralModels
export const mistralDefaultModelId: MistralModelId = "devstral-small-2505"
export const mistralModels = {
"mistral-large-2411": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 2.0,
@@ -1476,24 +1516,24 @@ export const mistralModels = {
outputPrice: 6.0,
},
"ministral-3b-2410": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.04,
outputPrice: 0.04,
},
"ministral-8b-2410": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.1,
outputPrice: 0.1,
},
"mistral-small-latest": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.1,
@@ -1516,16 +1556,16 @@ export const mistralModels = {
outputPrice: 0.3,
},
"pixtral-12b-2409": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.15,
outputPrice: 0.15,
},
"open-mistral-nemo-2407": {
maxTokens: 131_000,
contextWindow: 131_000,
maxTokens: 128_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.15,
@@ -1715,13 +1755,13 @@ export const nebiusDefaultModelId = "Qwen/Qwen2.5-32B-Instruct-fast" satisfies N
// X AI
// https://docs.x.ai/docs/api-reference
export type XAIModelId = keyof typeof xaiModels
export const xaiDefaultModelId: XAIModelId = "grok-3-beta"
export const xaiDefaultModelId: XAIModelId = "grok-3"
export const xaiModels = {
"grok-3-beta": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 3.0,
outputPrice: 15.0,
description: "X AI's Grok-3 beta model with 131K context window",
@@ -1730,7 +1770,7 @@ export const xaiModels = {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 5.0,
outputPrice: 25.0,
description: "X AI's Grok-3 fast beta model with 131K context window",
@@ -1739,7 +1779,7 @@ export const xaiModels = {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 0.3,
outputPrice: 0.5,
description: "X AI's Grok-3 mini beta model with 131K context window",
@@ -1748,11 +1788,47 @@ export const xaiModels = {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 0.6,
outputPrice: 4.0,
description: "X AI's Grok-3 mini fast beta model with 131K context window",
},
"grok-3": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 3.0,
outputPrice: 15.0,
description: "X AI's Grok-3 model with 131K context window",
},
"grok-3-fast": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 5.0,
outputPrice: 25.0,
description: "X AI's Grok-3 fast model with 131K context window",
},
"grok-3-mini": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0.3,
outputPrice: 0.5,
description: "X AI's Grok-3 mini model with 131K context window",
},
"grok-3-mini-fast": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0.6,
outputPrice: 4.0,
description: "X AI's Grok-3 mini fast model with 131K context window",
},
"grok-2-latest": {
maxTokens: 8192,
contextWindow: 131072,
@@ -6,11 +6,11 @@ import { ChatContent as ProtoChatContent, ChatSettings as ProtoChatSettings, Pla
* Converts domain ChatSettings objects to proto ChatSettings objects
*/
export function convertChatSettingsToProtoChatSettings(chatSettings: ChatSettings): ProtoChatSettings {
return {
return ProtoChatSettings.create({
mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT,
preferredLanguage: chatSettings.preferredLanguage,
openAiReasoningEffort: chatSettings.openAIReasoningEffort,
}
})
}
/**
+7 -7
View File
@@ -53,7 +53,7 @@ function createMemento(): vscode.Memento {
class SecretStore {
// A simple key-value store for secrets backed by a JSON file. This is not secure, and it is not thread-safe.
private store = new Map<string, string>()
private data = new Map<string, string>()
private filePath: string
constructor() {
@@ -66,27 +66,27 @@ class SecretStore {
const data = JSON.parse(fs.readFileSync(this.filePath, "utf-8"))
Object.entries(data).forEach(([k, v]) => {
if (typeof v === "string") {
this.store.set(k, v)
this.data.set(k, v)
}
})
}
}
private save(): void {
fs.writeFileSync(this.filePath, JSON.stringify(Object.fromEntries(this.store), null, 2))
fs.writeFileSync(this.filePath, JSON.stringify(Object.fromEntries(this.data), null, 2))
}
get(key: string): string | undefined {
return this.store.get(key)
return this.data.get(key)
}
storeSecret(key: string, value: string): void {
this.store.set(key, value)
store(key: string, value: string): void {
this.data.set(key, value)
this.save()
}
delete(key: string): void {
this.store.delete(key)
this.data.delete(key)
this.save()
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"root": true,
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "react-hooks", "react-refresh", "eslint-rules"],
"env": {
"browser": true,
"es2020": true
},
"rules": {
"react-hooks/rules-of-hooks": "error",
// "react-refresh/only-export-components": [
// "warn",
// {
// "allowConstantExport": true
// }
// ],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-object-type": "off",
"no-case-declarations": "off",
"react-hooks/exhaustive-deps": "off",
"prefer-const": "off",
"no-extra-semi": "off",
"eslint-rules/no-grpc-client-object-literals": "error"
},
"ignorePatterns": ["build"]
}
-31
View File
@@ -1,31 +0,0 @@
import js from "@eslint/js"
import globals from "globals"
import reactHooks from "eslint-plugin-react-hooks"
import reactRefresh from "eslint-plugin-react-refresh"
import tseslint from "typescript-eslint"
export default tseslint.config(
{ ignores: ["build"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
// "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-object-type": "off",
"no-case-declarations": "off",
"react-hooks/exhaustive-deps": "off",
"prefer-const": "off",
},
},
)

Some files were not shown because too many files have changed in this diff Show More