Compare commits

..
Author SHA1 Message Date
Andrei Eternal 2e530b1271 cleanup 2025-05-22 16:42:13 -07:00
Andrei Edell f6e481baf9 memory leak console boys 2025-05-22 16:42:13 -07:00
Andrei Edell 77128afa20 Revert "fix: Address memory leak by bypassing subscribeToState gRPC stream for state updates (#3597)"
This reverts commit 8ab35a5b06.
2025-05-22 16:42:13 -07:00
226 changed files with 11392 additions and 11307 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
add models to vertex ai
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Update `xaiModels` object and `xaiDefaultModelId` in `src/shared/api.ts`
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
fixing token counting for xai provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate mcpButtonClicked to protobus
-7
View File
@@ -1,7 +0,0 @@
---
"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
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
add suppport for parsing csv and xlsx
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixed search tool overloading conversation with massive outputs by setting a maximum overall byte limit for search tool responses
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
update chat box ui
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
bug fix for ollama
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
update the openrouter model list when refreshing
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix Title for windows in cline
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
scroll to task timeline
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add grep tool with new parsing format
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
optionsResponse protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Display delay information when retrying API calls
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Pass type of webview (tab or sidebar) to webview so it knows what type it is
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add edit tool definition
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
change proto type
-1
View File
@@ -164,7 +164,6 @@ Key providers include:
- **OpenRouter**: Meta-provider supporting multiple model providers
- **AWS Bedrock**: Integration with Amazon's AI services
- **Gemini**: Google's AI models
- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
- **Ollama**: Local model hosting
- **LM Studio**: Local model hosting
- **VSCode LM**: VSCode's built-in language models
+2 -3
View File
@@ -5,7 +5,7 @@
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "eslint-rules"],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/naming-convention": [
"warn",
@@ -19,8 +19,7 @@
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"react-hooks/exhaustive-deps": "off",
"eslint-rules/no-grpc-client-object-literals": "error"
"react-hooks/exhaustive-deps": "off"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
-2
View File
@@ -3,5 +3,3 @@ node_modules
webview-ui/build/
*.md
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
-30
View File
@@ -1,35 +1,5 @@
# 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
## [3.17.6]
- Add Cerebras as a new API provider with 5 high-performance models including reasoning-capable models (Thanks @kevint-cerebras!)
- Add support for uploading various file types (XML, JSON, TXT, LOG, MD, DOCX, IPYNB, PDF) alongside images
- Add improved onboarding experience for new users with guided setup
- Add prompt cache indicator for Gemini 2.5 Flash models
- Update SambaNova provider with new model list and documentation links (Thanks @luisfucros!)
- Fix diff editing support for Claude 4 family of models
- Improve telemetry and analytics for better user experience insights
## [3.17.5]
- Fix issue with Claude 4 models where after several conversation turns, it would start making invalid diff edits
## [3.17.4]
- Fix thinking budget slider for Claude 4
## [3.17.3]
- Fix diff edit errors with Claude 4 models
## [3.17.2]
- Add support for Claude 4 models (Sonnet 4 and Opus 4) in AWS Bedrock and Vertex AI providers
+1 -1
View File
@@ -51,7 +51,7 @@ Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthrop
### Use any API and Model
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, and Cerebras. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, and GCP Vertex. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
The extension also keeps track of total tokens and API usage cost for the entire task loop and individual requests, keeping you informed of spend every step of the way.
@@ -1,44 +0,0 @@
---
title: "VS Code Language Model API"
description: "Learn how to use Cline with the experimental VS Code Language Model API, enabling access to models from GitHub Copilot and other compatible extensions."
---
Cline offers _experimental_ support for the [VS Code Language Model API](https://code.visualstudio.com/api/extension-guides/language-model). This API enables extensions to grant access to language models directly within the VS Code environment. Consequently, you might be able to leverage models from:
- **GitHub Copilot:** Provided you have an active Copilot subscription and the extension installed.
- **Other VS Code Extensions:** Any extension that implements the Language Model API.
**Important Note:** This integration is currently in an experimental phase and might not perform as anticipated. Its functionality relies on other extensions correctly implementing the VS Code Language Model API.
### Prerequisites
- **VS Code:** The Language Model API is accessible via VS Code (it is not currently supported by Cursor).
- **A Language Model Provider Extension:** An extension that furnishes a language model is required. Examples include:
- **GitHub Copilot:** With a Copilot subscription, the GitHub Copilot and GitHub Copilot Chat extensions can serve as model providers.
- **Alternative Extensions:** Explore the VS Code Marketplace for extensions mentioning "Language Model API" or "lm". Other experimental options may be available.
### Configuration Steps
1. **Access Cline Settings:** Click the gear icon (⚙️) located in the Cline panel.
2. **Choose Provider:** Select "VS Code LM API" from the "API Provider" dropdown menu.
3. **Select Model:** The "Language Model" dropdown will (eventually) populate with available models. The naming convention is `vendor/family`. For instance, if Copilot is active, you might encounter options such as:
- `copilot - claude-3.5-sonnet`
- `copilot - o3-mini`
- `copilot - o1-ga`
- `copilot - gemini-2.0-flash`
### Current Limitations
- **Experimental API Status:** The VS Code Language Model API is still under active development. Anticipate potential changes and instability.
- **Dependency on Extensions:** This feature is entirely contingent on other extensions making models available. Cline does not directly control the list of accessible models.
- **Restricted Functionality:** The VS Code Language Model API might not encompass all features available through other API providers (e.g., image input capabilities, streaming responses, detailed usage metrics).
- **No Direct Cost Management:** Users are subject to the pricing structures and terms of service of the extension providing the model. Cline cannot directly monitor or regulate associated costs.
- **GitHub Copilot Rate Throttling:** When employing the VS Code LM API with GitHub Copilot, be mindful that GitHub may enforce rate limits on Copilot usage. These limitations are governed by GitHub, not Cline.
### Troubleshooting Tips
- **Models Not Appearing:**
- Confirm that VS Code is installed.
- Verify that a language model provider extension (e.g., GitHub Copilot, GitHub Copilot Chat) is installed and enabled.
- If utilizing Copilot, ensure you have previously sent a Copilot Chat message using the desired model.
- **Unexpected Operation:** Should you encounter unforeseen behavior, it is likely an issue stemming from the underlying Language Model API or the provider extension. Consider reporting the problem to the developers of the provider extension.
+1 -2
View File
@@ -148,8 +148,7 @@
"custom-model-configs/aws-bedrock-with-credentials-authentication",
"custom-model-configs/aws-bedrock-with-profile-authentication",
"custom-model-configs/gcp-vertex-ai",
"custom-model-configs/litellm-and-cline-using-codestral",
"custom-model-configs/vscode-language-model-api"
"custom-model-configs/litellm-and-cline-using-codestral"
]
},
{
+27 -27
View File
@@ -13,13 +13,35 @@ Before you jump into coding, make sure you have these essentials ready:
A popular, free, and powerful code editor.
- [<u>Download VS Code</u>](https://code.visualstudio.com/)
- [Download VS Code](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](https://www.youtube.com/watch?v=MlIzFUI1QGA)
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
> ✅ **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
#### 2. **Organize Your Projects**
#### 2. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.
📺 **Recommended YouTube Tutorials:**
- **For macOS:**
- [Install Homebrew on Mac](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [Install Git on MacOS 2024](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [Install Node.js on Mac (M1 | M2 | M3)](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [Install Git on Windows 10/11 (2024)](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [Install Node.js in Windows 10/11](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
#### 3. **Organize Your Projects**
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
@@ -33,36 +55,14 @@ Inside your `Cline` folder, structure projects clearly:
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 3. **Install the Cline VS Code Extension**
#### 4. **Install the Cline VS Code Extension**
Enhance your coding workflow by installing the Cline extension directly within VS Code:
- Get Started with Cline Extension Tutorial
📺 **Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](https://www.youtube.com/watch?v=E7trgwZa-mk)
📺 **Recommended YouTube Tutorial:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
> ✅ **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
#### 4. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 [<u>Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.</u>](https://docs.cline.bot/getting-started/installing-dev-essentials#installing-dev-essentials)
📺 **Recommended YouTube Tutorials for Manual Installation:**
- **For macOS:**
- [<u>Install Homebrew on Mac</u>](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [<u>Install Git on macOS 2024</u>](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [<u>Install Node.js on Mac (M1 | M2 | M3)</u>](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [<u>Install Git on Windows 10/11 (2024)</u>](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [<u>Install Node.js in Windows 10/11</u>](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
@@ -69,9 +69,9 @@ Choose your AI assistant based on your needs:
### Getting Started
1. Install the development essentials:
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/getting-started-new-coders/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/cline-memory-bank)
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)
- Create an empty `cline_docs` folder in your project root
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
- Tell Cline to "initialize memory bank"
@@ -197,20 +197,20 @@ git push origin main # Upload to GitHub
1. **Start of day**: Get latest changes
```bash
git pull origin main # Download latest code
bashCopygit pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
git add .
bashCopygit add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
git push origin main # Upload to GitHub
bashCopygit push origin main # Upload to GitHub
```
**Best Practices**
@@ -38,7 +38,7 @@ Cline actively builds context in two ways:
- Guide focus areas
- Share design thoughts and requirements
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/features/plan-and-act) mode.
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) mode.
### Context & Context Windows
@@ -93,7 +93,7 @@ Context files help maintain understanding across sessions. They serve as documen
#### Approaches to Context Files
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/prompting/cline-memory-bank)**)**
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
- Living documentation that evolves with your project
- Updated as architecture and patterns emerge
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
@@ -151,7 +151,7 @@ Context files help maintain understanding across sessions. They serve as documen
- Use Plan mode for complex discussions
- Start fresh sessions when needed
3. **Team Projects**
- Share common context files (consider using [.clinerules](https://docs.cline.bot/features/cline-rules) files in project roots)
- Share common context files (consider using [.clinerules](https://docs.cline.bot/improving-your-prompting-skills/prompting) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
@@ -1,174 +0,0 @@
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
@@ -1,16 +0,0 @@
// 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",
},
},
},
}
@@ -1,216 +0,0 @@
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
@@ -1,31 +0,0 @@
{
"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
@@ -1,16 +0,0 @@
{
"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"]
}
+49 -1736
View File
File diff suppressed because it is too large Load Diff
+11 -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.8",
"version": "3.17.2",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -58,7 +58,13 @@
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "!isMac"
"when": "isWindows"
},
{
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "isLinux || !isMac && !isWindows"
}
]
},
@@ -277,9 +283,9 @@
"postprotos": "prettier src/shared/proto src/core/controller webview-ui/src/services src/standalone/server-setup.ts --write --log-level silent",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint",
"pretest": "npm run compile-tests && npm run compile && npm run lint",
"check-types": "npm run protos && tsc --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && cd webview-ui && npm run lint",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts",
"format": "prettier . --check",
"format:fix": "prettier . --write",
"test": "npm-run-all test:unit test:integration",
@@ -316,15 +322,13 @@
"@types/turndown": "^5.0.5",
"@types/vscode": "^1.84.0",
"@typescript-eslint/eslint-plugin": "^7.14.1",
"@typescript-eslint/parser": "^7.18.0",
"@typescript-eslint/utils": "^8.33.0",
"@typescript-eslint/parser": "^7.11.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",
@@ -345,7 +349,6 @@
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
"@google/genai": "^0.13.0",
"@grpc/grpc-js": "^1.9.15",
@@ -359,7 +362,6 @@
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@vscode/codicons": "^0.0.36",
"archiver": "^7.0.1",
"axios": "^1.8.2",
@@ -369,7 +371,6 @@
"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",
-3
View File
@@ -16,7 +16,4 @@ service AccountService {
// Handles the user clicking the logout button in the UI.
// Clears API keys and user state.
rpc accountLogoutClicked(EmptyRequest) returns (Empty);
// Subscribe to auth callback events (when authentication tokens are received)
rpc subscribeToAuthCallback(EmptyRequest) returns (stream String);
}
-36
View File
@@ -6,44 +6,11 @@ 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, "..")
@@ -75,9 +42,6 @@ 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")
-5
View File
@@ -58,8 +58,3 @@ message Boolean {
message StringArray {
repeated string values = 1;
}
message StringArrays {
repeated string values1 = 1;
repeated string values2 = 2;
}
-3
View File
@@ -31,9 +31,6 @@ service FileService {
// Select images from the file system and return as data URLs
rpc selectImages(EmptyRequest) returns (StringArray);
// Select images and other files from the file system and returns as data URLs & paths respectively
rpc selectFiles(BooleanRequest) returns (StringArrays);
// Convert URIs to workspace-relative paths
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
-1
View File
@@ -15,7 +15,6 @@ service McpService {
rpc deleteMcpServer(StringRequest) returns (McpServers);
rpc toggleToolAutoApprove(ToggleToolAutoApproveRequest) returns (McpServers);
rpc refreshMcpMarketplace(EmptyRequest) returns (McpMarketplaceCatalog);
rpc openMcpSettings(EmptyRequest) returns (Empty);
}
message ToggleMcpServerRequest {
-3
View File
@@ -1,7 +1,5 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
@@ -39,7 +37,6 @@ message ChatSettings {
message ChatContent {
optional string message = 1;
repeated string images = 2;
repeated string files = 3;
}
// Message for auto approval settings
-4
View File
@@ -11,8 +11,6 @@ service TaskService {
rpc cancelTask(EmptyRequest) returns (Empty);
// Clears the current task
rpc clearTask(EmptyRequest) returns (Empty);
// Gets the total size of all tasks
rpc getTotalTasksSize(EmptyRequest) returns (Int64);
// Deletes multiple tasks with the given IDs
rpc deleteTasksWithIds(StringArrayRequest) returns (Empty);
// Creates a new task with the given text and optional images
@@ -40,7 +38,6 @@ message NewTaskRequest {
Metadata metadata = 1;
string text = 2;
repeated string images = 3;
repeated string files = 4;
}
// Request message for toggling task favorite status
@@ -105,5 +102,4 @@ message AskResponseRequest {
string response_type = 2;
string text = 3;
repeated string images = 4;
repeated string files = 5;
}
-18
View File
@@ -6,18 +6,6 @@ option java_multiple_files = true;
import "common.proto";
// Enum for webview provider types
enum WebviewProviderType {
SIDEBAR = 0;
TAB = 1;
}
// Define a new message type for webview provider info
message WebviewProviderTypeRequest {
Metadata metadata = 1;
WebviewProviderType providerType = 2;
}
// UiService provides methods for managing UI interactions
service UiService {
// Scrolls to a specific settings section in the settings view
@@ -25,10 +13,4 @@ service UiService {
// Marks the current announcement as shown and returns whether an announcement should still be shown
rpc onDidShowAnnouncement(EmptyRequest) returns (Boolean);
// Subscribe to addToInput events (when user adds content via context menu)
rpc subscribeToAddToInput(EmptyRequest) returns (stream String);
// Subscribe to MCP button clicked events
rpc subscribeToMcpButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
}
-1
View File
@@ -9,7 +9,6 @@ import "common.proto";
service WebService {
rpc checkIsImageUrl(StringRequest) returns (IsImageUrl);
rpc fetchOpenGraphData(StringRequest) returns (OpenGraphData);
rpc openInBrowser(StringRequest) returns (Empty);
}
message IsImageUrl {
-3
View File
@@ -24,7 +24,6 @@ import { FireworksHandler } from "./providers/fireworks"
import { AskSageHandler } from "./providers/asksage"
import { XAIHandler } from "./providers/xai"
import { SambanovaHandler } from "./providers/sambanova"
import { CerebrasHandler } from "./providers/cerebras"
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
@@ -85,8 +84,6 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
return new XAIHandler(options)
case "sambanova":
return new SambanovaHandler(options)
case "cerebras":
return new CerebrasHandler(options)
default:
return new AnthropicHandler(options)
}
+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
+2 -13
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,19 +223,8 @@ 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(providerOptions)
const providerChain = fromNodeProviderChain()
return await AwsBedrockHandler.withTempEnv(
() => {
AwsBedrockHandler.setEnv("AWS_REGION", this.options.awsRegion)
-169
View File
@@ -1,169 +0,0 @@
import { Anthropic } from "@anthropic-ai/sdk"
import Cerebras from "@cerebras/cerebras_cloud_sdk"
import { withRetry } from "../retry"
import { ApiHandlerOptions, ModelInfo, CerebrasModelId, cerebrasDefaultModelId, cerebrasModels } from "@shared/api"
import { ApiHandler } from "../index"
import { ApiStream } from "@api/transform/stream"
export class CerebrasHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Cerebras
constructor(options: ApiHandlerOptions) {
this.options = options
// Clean and validate the API key
const cleanApiKey = this.options.cerebrasApiKey?.trim()
if (!cleanApiKey) {
throw new Error("Cerebras API key is required")
}
this.client = new Cerebras({
apiKey: cleanApiKey,
timeout: 30000, // 30 second timeout
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
// Convert Anthropic messages to Cerebras format
const cerebrasMessages: Array<{
role: "system" | "user" | "assistant"
content: string
}> = [{ role: "system", content: systemPrompt }]
// Convert Anthropic messages to Cerebras format
for (const message of messages) {
if (message.role === "user") {
const content = Array.isArray(message.content)
? message.content
.map((block) => {
if (block.type === "text") {
return block.text
} else if (block.type === "image") {
return "[Image content not supported in Cerebras]"
}
return ""
})
.join("\n")
: message.content
cerebrasMessages.push({ role: "user", content })
} else if (message.role === "assistant") {
const content = Array.isArray(message.content)
? message.content
.map((block) => {
if (block.type === "text") {
return block.text
}
return ""
})
.join("\n")
: message.content || ""
cerebrasMessages.push({ role: "assistant", content })
}
}
try {
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: cerebrasMessages,
temperature: 0,
stream: true,
})
// Handle streaming response
let reasoning: string | null = null // Track reasoning content for models that support thinking
const modelId = this.getModel().id
const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill")
for await (const chunk of stream as any) {
// Type assertion for the streaming chunk
const streamChunk = chunk as any
if (streamChunk.choices?.[0]?.delta?.content) {
const content = streamChunk.choices[0].delta.content
// Handle reasoning models (Qwen and DeepSeek R1 Distill) that use <think> tags
if (isReasoningModel) {
// Check if we're entering or continuing reasoning mode
if (reasoning || content.includes("<think>")) {
reasoning = (reasoning || "") + content
// Clean the content by removing think tags for display
let cleanContent = content.replace(/<think>/g, "").replace(/<\/think>/g, "")
// Only yield reasoning content if there's actual content after cleaning
if (cleanContent.trim()) {
yield {
type: "reasoning",
reasoning: cleanContent,
}
}
// Check if reasoning is complete
if (reasoning.includes("</think>")) {
reasoning = null
}
} else {
// Regular content outside of thinking tags
yield {
type: "text",
text: content,
}
}
} else {
// Non-reasoning models - just yield text content
yield {
type: "text",
text: content,
}
}
}
// Handle usage information from Cerebras API
// Usage is typically only available in the final chunk
if (streamChunk.usage) {
const totalCost = this.calculateCost({
inputTokens: streamChunk.usage.prompt_tokens || 0,
outputTokens: streamChunk.usage.completion_tokens || 0,
})
yield {
type: "usage",
inputTokens: streamChunk.usage.prompt_tokens || 0,
outputTokens: streamChunk.usage.completion_tokens || 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
totalCost,
}
}
}
} catch (error) {
throw error
}
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in cerebrasModels) {
const id = modelId as CerebrasModelId
return { id, info: cerebrasModels[id] }
}
return {
id: cerebrasDefaultModelId,
info: cerebrasModels[cerebrasDefaultModelId],
}
}
private calculateCost({ inputTokens, outputTokens }: { inputTokens: number; outputTokens: number }): number {
const model = this.getModel()
const inputPrice = model.info.inputPrice || 0
const outputPrice = model.info.outputPrice || 0
const inputCost = (inputPrice / 1_000_000) * inputTokens
const outputCost = (outputPrice / 1_000_000) * outputTokens
return inputCost + outputCost
}
}
+1 -3
View File
@@ -80,9 +80,7 @@ export class OllamaHandler implements ApiHandler {
getModel(): { id: string; info: ModelInfo } {
return {
id: this.options.ollamaModelId || "",
info: this.options.ollamaApiOptionsCtxNum
? { ...openAiModelInfoSaneDefaults, contextWindow: Number(this.options.ollamaApiOptionsCtxNum) || 32768 }
: openAiModelInfoSaneDefaults,
info: openAiModelInfoSaneDefaults,
}
}
}
-4
View File
@@ -98,10 +98,6 @@ 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: chunk.usage.prompt_tokens || 0,
inputTokens: 0,
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
cacheReadTokens: chunk.usage.prompt_cache_hit_tokens || 0,
// @ts-ignore-next-line
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
}
-272
View File
@@ -1,272 +0,0 @@
import { JSONParser } from "@streamparser/json"
import * as fs from "fs"
import * as path from "path"
import * as os from "os"
// Fallback type definition based on the error message: "Property 'value' is optional in type 'ParsedElementInfo'"
type ParsedElementInfo = {
value?: any
key?: string | number
parent?: any
stack?: any[]
}
export interface ReplacementItem {
old_string: string
new_string: string
}
export interface ChangeLocation {
startLine: number
endLine: number
startChar: number
endChar: number
}
export class StreamingJsonReplacer {
private currentFileContent: string
private parser: JSONParser
private onContentUpdated: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void
private onErrorCallback: (error: Error) => void
private itemsProcessed: number = 0
private successfullyParsedItems: ReplacementItem[] = []
private logFilePath: string
constructor(
initialContent: string,
onContentUpdatedCallback: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void,
onErrorCallback: (error: Error) => void,
) {
// Initialize log file path
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
this.logFilePath = path.join(os.homedir(), "Documents", `streaming-json-replacer-debug-${timestamp}.log`)
// Initialize log file
this.log("StreamingJsonReplacer Debug Log Started", "INFO")
this.log("Timestamp: " + new Date().toISOString(), "INFO")
this.log("Constructor called with initial content length: " + initialContent.length, "INFO")
this.log("Initial content preview: " + initialContent.substring(0, 200) + "...", "INFO")
this.currentFileContent = initialContent
this.onContentUpdated = onContentUpdatedCallback
this.onErrorCallback = onErrorCallback
this.log("Initializing JSONParser with paths: ['$.*']", "INFO")
this.parser = new JSONParser({ paths: ["$.*"] })
this.parser.onValue = (parsedElementInfo: ParsedElementInfo) => {
this.log("onValue callback triggered")
this.log("parsedElementInfo: " + JSON.stringify(parsedElementInfo, null, 2))
const { value } = parsedElementInfo // Destructure to get value, which might be undefined
this.log("Extracted value: " + JSON.stringify(value))
this.log("Value type: " + typeof value)
// This callback is triggered for each item matched by '$.replacements.*'
if (value && typeof value === "object" && "old_string" in value && "new_string" in value) {
this.log("Found valid replacement item structure")
const item = value as ReplacementItem // Value here is confirmed to be an object
this.log("Replacement item: " + JSON.stringify(item, null, 2))
if (typeof item.old_string === "string" && typeof item.new_string === "string") {
this.log("Item has valid string types for old_string and new_string")
this.log("old_string length: " + item.old_string.length)
this.log("new_string length: " + item.new_string.length)
this.log(
"old_string preview: " +
(item.old_string.substring(0, 100) + (item.old_string.length > 100 ? "..." : "")),
)
this.log(
"new_string preview: " +
(item.new_string.substring(0, 100) + (item.new_string.length > 100 ? "..." : "")),
)
this.successfullyParsedItems.push(item) // Store the structurally valid item
this.log("Added item to successfullyParsedItems. Total count: " + this.successfullyParsedItems.length)
if (this.currentFileContent.includes(item.old_string)) {
this.log("old_string found in current file content - proceeding with replacement")
// Calculate the change location before making the replacement
const changeLocation = this.calculateChangeLocation(item.old_string, item.new_string)
this.log("Calculated change location: " + JSON.stringify(changeLocation))
const beforeLength = this.currentFileContent.length
this.currentFileContent = this.currentFileContent.replace(item.old_string, item.new_string)
const afterLength = this.currentFileContent.length
this.log("Content length before replacement: " + beforeLength)
this.log("Content length after replacement: " + afterLength)
this.log("Length difference: " + (afterLength - beforeLength))
this.itemsProcessed++
this.log("Incremented itemsProcessed to: " + this.itemsProcessed)
// Notify that an item has been processed. The `isFinalItem` argument here is tricky
// as we don't know from the parser alone if this is the *absolute* last item
// until the stream ends. The caller (Task.ts) will manage the final update.
// For now, we'll pass `false` and let Task.ts handle the final diff view update.
this.log("Calling onContentUpdated callback")
this.onContentUpdated(this.currentFileContent, false, changeLocation)
this.log("onContentUpdated callback completed")
} else {
this.log("old_string NOT found in current file content - generating error", "ERROR")
this.log("Current file content length: " + this.currentFileContent.length)
this.log("Current file content preview: " + this.currentFileContent.substring(0, 200) + "...")
const snippet = item.old_string.length > 50 ? item.old_string.substring(0, 47) + "..." : item.old_string
const error = new Error(`Streaming Replacement failed: 'old_string' not found. Snippet: "${snippet}"`)
this.log("Calling onErrorCallback with error: " + error.message, "ERROR")
this.onErrorCallback(error) // Call our own error callback
}
} else {
this.log(
"Invalid string types - old_string type: " +
typeof item.old_string +
", new_string type: " +
typeof item.new_string,
"ERROR",
)
const error = new Error(`Invalid item structure in replacements stream: ${JSON.stringify(item)}`)
this.log("Calling onErrorCallback with error: " + error.message, "ERROR")
this.onErrorCallback(error) // Call our own error callback
}
} else if (value && (Array.isArray(value) || (typeof value === "object" && "replacements" in value))) {
// This might be the 'replacements' array itself or the root object.
// The `paths: ['$.replacements.*']` should mean we only get items.
// If we get here, it's likely the root object if paths wasn't specific enough or if it's an empty replacements array.
this.log("Streaming parser emitted container: " + JSON.stringify(value))
this.log(
"Container type - isArray: " +
Array.isArray(value) +
", hasReplacements: " +
(typeof value === "object" && "replacements" in value),
)
} else {
// Value is not a ReplacementItem or a known container, could be an issue with the JSON structure or path.
// If `paths` is correct, this path should ideally not be hit often for valid streams.
this.log("Streaming parser emitted unexpected value: " + JSON.stringify(value), "WARN")
this.log("Unexpected value type: " + typeof value, "WARN")
this.log("Has old_string: " + (value && typeof value === "object" && "old_string" in value), "WARN")
this.log("Has new_string: " + (value && typeof value === "object" && "new_string" in value), "WARN")
}
}
this.parser.onError = (err: Error) => {
this.log("Parser onError callback triggered", "ERROR")
this.log("Error details: " + JSON.stringify(err), "ERROR")
this.log("Error message: " + err.message, "ERROR")
this.log("Error stack: " + err.stack, "ERROR")
// Propagate the error to the caller via the callback
this.log("Calling onErrorCallback with parser error", "ERROR")
this.onErrorCallback(err)
// Note: The @streamparser/json library might throw synchronously on write if onError is not set,
// or if it re-throws. We'll ensure Task.ts wraps write/end in try-catch.
}
this.log("Constructor completed - parser setup finished")
// Log to console where the debug file is located
console.log(`[StreamingJsonReplacer] Debug logging to file: ${this.logFilePath}`)
}
public write(jsonChunk: string): void {
this.log("write() called")
this.log("JSON chunk length: " + jsonChunk.length)
this.log("JSON chunk preview: " + jsonChunk.substring(0, 200) + (jsonChunk.length > 200 ? "..." : ""))
try {
// Errors during write will be caught by the parser's onError or thrown.
this.log("Calling parser.write()")
this.parser.write(jsonChunk)
this.log("parser.write() completed successfully")
} catch (error) {
this.log("Exception during parser.write(): " + error, "ERROR")
throw error
}
}
public getCurrentContent(): string {
this.log("getCurrentContent() called")
this.log("Current content length: " + this.currentFileContent.length)
return this.currentFileContent
}
public getSuccessfullyParsedItems(): ReplacementItem[] {
this.log("getSuccessfullyParsedItems() called")
this.log("Returning copy of " + this.successfullyParsedItems.length + " items")
return [...this.successfullyParsedItems] // Return a copy
}
private calculateChangeLocation(oldStr: string, newStr: string): ChangeLocation {
this.log("calculateChangeLocation() called")
this.log("oldStr length: " + oldStr.length)
this.log("newStr length: " + newStr.length)
this.log("oldStr preview: " + oldStr.substring(0, 50) + (oldStr.length > 50 ? "..." : ""))
this.log("newStr preview: " + newStr.substring(0, 50) + (newStr.length > 50 ? "..." : ""))
// Find the index where the old string starts
const startIndex = this.currentFileContent.indexOf(oldStr)
this.log("startIndex found: " + startIndex)
if (startIndex === -1) {
this.log("startIndex is -1 - old string not found in content!", "WARN")
this.log("This shouldn't happen since we already checked includes()", "WARN")
// This shouldn't happen since we already checked includes(), but just in case
return { startLine: 0, endLine: 0, startChar: 0, endChar: 0 }
}
// Calculate line numbers by counting newlines before the start index
const contentBeforeStart = this.currentFileContent.substring(0, startIndex)
this.log("contentBeforeStart length: " + contentBeforeStart.length)
const startLine = (contentBeforeStart.match(/\n/g) || []).length
this.log("calculated startLine: " + startLine)
// Calculate the end index after replacement
const endIndex = startIndex + oldStr.length
this.log("calculated endIndex: " + endIndex)
const contentBeforeEnd = this.currentFileContent.substring(0, endIndex)
this.log("contentBeforeEnd length: " + contentBeforeEnd.length)
const endLine = (contentBeforeEnd.match(/\n/g) || []).length
this.log("calculated endLine: " + endLine)
// Calculate character positions within their respective lines
const lastNewlineBeforeStart = contentBeforeStart.lastIndexOf("\n")
this.log("lastNewlineBeforeStart: " + lastNewlineBeforeStart)
const startChar = lastNewlineBeforeStart === -1 ? startIndex : startIndex - lastNewlineBeforeStart - 1
this.log("calculated startChar: " + startChar)
const lastNewlineBeforeEnd = contentBeforeEnd.lastIndexOf("\n")
this.log("lastNewlineBeforeEnd: " + lastNewlineBeforeEnd)
const endChar = lastNewlineBeforeEnd === -1 ? endIndex : endIndex - lastNewlineBeforeEnd - 1
this.log("calculated endChar: " + endChar)
const result = {
startLine,
endLine,
startChar,
endChar,
}
this.log("calculateChangeLocation() returning: " + JSON.stringify(result))
return result
}
private log(message: string, level: "INFO" | "WARN" | "ERROR" = "INFO"): void {
const timestamp = new Date().toISOString()
const logLine = `[${timestamp}] [${level}] ${message}\n`
try {
fs.appendFileSync(this.logFilePath, logLine)
} catch (error) {
// Fallback to console if file logging fails
console.error("Failed to write to log file:", error)
console.log(`[${level}] ${message}`)
}
}
}
+1 -2
View File
@@ -1,6 +1,6 @@
export type AssistantMessageContent = TextContent | ToolUse
export { parseAssistantMessageV1, parseAssistantMessageV2, parseAssistantMessageV3 } from "./parse-assistant-message"
export { parseAssistantMessageV1, parseAssistantMessageV2 } from "./parse-assistant-message"
export interface TextContent {
type: "text"
@@ -27,7 +27,6 @@ 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" | ...)
@@ -473,621 +473,3 @@ export function parseAssistantMessageV2(assistantMessage: string): AssistantMess
return contentBlocks
}
export function parseAssistantMessageV3(assistantMessage: string): AssistantMessageContent[] {
const contentBlocks: AssistantMessageContent[] = []
let currentTextContentStart = 0 // Index where the current text block started
let currentTextContent: TextContent | undefined = undefined
let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use
let currentToolUse: ToolUse | undefined = undefined
let currentParamValueStart = 0 // Index *after* the opening tag of the current param
let currentParamName: ToolParamName | undefined = undefined
// Precompute tags for faster lookups
const toolUseOpenTags = new Map<string, ToolUseName>()
const toolParamOpenTags = new Map<string, ToolParamName>()
for (const name of toolUseNames) {
toolUseOpenTags.set(`<${name}>`, name)
}
for (const name of toolParamNames) {
toolParamOpenTags.set(`<${name}>`, name)
}
// Function calls format detection
const isFunctionCallsOpen = "<function_calls>"
const isFunctionCallsClose = "</function_calls>"
const isInvokeStart = '<invoke name="'
const isInvokeEnd = '">'
const isInvokeClose = "</invoke>"
const isParameterStart = '<parameter name="'
const isParameterNameEnd = '">'
const isParameterClose = "</parameter>"
// Variables for function calls parsing
let inFunctionCalls = false
let currentInvokeName = ""
let currentParameterName = ""
const len = assistantMessage.length
for (let i = 0; i < len; i++) {
const currentCharIndex = i
// --- State: Parsing Function Calls ---
// Check for opening function_calls tag
if (
!inFunctionCalls &&
currentCharIndex >= isFunctionCallsOpen.length - 1 &&
assistantMessage.startsWith(isFunctionCallsOpen, currentCharIndex - isFunctionCallsOpen.length + 1)
) {
// End current text block if one was active
if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(currentTextContentStart, currentCharIndex - isFunctionCallsOpen.length + 1)
.trim()
currentTextContent.partial = false
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
}
inFunctionCalls = true
continue
}
// Check for invoke start within function_calls
if (
inFunctionCalls &&
currentInvokeName === "" &&
!currentToolUse && // Don't create a new tool if we already have one
currentCharIndex >= isInvokeStart.length - 1 &&
assistantMessage.startsWith(isInvokeStart, currentCharIndex - isInvokeStart.length + 1)
) {
// Find the end of the invoke name
const nameEndPos = assistantMessage.indexOf(isInvokeEnd, currentCharIndex + 1)
if (nameEndPos !== -1) {
// Extract the invoke name
currentInvokeName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
i = nameEndPos + isInvokeEnd.length - 1 // Skip to after the '">
// If this is an LS invoke, create a list_files tool
if (currentInvokeName === "LS") {
currentToolUse = {
type: "tool_use",
name: "list_files",
params: {},
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,
}
}
// If this is a MultiEdit invoke, create a replace_in_file tool
if (currentInvokeName === "MultiEdit") {
currentToolUse = {
type: "tool_use",
name: "replace_in_file",
params: {},
partial: true,
}
}
continue
}
}
// Check for parameter start within invoke
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentParameterName === "" &&
currentCharIndex >= isParameterStart.length - 1 &&
assistantMessage.startsWith(isParameterStart, currentCharIndex - isParameterStart.length + 1)
) {
// Find the end of the parameter name
const nameEndPos = assistantMessage.indexOf(isParameterNameEnd, currentCharIndex + 1)
if (nameEndPos !== -1) {
// Extract the parameter name
currentParameterName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
currentParamValueStart = nameEndPos + isParameterNameEnd.length
i = nameEndPos + isParameterNameEnd.length - 1 // Skip to after the '">'
continue
}
}
// Check for parameter end
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentParameterName !== "" &&
currentCharIndex >= isParameterClose.length - 1 &&
assistantMessage.startsWith(isParameterClose, currentCharIndex - isParameterClose.length + 1)
) {
// Extract parameter value
const value = assistantMessage.slice(currentParamValueStart, currentCharIndex - isParameterClose.length + 1).trim()
// Map parameter to tool params
if (currentToolUse && currentInvokeName === "LS" && currentParameterName === "path") {
currentToolUse.params["path"] = value
// Default recursive to false - only show top level
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
}
}
// Map parameter to tool params for MultiEdit
if (currentToolUse && currentInvokeName === "MultiEdit") {
if (currentParameterName === "file_path") {
currentToolUse.params["path"] = value
} else if (currentParameterName === "edits") {
// Save the value to the diff parameter for replace_in_file
currentToolUse.params["diff"] = value
}
}
currentParameterName = ""
continue
}
// Check for invoke end
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentCharIndex >= isInvokeClose.length - 1 &&
assistantMessage.startsWith(isInvokeClose, currentCharIndex - isInvokeClose.length + 1)
) {
// If we have a tool use from this invoke, finalize it
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" ||
currentInvokeName === "MultiEdit")
) {
currentToolUse.partial = false
contentBlocks.push(currentToolUse)
currentToolUse = undefined
}
currentInvokeName = ""
continue
}
// Check for function_calls end
if (
inFunctionCalls &&
currentCharIndex >= isFunctionCallsClose.length - 1 &&
assistantMessage.startsWith(isFunctionCallsClose, currentCharIndex - isFunctionCallsClose.length + 1)
) {
inFunctionCalls = false
currentTextContentStart = currentCharIndex + 1
// Start a new text content block for any text after function_calls
currentTextContent = {
type: "text",
content: "",
partial: true,
}
continue
}
// Skip normal parsing when inside function_calls
if (inFunctionCalls) {
continue
}
// --- State: Parsing a Tool Parameter ---
if (currentToolUse && currentParamName) {
const closeTag = `</${currentParamName}>`
// Check if the string *ending* at index `i` matches the closing tag
if (
currentCharIndex >= closeTag.length - 1 &&
assistantMessage.startsWith(
closeTag,
currentCharIndex - closeTag.length + 1, // Start checking from potential start of tag
)
) {
// Found the closing tag for the parameter
const value = assistantMessage
.slice(
currentParamValueStart, // Start after the opening tag
currentCharIndex - closeTag.length + 1, // End before the closing tag
)
.trim()
currentToolUse.params[currentParamName] = value
currentParamName = undefined // Go back to parsing tool content
// We don't continue loop here, need to check for tool close or other params at index i
} else {
continue // Still inside param value, move to next char
}
}
// --- State: Parsing a Tool Use (but not a specific parameter) ---
if (currentToolUse && !currentParamName) {
// Ensure we are not inside a parameter already
// Check if starting a new parameter
let startedNewParam = false
for (const [tag, paramName] of toolParamOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
currentParamName = paramName
currentParamValueStart = currentCharIndex + 1 // Value starts after the tag
startedNewParam = true
break
}
}
if (startedNewParam) {
continue // Handled start of param, move to next char
}
// Check if closing the current tool use
const toolCloseTag = `</${currentToolUse.name}>`
if (
currentCharIndex >= toolCloseTag.length - 1 &&
assistantMessage.startsWith(toolCloseTag, currentCharIndex - toolCloseTag.length + 1)
) {
// End of the tool use found
// Special handling for content params *before* finalizing the tool
const toolContentSlice = assistantMessage.slice(
currentToolUseStart, // From after the tool opening tag
currentCharIndex - toolCloseTag.length + 1, // To before the tool closing tag
)
// Check if content parameter needs special handling (write_to_file/new_rule)
// This check is important if the closing </content> tag was missed by the parameter parsing logic
// (e.g., if content is empty or parsing logic prioritizes tool close)
const contentParamName: ToolParamName = "content"
if (
currentToolUse.name === "write_to_file" /* || currentToolUse.name === "new_rule" */ &&
toolContentSlice.includes(`<${contentParamName}>`)
) {
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
const contentStart = toolContentSlice.indexOf(contentStartTag)
// Use lastIndexOf for robustness against nested tags
const contentEnd = toolContentSlice.lastIndexOf(contentEndTag)
if (contentStart !== -1 && contentEnd !== -1 && contentEnd > contentStart) {
const contentValue = toolContentSlice.slice(contentStart + contentStartTag.length, contentEnd).trim()
currentToolUse.params[contentParamName] = contentValue
}
}
currentToolUse.partial = false // Mark as complete
contentBlocks.push(currentToolUse)
currentToolUse = undefined // Reset state
currentTextContentStart = currentCharIndex + 1 // Potential text starts after this tag
continue // Move to next char
}
// If not starting a param and not closing the tool, continue accumulating tool content implicitly
continue
}
// --- State: Parsing Text / Looking for Tool Start ---
if (!currentToolUse) {
// Check if starting a new tool use
let startedNewTool = false
for (const [tag, toolName] of toolUseOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
// End current text block if one was active
if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(
currentTextContentStart, // From where text started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
currentTextContent.partial = false // Ended because tool started
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
} else {
// Check for any text between the last block and this tag
const potentialText = assistantMessage
.slice(
currentTextContentStart, // From where text *might* have started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
if (potentialText.length > 0) {
contentBlocks.push({
type: "text",
content: potentialText,
partial: false,
})
}
}
// Start the new tool use
currentToolUse = {
type: "tool_use",
name: toolName,
params: {},
partial: true, // Assume partial until closing tag is found
}
currentToolUseStart = currentCharIndex + 1 // Tool content starts after the opening tag
startedNewTool = true
break
}
}
if (startedNewTool) {
continue // Handled start of tool, move to next char
}
// If not starting a tool, it must be text content
if (!currentTextContent) {
// Start a new text block if we aren't already in one
currentTextContentStart = currentCharIndex // Text starts at the current character
// Check if the current char is the start of potential text *immediately* after a tag
// This needs the previous state - simpler to let slicing handle it later.
// Resetting start index accurately is key.
// It should be the index *after* the last processed tag.
// The logic managing currentTextContentStart after closing tags handles this.
currentTextContent = {
type: "text",
content: "", // Will be determined by slicing at the end or when a tool starts
partial: true,
}
}
// Continue accumulating text implicitly; content is extracted later.
}
} // End of loop
// --- Finalization after loop ---
// Finalize any open parameter within an open tool use
if (currentToolUse && currentParamName) {
currentToolUse.params[currentParamName] = assistantMessage
.slice(currentParamValueStart) // From param start to end of string
.trim()
// Tool use remains partial
}
// Finalize any open tool use (which might contain the finalized partial param)
if (currentToolUse) {
// Tool use is partial because the loop finished before its closing tag
contentBlocks.push(currentToolUse)
}
// Finalize any trailing text content
// Only possible if a tool use wasn't open at the very end
else if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(currentTextContentStart) // From text start to end of string
.trim()
// Text is partial because the loop finished
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
}
return contentBlocks
}
@@ -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, _: EmptyRequest): Promise<String> {
export async function accountLoginClicked(controller: Controller, unused: 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, _: EmptyReques
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
await vscode.env.openExternal(authUrl)
return String.create({
return {
value: authUrl.toString(),
})
}
}
@@ -1,4 +1,4 @@
import { Empty } from "../../../shared/proto/common"
import type { 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 Empty.create({})
return {}
}
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create account service registry
const accountService = createServiceRegistry("account")
// Export the method handler types and registration function
export type AccountMethodHandler = ServiceMethodHandler
export type AccountStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = accountService.registerMethod
// Export the request handlers
export const handleAccountServiceRequest = accountService.handleRequest
export const handleAccountServiceStreamingRequest = accountService.handleStreamingRequest
export const isStreamingMethod = accountService.isStreamingMethod
// Register all account methods
registerAllMethods()
+14
View File
@@ -0,0 +1,14 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { accountLoginClicked } from "./accountLoginClicked"
import { accountLogoutClicked } from "./accountLogoutClicked"
// Register all account service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("accountLoginClicked", accountLoginClicked)
registerMethod("accountLogoutClicked", accountLogoutClicked)
}
@@ -1,59 +0,0 @@
import { Controller } from "../index"
import { EmptyRequest } from "../../../shared/proto/common"
import { String as ProtoString } from "../../../shared/proto/common"
import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler"
// Keep track of active authCallback subscriptions
const activeAuthCallbackSubscriptions = new Set<StreamingResponseHandler>()
/**
* Subscribe to authCallback events
* @param controller The controller instance
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToAuthCallback(
controller: Controller,
request: EmptyRequest,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
// Add this subscription to the active subscriptions
activeAuthCallbackSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeAuthCallbackSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "authCallback_subscription" }, responseStream)
}
}
/**
* Send an authCallback event to all active subscribers
* @param customToken The custom token for authentication
*/
export async function sendAuthCallbackEvent(customToken: string): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeAuthCallbackSubscriptions).map(async (responseStream) => {
try {
const event: ProtoString = {
value: customToken,
}
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending authCallback event:", error)
// Remove the subscription if there was an error
activeAuthCallbackSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
@@ -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 BrowserConnection.create({
return {
success: true,
message: `Successfully discovered and connected to Chrome at ${discoveredHost}`,
endpoint: result.endpoint || "",
})
}
} else {
return BrowserConnection.create({
return {
success: false,
message:
"No Chrome instances found. Make sure Chrome is running with remote debugging enabled (--remote-debugging-port=9222).",
endpoint: "",
})
}
}
} catch (error) {
return BrowserConnection.create({
return {
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, _: EmptyRequest): Promise<BrowserConnectionInfo> {
export async function getBrowserConnectionInfo(controller: Controller, request: 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, _: EmptyR
const connectionInfo = browserSession.getConnectionInfo()
// Convert from BrowserSession.BrowserConnectionInfo to proto.BrowserConnectionInfo
return BrowserConnectionInfo.create({
return {
isConnected: connectionInfo.isConnected,
isRemote: connectionInfo.isRemote,
host: connectionInfo.host || "", // Ensure host is never undefined
})
}
}
// Fallback to browser settings if no active browser session
return BrowserConnectionInfo.create({
return {
isConnected: false,
isRemote: !!browserSettings.remoteBrowserEnabled,
host: browserSettings.remoteBrowserHost || "",
})
}
} catch (error: unknown) {
console.error("Error getting browser connection info:", error)
return BrowserConnectionInfo.create({
return {
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, _: EmptyRequest): Promise<ChromePath> {
export async function getDetectedChromePath(controller: Controller, request: EmptyRequest): Promise<ChromePath> {
try {
const { browserSettings } = await getAllExtensionState(controller.context)
const browserSession = new BrowserSession(controller.context, browserSettings)
const result = await browserSession.getDetectedChromePath()
return ChromePath.create({
return {
path: result.path,
isBundled: result.isBundled,
})
}
} catch (error) {
console.error("Error getting detected Chrome path:", error)
return ChromePath.create({
return {
path: "",
isBundled: false,
})
}
}
}
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create browser service registry
const browserService = createServiceRegistry("browser")
// Export the method handler types and registration function
export type BrowserMethodHandler = ServiceMethodHandler
export type BrowserStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = browserService.registerMethod
// Export the request handlers
export const handleBrowserServiceRequest = browserService.handleRequest
export const handleBrowserServiceStreamingRequest = browserService.handleStreamingRequest
export const isStreamingMethod = browserService.isStreamingMethod
// Register all browser methods
registerAllMethods()
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { discoverBrowser } from "./discoverBrowser"
import { getBrowserConnectionInfo } from "./getBrowserConnectionInfo"
import { getDetectedChromePath } from "./getDetectedChromePath"
import { relaunchChromeDebugMode } from "./relaunchChromeDebugMode"
import { testBrowserConnection } from "./testBrowserConnection"
import { updateBrowserSettings } from "./updateBrowserSettings"
// Register all browser service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("discoverBrowser", discoverBrowser)
registerMethod("getBrowserConnectionInfo", getBrowserConnectionInfo)
registerMethod("getDetectedChromePath", getDetectedChromePath)
registerMethod("relaunchChromeDebugMode", relaunchChromeDebugMode)
registerMethod("testBrowserConnection", testBrowserConnection)
registerMethod("updateBrowserSettings", updateBrowserSettings)
}
@@ -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, _: EmptyRequest): Promise<StringMessage> {
export async function relaunchChromeDebugMode(controller: Controller, request: 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, _: EmptyRe
// The actual result will be sent via postMessageToWebview in the BrowserSession.relaunchChromeDebugMode method
// Here we just return a message as a placeholder
return StringMessage.create({
return {
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 BrowserConnection.create({
return {
success: result.success,
message: `Auto-discovered and tested connection to Chrome at ${discoveredHost}: ${result.message}`,
endpoint: result.endpoint || "",
})
}
} else {
return BrowserConnection.create({
return {
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 BrowserConnection.create({
return {
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 BrowserConnection.create({
return {
success: result.success,
message: result.message,
endpoint: result.endpoint || "",
})
}
}
} catch (error) {
return BrowserConnection.create({
return {
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 Boolean.create({
return {
value: true,
})
}
} catch (error) {
console.error("Error updating browser settings:", error)
return Boolean.create({
return {
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 Empty.create({})
return {}
}
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create checkpoints service registry
const checkpointsService = createServiceRegistry("checkpoints")
// Export the method handler types and registration function
export type CheckpointsMethodHandler = ServiceMethodHandler
export type CheckpointsStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = checkpointsService.registerMethod
// Export the request handlers
export const handleCheckpointsServiceRequest = checkpointsService.handleRequest
export const handleCheckpointsServiceStreamingRequest = checkpointsService.handleStreamingRequest
export const isStreamingMethod = checkpointsService.isStreamingMethod
// Register all checkpoints methods
registerAllMethods()
@@ -0,0 +1,14 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { checkpointDiff } from "./checkpointDiff"
import { checkpointRestore } from "./checkpointRestore"
// Register all checkpoints service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("checkpointDiff", checkpointDiff)
registerMethod("checkpointRestore", checkpointRestore)
}
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create file service registry
const fileService = createServiceRegistry("file")
// Export the method handler types and registration function
export type FileMethodHandler = ServiceMethodHandler
export type FileStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = fileService.registerMethod
// Export the request handlers
export const handleFileServiceRequest = fileService.handleRequest
export const handleFileServiceStreamingRequest = fileService.handleStreamingRequest
export const isStreamingMethod = fileService.isStreamingMethod
// Register all file methods
registerAllMethods()
+38
View File
@@ -0,0 +1,38 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { copyToClipboard } from "./copyToClipboard"
import { createRuleFile } from "./createRuleFile"
import { deleteRuleFile } from "./deleteRuleFile"
import { getRelativePaths } from "./getRelativePaths"
import { openFile } from "./openFile"
import { openImage } from "./openImage"
import { openMention } from "./openMention"
import { refreshRules } from "./refreshRules"
import { searchCommits } from "./searchCommits"
import { searchFiles } from "./searchFiles"
import { selectImages } from "./selectImages"
import { toggleClineRule } from "./toggleClineRule"
import { toggleCursorRule } from "./toggleCursorRule"
import { toggleWindsurfRule } from "./toggleWindsurfRule"
// Register all file service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("copyToClipboard", copyToClipboard)
registerMethod("createRuleFile", createRuleFile)
registerMethod("deleteRuleFile", deleteRuleFile)
registerMethod("getRelativePaths", getRelativePaths)
registerMethod("openFile", openFile)
registerMethod("openImage", openImage)
registerMethod("openMention", openMention)
registerMethod("refreshRules", refreshRules)
registerMethod("searchCommits", searchCommits)
registerMethod("searchFiles", searchFiles)
registerMethod("selectImages", selectImages)
registerMethod("toggleClineRule", toggleClineRule)
registerMethod("toggleCursorRule", toggleCursorRule)
registerMethod("toggleWindsurfRule", toggleWindsurfRule)
}
+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 RefreshedRules.create({
return {
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
-21
View File
@@ -1,21 +0,0 @@
import { Controller } from ".."
import { BooleanRequest, StringArrays } from "@shared/proto/common"
import { selectFiles as selectFilesIntegration } from "@integrations/misc/process-files"
import { FileMethodHandler } from "./index"
/**
* Prompts the user to select images from the file system and returns them as data URLs
* @param controller The controller instance
* @param request Boolean request, with the value defining whether this model supports images
* @returns Two arrays of image data URLs and other file paths
*/
export const selectFiles: FileMethodHandler = async (controller: Controller, request: BooleanRequest): Promise<StringArrays> => {
try {
const { images, files } = await selectFilesIntegration(request.value)
return StringArrays.create({ values1: images, values2: files })
} catch (error) {
console.error("Error selecting images & files:", error)
// Return empty array on error
return StringArrays.create({ values1: [], values2: [] })
}
}
+3 -4
View File
@@ -1,5 +1,4 @@
import { ToggleClineRules } from "../../../shared/proto/file"
import type { ToggleClineRuleRequest } from "../../../shared/proto/file"
import type { ToggleClineRuleRequest, ClineRulesToggles, ToggleClineRules } 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"
@@ -37,8 +36,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 ToggleClineRules.create({
return {
globalClineRulesToggles: { toggles: globalToggles },
localClineRulesToggles: { toggles: localToggles },
})
}
}
+3 -4
View File
@@ -1,5 +1,4 @@
import type { ToggleCursorRuleRequest } from "../../../shared/proto/file"
import { ClineRulesToggles } from "../../../shared/proto/file"
import type { ToggleCursorRuleRequest, 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"
@@ -29,7 +28,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 ClineRulesToggles.create({
return {
toggles: cursorToggles,
})
}
}
@@ -1,5 +1,4 @@
import type { ToggleWindsurfRuleRequest } from "../../../shared/proto/file"
import { ClineRulesToggles } from "../../../shared/proto/file"
import type { ToggleWindsurfRuleRequest, 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"
@@ -27,5 +26,5 @@ export async function toggleWindsurfRule(controller: Controller, request: Toggle
await updateWorkspaceState(controller.context, "localWindsurfRulesToggles", toggles)
// Return the toggles directly
return ClineRulesToggles.create({ toggles: toggles })
return { toggles: toggles }
}
@@ -0,0 +1,80 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { Controller } from "./index"
import { StreamingResponseHandler } from "./grpc-handler"
import { handleAccountServiceRequest, handleAccountServiceStreamingRequest } from "./account/index"
import { handleBrowserServiceRequest, handleBrowserServiceStreamingRequest } from "./browser/index"
import { handleCheckpointsServiceRequest, handleCheckpointsServiceStreamingRequest } from "./checkpoints/index"
import { handleFileServiceRequest, handleFileServiceStreamingRequest } from "./file/index"
import { handleMcpServiceRequest, handleMcpServiceStreamingRequest } from "./mcp/index"
import { handleStateServiceRequest, handleStateServiceStreamingRequest } from "./state/index"
import { handleTaskServiceRequest, handleTaskServiceStreamingRequest } from "./task/index"
import { handleWebServiceRequest, handleWebServiceStreamingRequest } from "./web/index"
import { handleModelsServiceRequest, handleModelsServiceStreamingRequest } from "./models/index"
import { handleSlashServiceRequest, handleSlashServiceStreamingRequest } from "./slash/index"
import { handleUiServiceRequest, handleUiServiceStreamingRequest } from "./ui/index"
/**
* Configuration for a service handler
*/
export interface ServiceHandlerConfig {
requestHandler: (controller: Controller, method: string, message: any) => Promise<any>
streamingHandler: (
controller: Controller,
method: string,
message: any,
responseStream: StreamingResponseHandler,
requestId?: string,
) => Promise<void>
}
/**
* Map of service names to their handler configurations
*/
export const serviceHandlers: Record<string, ServiceHandlerConfig> = {
"cline.AccountService": {
requestHandler: handleAccountServiceRequest,
streamingHandler: handleAccountServiceStreamingRequest,
},
"cline.BrowserService": {
requestHandler: handleBrowserServiceRequest,
streamingHandler: handleBrowserServiceStreamingRequest,
},
"cline.CheckpointsService": {
requestHandler: handleCheckpointsServiceRequest,
streamingHandler: handleCheckpointsServiceStreamingRequest,
},
"cline.FileService": {
requestHandler: handleFileServiceRequest,
streamingHandler: handleFileServiceStreamingRequest,
},
"cline.McpService": {
requestHandler: handleMcpServiceRequest,
streamingHandler: handleMcpServiceStreamingRequest,
},
"cline.StateService": {
requestHandler: handleStateServiceRequest,
streamingHandler: handleStateServiceStreamingRequest,
},
"cline.TaskService": {
requestHandler: handleTaskServiceRequest,
streamingHandler: handleTaskServiceStreamingRequest,
},
"cline.WebService": {
requestHandler: handleWebServiceRequest,
streamingHandler: handleWebServiceStreamingRequest,
},
"cline.ModelsService": {
requestHandler: handleModelsServiceRequest,
streamingHandler: handleModelsServiceStreamingRequest,
},
"cline.SlashService": {
requestHandler: handleSlashServiceRequest,
streamingHandler: handleSlashServiceStreamingRequest,
},
"cline.UiService": {
requestHandler: handleUiServiceRequest,
streamingHandler: handleUiServiceStreamingRequest,
},
}
+103 -28
View File
@@ -23,7 +23,7 @@ import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { ApiProvider, ModelInfo } from "@shared/api"
import { ChatContent } from "@shared/ChatContent"
import { ChatSettings } from "@shared/ChatSettings"
import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage"
import { ExtensionMessage, ExtensionState, Invoke, Platform } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { McpDownloadResponse, McpMarketplaceCatalog, McpServer } from "@shared/mcp"
import { TelemetrySetting } from "@shared/TelemetrySetting"
@@ -52,8 +52,6 @@ import {
import { Task, cwd } from "../task"
import { ClineRulesToggles } from "@shared/cline-rules"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendAddToInputEvent } from "./ui/subscribeToAddToInput"
import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback"
import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules"
import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules"
import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows"
@@ -109,7 +107,9 @@ 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) {
@@ -118,6 +118,7 @@ export class Controller {
}
this.workspaceTracker.dispose()
this.mcpHub.dispose()
this.outputChannel.appendLine("Disposed all disposables")
console.error("Controller disposed")
}
@@ -139,7 +140,7 @@ export class Controller {
await updateGlobalState(this.context, "userInfo", info)
}
async initTask(task?: string, images?: string[], files?: string[], historyItem?: HistoryItem) {
async initTask(task?: string, images?: string[], historyItem?: HistoryItem) {
await this.clearTask() // ensures that an existing task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
const {
apiConfiguration,
@@ -186,7 +187,6 @@ export class Controller {
customInstructions,
task,
images,
files,
historyItem,
)
}
@@ -194,7 +194,7 @@ export class Controller {
async reinitExistingTaskFromId(taskId: string) {
const history = await this.getTaskWithId(taskId)
if (history) {
await this.initTask(undefined, undefined, undefined, history.historyItem)
await this.initTask(undefined, undefined, history.historyItem)
}
}
@@ -261,7 +261,21 @@ export class Controller {
}
}
})
// If user already opted in to telemetry, enable telemetry service
this.getStateToPostToWebview().then((state) => {
const { telemetrySetting } = state
const isOptedIn = telemetrySetting !== "disabled"
telemetryService.updateTelemetryState(isOptedIn)
})
break
case "showChatView": {
this.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
break
}
case "newTask":
// Code that should run in response to the hello message command
//vscode.window.showInformationMessage(message.text!)
@@ -271,7 +285,7 @@ export class Controller {
// Could also do this in extension .ts
//this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
// initializing new instance of Cline will make sure that any agentically running promises in old instance don't affect our new task. this essentially creates a fresh slate for the new task
await this.initTask(message.text, message.images, message.files)
await this.initTask(message.text, message.images)
break
case "apiConfiguration":
if (message.apiConfiguration) {
@@ -282,10 +296,33 @@ export class Controller {
}
await this.postStateToWebview()
break
case "optionsResponse":
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: message.text,
})
break
case "openInBrowser":
if (message.url) {
vscode.env.openExternal(vscode.Uri.parse(message.url))
}
break
case "showAccountViewClicked": {
await this.postMessageToWebview({ type: "action", action: "accountButtonClicked" })
break
}
case "fetchUserCreditsData": {
await this.fetchUserCreditsData()
break
}
case "openMcpSettings": {
const mcpSettingsFilePath = await this.mcpHub?.getMcpSettingsFilePath()
if (mcpSettingsFilePath) {
await handleFileServiceRequest(this, "openFile", { value: mcpSettingsFilePath })
}
break
}
case "fetchMcpMarketplace": {
await this.fetchMcpMarketplace(message.bool)
break
@@ -343,10 +380,32 @@ export class Controller {
}
break
}
case "requestTotalTasksSize": {
this.refreshTotalTasksSize()
break
}
case "fetchLatestMcpServersFromHub": {
this.mcpHub?.sendLatestMcpServers()
break
}
case "openExtensionSettings": {
const settingsFilter = message.text || ""
await vscode.commands.executeCommand(
"workbench.action.openSettings",
`@ext:saoudrizwan.claude-dev ${settingsFilter}`.trim(), // trim whitespace if no settings filter
)
break
}
case "invoke": {
if (message.text) {
await this.postMessageToWebview({
type: "invoke",
invoke: message.text as Invoke,
})
}
break
}
// telemetry
case "telemetrySetting": {
if (message.telemetrySetting) {
@@ -409,9 +468,11 @@ export class Controller {
if (answer === "Delete All Except Favorites") {
await this.deleteNonFavoriteTaskHistory()
await this.postStateToWebview()
this.refreshTotalTasksSize()
} else if (answer === "Delete Everything") {
await this.deleteAllTaskHistory()
await this.postStateToWebview()
this.refreshTotalTasksSize()
}
this.postMessageToWebview({ type: "relinquishControl" })
break
@@ -428,13 +489,6 @@ export class Controller {
}
break
}
case "executeQuickWin":
if (message.payload) {
const { command, title } = message.payload
this.outputChannel.appendLine(`Received executeQuickWin: command='${command}', title='${title}'`)
await this.initTask(title)
}
break
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
@@ -601,12 +655,12 @@ export class Controller {
if (this.task.isAwaitingPlanResponse && didSwitchToActMode) {
this.task.didRespondToPlanAskBySwitchingMode = true
// Use chatContent if provided, otherwise use default message
await this.task.handleWebviewAskResponse(
"messageResponse",
chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
chatContent?.images || [],
chatContent?.files || [],
)
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
images: chatContent?.images,
})
} else {
this.cancelTask()
}
@@ -637,7 +691,7 @@ export class Controller {
// 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request
this.task.abandoned = true
}
await this.initTask(undefined, undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
await this.initTask(undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
// await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list
}
}
@@ -681,7 +735,10 @@ export class Controller {
await storeSecret(this.context, "clineApiKey", apiKey)
// Send custom token to webview for Firebase auth
await sendAuthCallbackEvent(customToken)
await this.postMessageToWebview({
type: "authCallback",
customToken,
})
const clineProvider: ApiProvider = "cline"
await updateGlobalState(this.context, "apiProvider", clineProvider)
@@ -753,7 +810,6 @@ export class Controller {
const response = await axios.get("https://api.cline.bot/v1/mcp/marketplace", {
headers: {
"Content-Type": "application/json",
"User-Agent": "cline-vscode-extension",
},
})
@@ -915,7 +971,10 @@ export class Controller {
input += `\nProblems:\n${problemsString}`
}
await sendAddToInputEvent(input)
await this.postMessageToWebview({
type: "addToInput",
text: input,
})
console.log("addSelectedCodeToChat", code, filePath, languageId)
}
@@ -933,7 +992,10 @@ export class Controller {
// terminalName
// })
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${output}\n\`\`\``)
await this.postMessageToWebview({
type: "addToInput",
text: `Terminal output:\n\`\`\`\n${output}\n\`\`\``,
})
console.log("addSelectedTerminalOutputToChat", output, terminalName)
}
@@ -1022,7 +1084,7 @@ export class Controller {
if (id !== this.task?.taskId) {
// non-current task
const { historyItem } = await this.getTaskWithId(id)
await this.initTask(undefined, undefined, undefined, historyItem) // clears existing task
await this.initTask(undefined, undefined, historyItem) // clears existing task
}
await this.postMessageToWebview({
type: "action",
@@ -1094,6 +1156,19 @@ export class Controller {
await this.postStateToWebview()
}
async refreshTotalTasksSize() {
getTotalTasksSize(this.context.globalStorageUri.fsPath)
.then((newTotalSize) => {
this.postMessageToWebview({
type: "totalTasksSize",
totalTasksSize: newTotalSize,
})
})
.catch((error) => {
console.error("Error calculating total tasks size:", error)
})
}
async deleteTaskWithId(id: string) {
console.info("deleteTaskWithId: ", id)
@@ -1136,7 +1211,7 @@ export class Controller {
console.debug(`Error deleting task:`, error)
}
await this.postStateToWebview()
this.refreshTotalTasksSize()
}
async deleteTaskFromState(id: string) {
@@ -1209,7 +1284,7 @@ export class Controller {
telemetrySetting,
planActSeparateModelsSetting,
enableCheckpointsSetting: enableCheckpointsSetting ?? true,
distinctId: telemetryService.distinctId,
vscMachineId: vscode.env.machineId,
globalClineRulesToggles: globalClineRulesToggles || {},
localClineRulesToggles: localClineRulesToggles || {},
localWindsurfRulesToggles: localWindsurfRulesToggles || {},
@@ -1,6 +1,5 @@
import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion"
import type { AddRemoteMcpServerRequest } from "../../../shared/proto/mcp"
import { McpServers } from "../../../shared/proto/mcp"
import type { AddRemoteMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
/**
@@ -24,7 +23,7 @@ export async function addRemoteMcpServer(controller: Controller, request: AddRem
const protoServers = convertMcpServersToProtoMcpServers(servers)
return McpServers.create({ mcpServers: protoServers })
return { 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 { McpServers } from "../../../shared/proto/mcp"
import type { 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.create({ mcpServers: protoServers })
return { mcpServers: protoServers }
} catch (error) {
console.error(`Failed to delete MCP server: ${error}`)
throw error
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create mcp service registry
const mcpService = createServiceRegistry("mcp")
// Export the method handler types and registration function
export type McpMethodHandler = ServiceMethodHandler
export type McpStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = mcpService.registerMethod
// Export the request handlers
export const handleMcpServiceRequest = mcpService.handleRequest
export const handleMcpServiceStreamingRequest = mcpService.handleStreamingRequest
export const isStreamingMethod = mcpService.isStreamingMethod
// Register all mcp methods
registerAllMethods()
+26
View File
@@ -0,0 +1,26 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { addRemoteMcpServer } from "./addRemoteMcpServer"
import { deleteMcpServer } from "./deleteMcpServer"
import { downloadMcp } from "./downloadMcp"
import { refreshMcpMarketplace } from "./refreshMcpMarketplace"
import { restartMcpServer } from "./restartMcpServer"
import { toggleMcpServer } from "./toggleMcpServer"
import { toggleToolAutoApprove } from "./toggleToolAutoApprove"
import { updateMcpTimeout } from "./updateMcpTimeout"
// Register all mcp service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("addRemoteMcpServer", addRemoteMcpServer)
registerMethod("deleteMcpServer", deleteMcpServer)
registerMethod("downloadMcp", downloadMcp)
registerMethod("refreshMcpMarketplace", refreshMcpMarketplace)
registerMethod("restartMcpServer", restartMcpServer)
registerMethod("toggleMcpServer", toggleMcpServer)
registerMethod("toggleToolAutoApprove", toggleToolAutoApprove)
registerMethod("updateMcpTimeout", updateMcpTimeout)
}
@@ -1,17 +0,0 @@
import { Controller } from ".."
import { Empty, EmptyRequest } from "@shared/proto/common"
import { openFile as openFileIntegration } from "@integrations/misc/open-file"
/**
* Opens the MCP settings file in the editor
* @param controller The controller instance
* @param _request Empty request
* @returns Empty response
*/
export async function openMcpSettings(controller: Controller, _request: EmptyRequest): Promise<Empty> {
const mcpSettingsFilePath = await controller.mcpHub?.getMcpSettingsFilePath()
if (mcpSettingsFilePath) {
await openFileIntegration(mcpSettingsFilePath)
}
return Empty.create()
}
@@ -1,5 +1,5 @@
import type { EmptyRequest } from "../../../shared/proto/common"
import { McpMarketplaceCatalog } from "../../../shared/proto/mcp"
import type { 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 McpMarketplaceCatalog.create({ items: [] })
return { items: [] }
} catch (error) {
console.error("Failed to refresh MCP marketplace:", error)
return McpMarketplaceCatalog.create({ items: [] })
return { items: [] }
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { McpServers } from "@shared/proto/mcp"
import type { 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.create({ mcpServers: protoServers })
return { mcpServers: protoServers }
} catch (error) {
console.error(`Failed to restart MCP server ${request.value}:`, error)
throw error
+2 -3
View File
@@ -1,5 +1,4 @@
import type { ToggleMcpServerRequest } from "../../../shared/proto/mcp"
import { McpServers } from "../../../shared/proto/mcp"
import type { ToggleMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion"
@@ -16,7 +15,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.create({ mcpServers: protoServers })
return { mcpServers: protoServers }
} catch (error) {
console.error(`Failed to toggle MCP server ${request.serverName}:`, error)
throw error
@@ -1,5 +1,4 @@
import type { ToggleToolAutoApproveRequest } from "@shared/proto/mcp"
import { McpServers } from "@shared/proto/mcp"
import type { ToggleToolAutoApproveRequest, McpServers } from "@shared/proto/mcp"
import type { Controller } from "../index"
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
@@ -16,7 +15,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.create({ mcpServers: convertMcpServersToProtoMcpServers(mcpServers) })
return { 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.create({ mcpServers: convertedMcpServers })
return { mcpServers: convertedMcpServers }
} else {
console.error("Server name and timeout are required")
throw new Error("Server name and timeout are required")
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create models service registry
const modelsService = createServiceRegistry("models")
// Export the method handler types and registration function
export type ModelsMethodHandler = ServiceMethodHandler
export type ModelsStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = modelsService.registerMethod
// Export the request handlers
export const handleModelsServiceRequest = modelsService.handleRequest
export const handleModelsServiceStreamingRequest = modelsService.handleStreamingRequest
export const isStreamingMethod = modelsService.isStreamingMethod
// Register all models methods
registerAllMethods()
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { getLmStudioModels } from "./getLmStudioModels"
import { getOllamaModels } from "./getOllamaModels"
import { getVsCodeLmModels } from "./getVsCodeLmModels"
import { refreshOpenAiModels } from "./refreshOpenAiModels"
import { refreshOpenRouterModels } from "./refreshOpenRouterModels"
import { refreshRequestyModels } from "./refreshRequestyModels"
// Register all models service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("getLmStudioModels", getLmStudioModels)
registerMethod("getOllamaModels", getOllamaModels)
registerMethod("getVsCodeLmModels", getVsCodeLmModels)
registerMethod("refreshOpenAiModels", refreshOpenAiModels)
registerMethod("refreshOpenRouterModels", refreshOpenRouterModels)
registerMethod("refreshRequestyModels", refreshRequestyModels)
}
@@ -10,7 +10,10 @@ import { getSecret } from "@core/storage/state"
* @param request Empty request object
* @returns Response containing the Requesty models
*/
export async function refreshRequestyModels(controller: Controller, _: EmptyRequest): Promise<OpenRouterCompatibleModelInfo> {
export async function refreshRequestyModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
@@ -27,7 +30,7 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ
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 = OpenRouterModelInfo.create({
const modelInfo: OpenRouterModelInfo = {
maxTokens: model.max_output_tokens || undefined,
contextWindow: model.context_window,
supportsImages: model.supports_vision || undefined,
@@ -37,7 +40,7 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ
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)
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create slash service registry
const slashService = createServiceRegistry("slash")
// Export the method handler types and registration function
export type SlashMethodHandler = ServiceMethodHandler
export type SlashStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = slashService.registerMethod
// Export the request handlers
export const handleSlashServiceRequest = slashService.handleRequest
export const handleSlashServiceStreamingRequest = slashService.handleStreamingRequest
export const isStreamingMethod = slashService.isStreamingMethod
// Register all slash methods
registerAllMethods()
+14
View File
@@ -0,0 +1,14 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { condense } from "./condense"
import { reportBug } from "./reportBug"
// Register all slash service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("condense", condense)
registerMethod("reportBug", reportBug)
}
+4 -3
View File
@@ -2,6 +2,7 @@ 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
@@ -9,7 +10,7 @@ import { State } from "../../../shared/proto/state"
* @param request The empty request
* @returns The current extension state
*/
export async function getLatestState(controller: Controller, _: EmptyRequest): Promise<State> {
export async function getLatestState(controller: Controller, request: EmptyRequest): Promise<State> {
// Get the state using the existing method
const state = await controller.getStateToPostToWebview()
@@ -17,7 +18,7 @@ export async function getLatestState(controller: Controller, _: EmptyRequest): P
const stateJson = JSON.stringify(state)
// Return the state as a JSON string
return State.create({
return {
stateJson,
})
}
}
+22
View File
@@ -0,0 +1,22 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create state service registry
const stateService = createServiceRegistry("state")
// Export the method handler types and registration function
export type StateMethodHandler = ServiceMethodHandler
export type StateStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = stateService.registerMethod
// Export the request handlers
export const handleStateServiceRequest = stateService.handleRequest
export const handleStateServiceStreamingRequest = stateService.handleStreamingRequest
export const isStreamingMethod = stateService.isStreamingMethod
// Register all state methods
registerAllMethods()
+27
View File
@@ -0,0 +1,27 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { getLatestState } from "./getLatestState"
import { resetState } from "./resetState"
import { subscribeToState } from "./subscribeToState"
import { toggleFavoriteModel } from "./toggleFavoriteModel"
import { togglePlanActMode } from "./togglePlanActMode"
import { updateAutoApprovalSettings } from "./updateAutoApprovalSettings"
import { updateTerminalConnectionTimeout } from "./updateTerminalConnectionTimeout"
// Streaming methods for this service
export const streamingMethods = ["subscribeToState"]
// Register all state service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("getLatestState", getLatestState)
registerMethod("resetState", resetState)
registerMethod("subscribeToState", subscribeToState, { isStreaming: true })
registerMethod("toggleFavoriteModel", toggleFavoriteModel)
registerMethod("togglePlanActMode", togglePlanActMode)
registerMethod("updateAutoApprovalSettings", updateAutoApprovalSettings)
registerMethod("updateTerminalConnectionTimeout", updateTerminalConnectionTimeout)
}
@@ -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 Int64.create({ value: timeout })
return { 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.")

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