fix shengsuanyun and requesty models get function.

This commit is contained in:
coohu committed 2025-05-14 14:51:50 +08:00
commit 005feaa3f4
287 files changed
+51016 -4961

No files matched your search

@@ -2,6 +2,7 @@ import * as vscode from "vscode"
import crypto from "crypto"
import { Controller } from "../index"
import { storeSecret } from "../../storage/state"
import { EmptyRequest, String } from "../../../shared/proto/common"
/**
* Handles the user clicking the login link in the UI.
@@ -11,7 +12,7 @@ import { storeSecret } from "../../storage/state"
* @param controller The controller instance.
* @returns The login URL as a string.
*/
export async function accountLoginClicked(controller: Controller): 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)
@@ -25,6 +26,8 @@ export async function accountLoginClicked(controller: Controller): Promise<Strin
const authUrl = vscode.Uri.parse(
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
vscode.env.openExternal(authUrl)
return authUrl.toString()
await vscode.env.openExternal(authUrl)
return {
value: authUrl.toString(),
}
}
+11 -3
View File
@@ -1,14 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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 type and registration function
// Export the method handler types and registration function
export type AccountMethodHandler = ServiceMethodHandler
export type AccountStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = accountService.registerMethod
// Export the request handler
// Export the request handlers
export const handleAccountServiceRequest = accountService.handleRequest
export const handleAccountServiceStreamingRequest = accountService.handleStreamingRequest
export const isStreamingMethod = accountService.isStreamingMethod
// Register all account methods
registerAllMethods()
+10 -3
View File
@@ -1,15 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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 type and registration function
// Export the method handler types and registration function
export type BrowserMethodHandler = ServiceMethodHandler
export type BrowserStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = browserService.registerMethod
// Export the request handler
// Export the request handlers
export const handleBrowserServiceRequest = browserService.handleRequest
export const handleBrowserServiceStreamingRequest = browserService.handleStreamingRequest
export const isStreamingMethod = browserService.isStreamingMethod
// Register all browser methods
registerAllMethods()
@@ -1,8 +1,8 @@
import { UpdateBrowserSettingsRequest } from "../../../shared/proto/browser"
import { Boolean } from "../../../shared/proto/common"
import { Controller } from "../index"
import { updateGlobalState } from "../../storage/state"
import { BrowserSettings as SharedBrowserSettings } from "../../../shared/BrowserSettings"
import { updateGlobalState, getGlobalState } from "../../storage/state"
import { BrowserSettings as SharedBrowserSettings, DEFAULT_BROWSER_SETTINGS } from "../../../shared/BrowserSettings"
/**
* Update browser settings
@@ -12,23 +12,39 @@ import { BrowserSettings as SharedBrowserSettings } from "../../../shared/Browse
*/
export async function updateBrowserSettings(controller: Controller, request: UpdateBrowserSettingsRequest): Promise<Boolean> {
try {
// Convert from protobuf format to shared format
const browserSettings: SharedBrowserSettings = {
// Get current browser settings to preserve fields not in the request
const currentSettings = (await getGlobalState(controller.context, "browserSettings")) as SharedBrowserSettings | undefined
const mergedWithDefaults = { ...DEFAULT_BROWSER_SETTINGS, ...currentSettings }
// Convert from protobuf format to shared format, merging with existing settings
const newBrowserSettings: SharedBrowserSettings = {
...mergedWithDefaults, // Start with existing settings (and defaults)
viewport: {
width: request.viewport?.width || 900,
height: request.viewport?.height || 600,
// Apply updates from request
width: request.viewport?.width || mergedWithDefaults.viewport.width,
height: request.viewport?.height || mergedWithDefaults.viewport.height,
},
remoteBrowserEnabled: request.remoteBrowserEnabled || false,
remoteBrowserHost: request.remoteBrowserHost || undefined,
// Explicitly handle optional boolean and string fields from the request
remoteBrowserEnabled:
request.remoteBrowserEnabled === undefined
? mergedWithDefaults.remoteBrowserEnabled
: request.remoteBrowserEnabled,
remoteBrowserHost:
request.remoteBrowserHost === undefined ? mergedWithDefaults.remoteBrowserHost : request.remoteBrowserHost,
chromeExecutablePath:
// If chromeExecutablePath is explicitly in the request (even as ""), use it.
// Otherwise, fall back to mergedWithDefaults.
"chromeExecutablePath" in request ? request.chromeExecutablePath : mergedWithDefaults.chromeExecutablePath,
disableToolUse: request.disableToolUse === undefined ? mergedWithDefaults.disableToolUse : request.disableToolUse,
}
// Update global state with new settings
await updateGlobalState(controller.context, "browserSettings", browserSettings)
await updateGlobalState(controller.context, "browserSettings", newBrowserSettings)
// Update task browser settings if task exists
if (controller.task) {
controller.task.browserSettings = browserSettings
controller.task.browserSession.browserSettings = browserSettings
controller.task.browserSettings = newBrowserSettings
controller.task.browserSession.browserSettings = newBrowserSettings
}
// Post updated state to webview
+10 -3
View File
@@ -1,15 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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 type and registration function
// Export the method handler types and registration function
export type CheckpointsMethodHandler = ServiceMethodHandler
export type CheckpointsStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = checkpointsService.registerMethod
// Export the request handler
// 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,55 @@
import { Controller } from ".."
import { RuleFileRequest, RuleFile } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import {
createRuleFile as createRuleFileImpl,
refreshClineRulesToggles,
} from "@core/context/instructions/user-instructions/cline-rules"
import * as vscode from "vscode"
import * as path from "path"
import { handleFileServiceRequest } from "./index"
import { cwd } from "@core/task"
/**
* Creates a rule file in either global or workspace rules directory
* @param controller The controller instance
* @param request The request containing filename and isGlobal flag
* @returns Result with file path and display name
* @throws Error if operation fails
*/
export const createRuleFile: FileMethodHandler = async (controller: Controller, request: RuleFileRequest): Promise<RuleFile> => {
if (typeof request.isGlobal !== "boolean" || typeof request.filename !== "string" || !request.filename) {
console.error("createRuleFile: Missing or invalid parameters", {
isGlobal: typeof request.isGlobal === "boolean" ? request.isGlobal : `Invalid: ${typeof request.isGlobal}`,
filename: typeof request.filename === "string" ? request.filename : `Invalid: ${typeof request.filename}`,
})
throw new Error("Missing or invalid parameters")
}
const { filePath, fileExists } = await createRuleFileImpl(request.isGlobal, request.filename, cwd)
if (!filePath) {
throw new Error("Failed to create rule file.")
}
if (fileExists) {
vscode.window.showWarningMessage(`Rule file "${request.filename}" already exists.`)
// Still open it for editing
await handleFileServiceRequest(controller, "openFile", { value: filePath })
} else {
await refreshClineRulesToggles(controller.context, cwd)
await controller.postStateToWebview()
await handleFileServiceRequest(controller, "openFile", { value: filePath })
vscode.window.showInformationMessage(
`Created new ${request.isGlobal ? "global" : "workspace"} rule file: ${request.filename}`,
)
}
return RuleFile.create({
filePath: filePath,
displayName: path.basename(filePath),
alreadyExists: fileExists,
})
}
@@ -0,0 +1,47 @@
import { Controller } from ".."
import { RuleFileRequest, RuleFile } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import {
deleteRuleFile as deleteRuleFileImpl,
refreshClineRulesToggles,
} from "@core/context/instructions/user-instructions/cline-rules"
import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules"
import * as vscode from "vscode"
import * as path from "path"
import { cwd } from "@core/task"
/**
* Deletes a rule file from either global or workspace rules directory
* @param controller The controller instance
* @param request The request containing rule path and isGlobal flag
* @returns Result with file path and display name
* @throws Error if operation fails
*/
export const deleteRuleFile: FileMethodHandler = async (controller: Controller, request: RuleFileRequest): Promise<RuleFile> => {
if (typeof request.isGlobal !== "boolean" || typeof request.rulePath !== "string" || !request.rulePath) {
console.error("deleteRuleFile: Missing or invalid parameters", {
isGlobal: typeof request.isGlobal === "boolean" ? request.isGlobal : `Invalid: ${typeof request.isGlobal}`,
rulePath: typeof request.rulePath === "string" ? request.rulePath : `Invalid: ${typeof request.rulePath}`,
})
throw new Error("Missing or invalid parameters")
}
const result = await deleteRuleFileImpl(controller.context, request.rulePath, request.isGlobal)
if (!result.success) {
throw new Error(result.message || "Failed to delete rule file")
}
await refreshClineRulesToggles(controller.context, cwd)
await refreshExternalRulesToggles(controller.context, cwd)
await controller.postStateToWebview()
const fileName = path.basename(request.rulePath)
vscode.window.showInformationMessage(`Rule file "${fileName}" deleted successfully`)
return RuleFile.create({
filePath: request.rulePath,
displayName: fileName,
alreadyExists: false,
})
}
@@ -0,0 +1,50 @@
import { Controller } from ".."
import { RelativePathsRequest, RelativePaths } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import * as vscode from "vscode"
import * as path from "path"
/**
* Converts a list of URIs to workspace-relative paths
* @param controller The controller instance
* @param request The request containing URIs to convert
* @returns Response with resolved relative paths
*/
export const getRelativePaths: FileMethodHandler = async (
controller: Controller,
request: RelativePathsRequest,
): Promise<RelativePaths> => {
const resolvedPaths = await Promise.all(
request.uris.map(async (uriString) => {
try {
const fileUri = vscode.Uri.parse(uriString, true)
const relativePathToGet = vscode.workspace.asRelativePath(fileUri, false)
// If the path is still absolute, it's outside the workspace
if (path.isAbsolute(relativePathToGet)) {
console.warn(`Dropped file ${relativePathToGet} is outside the workspace. Sending original path.`)
return fileUri.fsPath.replace(/\\/g, "/")
} else {
let finalPath = "/" + relativePathToGet.replace(/\\/g, "/")
try {
const stat = await vscode.workspace.fs.stat(fileUri)
if (stat.type === vscode.FileType.Directory) {
finalPath += "/"
}
} catch (statError) {
console.error(`Error stating file ${fileUri.fsPath}:`, statError)
}
return finalPath
}
} catch (error) {
console.error(`Error calculating relative path for ${uriString}:`, error)
return null
}
}),
)
// Filter out any null values from errors
const validPaths = resolvedPaths.filter((path): path is string => path !== null)
return RelativePaths.create({ paths: validPaths })
}
+10 -3
View File
@@ -1,15 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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 type and registration function
// Export the method handler types and registration function
export type FileMethodHandler = ServiceMethodHandler
export type FileStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = fileService.registerMethod
// Export the request handler
// Export the request handlers
export const handleFileServiceRequest = fileService.handleRequest
export const handleFileServiceStreamingRequest = fileService.handleStreamingRequest
export const isStreamingMethod = fileService.isStreamingMethod
// Register all file methods
registerAllMethods()
+10
View File
@@ -3,12 +3,22 @@
// Import all method implementations
import { registerMethod } from "./index"
import { createRuleFile } from "./createRuleFile"
import { deleteRuleFile } from "./deleteRuleFile"
import { getRelativePaths } from "./getRelativePaths"
import { openFile } from "./openFile"
import { openImage } from "./openImage"
import { searchCommits } from "./searchCommits"
import { searchFiles } from "./searchFiles"
// Register all file service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("createRuleFile", createRuleFile)
registerMethod("deleteRuleFile", deleteRuleFile)
registerMethod("getRelativePaths", getRelativePaths)
registerMethod("openFile", openFile)
registerMethod("openImage", openImage)
registerMethod("searchCommits", searchCommits)
registerMethod("searchFiles", searchFiles)
}
+31
View File
@@ -0,0 +1,31 @@
import { Controller } from ".."
import { GitCommits } from "@shared/proto/file"
import { StringRequest } from "@shared/proto/common"
import { searchCommits as searchCommitsUtil } from "@utils/git"
import { getWorkspacePath } from "@utils/path"
import { FileMethodHandler } from "./index"
import { convertGitCommitsToProtoGitCommits } from "@shared/proto-conversions/file/git-commit-conversion"
/**
* Searches for git commits in the workspace repository
* @param controller The controller instance
* @param request The request message containing the search query in the 'value' field
* @returns GitCommits containing the matching commits
*/
export const searchCommits: FileMethodHandler = async (controller: Controller, request: StringRequest): Promise<GitCommits> => {
const cwd = getWorkspacePath()
if (!cwd) {
return GitCommits.create({ commits: [] })
}
try {
const commits = await searchCommitsUtil(request.value || "", cwd)
const protoCommits = convertGitCommitsToProtoGitCommits(commits)
return GitCommits.create({ commits: protoCommits })
} catch (error) {
console.error(`Error searching commits: ${JSON.stringify(error)}`)
return GitCommits.create({ commits: [] })
}
}
+55
View File
@@ -0,0 +1,55 @@
import { Controller } from ".."
import { FileSearchRequest, FileSearchResults } from "@shared/proto/file"
import { searchWorkspaceFiles } from "@services/search/file-search"
import { getWorkspacePath } from "@utils/path"
import { FileMethodHandler } from "./index"
import { convertSearchResultsToProtoFileInfos } from "@shared/proto-conversions/file/search-result-conversion"
/**
* Searches for files in the workspace with fuzzy matching
* @param controller The controller instance
* @param request The request containing search query and optionally a mentionsRequestId
* @returns Results containing matching files/folders
*/
export const searchFiles: FileMethodHandler = async (
controller: Controller,
request: FileSearchRequest,
): Promise<FileSearchResults> => {
const workspacePath = getWorkspacePath()
if (!workspacePath) {
// Handle case where workspace path is not available
console.error("Error in searchFiles: No workspace path available")
return FileSearchResults.create({
results: [],
mentionsRequestId: request.mentionsRequestId,
})
}
try {
// Call file search service with query from request
const searchResults = await searchWorkspaceFiles(
request.query || "",
workspacePath,
request.limit || 20, // Use default limit of 20 if not specified
)
// Convert search results to proto FileInfo objects using the conversion function
const protoResults = convertSearchResultsToProtoFileInfos(searchResults)
// Return successful results
return FileSearchResults.create({
results: protoResults,
mentionsRequestId: request.mentionsRequestId,
})
} catch (error) {
// Log the error but don't include it in the response, following the pattern in searchCommits
console.error("Error in searchFiles:", error instanceof Error ? error.message : String(error))
// Return empty results without error message
return FileSearchResults.create({
results: [],
mentionsRequestId: request.mentionsRequestId,
})
}
}
+146 -42
View File
@@ -1,10 +1,11 @@
import { Controller } from "./index"
import { handleAccountServiceRequest } from "./account"
import { handleBrowserServiceRequest } from "./browser/index"
import { handleFileServiceRequest } from "./file"
import { handleTaskServiceRequest } from "./task"
import { handleCheckpointsServiceRequest } from "./checkpoints"
import { handleMcpServiceRequest } from "./mcp"
import { serviceHandlers } from "./grpc-service-config"
import { GrpcRequestRegistry } from "./grpc-request-registry"
/**
* Type definition for a streaming response handler
*/
export type StreamingResponseHandler = (response: any, isLast?: boolean, sequenceNumber?: number) => Promise<void>
/**
* Handles gRPC requests from the webview
@@ -18,52 +19,37 @@ export class GrpcHandler {
* @param method The method name
* @param message The request message
* @param requestId The request ID for response correlation
* @returns The response message or error
* @param isStreaming Whether this is a streaming request
* @returns The response message or error for unary requests, void for streaming requests
*/
async handleRequest(
service: string,
method: string,
message: any,
requestId: string,
isStreaming: boolean = false,
): Promise<{
message?: any
error?: string
request_id: string
}> {
} | void> {
try {
switch (service) {
case "cline.AccountService":
return {
message: await handleAccountServiceRequest(this.controller, method, message),
request_id: requestId,
}
case "cline.BrowserService":
return {
message: await handleBrowserServiceRequest(this.controller, method, message),
request_id: requestId,
}
case "cline.CheckpointsService":
return {
message: await handleCheckpointsServiceRequest(this.controller, method, message),
request_id: requestId,
}
case "cline.FileService":
return {
message: await handleFileServiceRequest(this.controller, method, message),
request_id: requestId,
}
case "cline.TaskService":
return {
message: await handleTaskServiceRequest(this.controller, method, message),
request_id: requestId,
}
case "cline.McpService":
return {
message: await handleMcpServiceRequest(this.controller, method, message),
request_id: requestId,
}
default:
throw new Error(`Unknown service: ${service}`)
// If this is a streaming request, use the streaming handler
if (isStreaming) {
await this.handleStreamingRequest(service, method, message, requestId)
return
}
// Get the service handler from the config
const serviceConfig = serviceHandlers[service]
if (!serviceConfig) {
throw new Error(`Unknown service: ${service}`)
}
// Handle unary request
return {
message: await serviceConfig.requestHandler(this.controller, method, message),
request_id: requestId,
}
} catch (error) {
return {
@@ -72,8 +58,66 @@ export class GrpcHandler {
}
}
}
/**
* Handle a streaming gRPC request
* @param service The service name
* @param method The method name
* @param message The request message
* @param requestId The request ID for response correlation
*/
private async handleStreamingRequest(service: string, method: string, message: any, requestId: string): Promise<void> {
// Create a response stream function
const responseStream: StreamingResponseHandler = async (
response: any,
isLast: boolean = false,
sequenceNumber?: number,
) => {
await this.controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
message: response,
request_id: requestId,
is_streaming: !isLast,
sequence_number: sequenceNumber,
},
})
}
try {
// Get the service handler from the config
const serviceConfig = serviceHandlers[service]
if (!serviceConfig) {
throw new Error(`Unknown service: ${service}`)
}
// Check if the service supports streaming
if (!serviceConfig.streamingHandler) {
throw new Error(`Service ${service} does not support streaming`)
}
// Handle streaming request and pass the requestId to all streaming handlers
await serviceConfig.streamingHandler(this.controller, method, message, responseStream, requestId)
// Don't send a final message here - the stream should stay open for future updates
// The stream will be closed when the client disconnects or when the service explicitly ends it
} catch (error) {
// Send error response
await this.controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
error: error instanceof Error ? error.message : String(error),
request_id: requestId,
is_streaming: false,
},
})
}
}
}
// Registry to track active gRPC requests and their cleanup functions
const requestRegistry = new GrpcRequestRegistry()
/**
* Handle a gRPC request from the webview
* @param controller The controller instance
@@ -86,11 +130,35 @@ export async function handleGrpcRequest(
method: string
message: any
request_id: string
is_streaming?: boolean
},
) {
try {
const grpcHandler = new GrpcHandler(controller)
const response = await grpcHandler.handleRequest(request.service, request.method, request.message, request.request_id)
// For streaming requests, handleRequest handles sending responses directly
if (request.is_streaming) {
try {
await grpcHandler.handleRequest(request.service, request.method, request.message, request.request_id, true)
} finally {
// Note: We don't automatically clean up here anymore
// The request will be cleaned up when it completes or is cancelled
}
return
}
// For unary requests, we get a response and send it back
const response = (await grpcHandler.handleRequest(
request.service,
request.method,
request.message,
request.request_id,
false,
)) as {
message?: any
error?: string
request_id: string
}
// Send the response back to the webview
await controller.postMessageToWebview({
@@ -108,3 +176,39 @@ export async function handleGrpcRequest(
})
}
}
/**
* Handle a gRPC request cancellation from the webview
* @param controller The controller instance
* @param request The cancellation request
*/
export async function handleGrpcRequestCancel(
controller: Controller,
request: {
request_id: string
},
) {
const cancelled = requestRegistry.cancelRequest(request.request_id)
if (cancelled) {
// Send a cancellation confirmation
await controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
message: { cancelled: true },
request_id: request.request_id,
is_streaming: false,
},
})
} else {
console.log(`[DEBUG] Request not found for cancellation: ${request.request_id}`)
}
}
/**
* Get the request registry instance
* This allows other parts of the code to access the registry
*/
export function getRequestRegistry(): GrpcRequestRegistry {
return requestRegistry
}
@@ -0,0 +1,124 @@
import { StreamingResponseHandler } from "./grpc-handler"
/**
* Information about a registered gRPC request
*/
export interface RequestInfo {
/**
* Function to clean up resources when the request is cancelled or completed
*/
cleanup: () => void
/**
* Optional metadata about the request
*/
metadata?: any
/**
* Timestamp when the request was registered
*/
timestamp: Date
/**
* The streaming response handler for this request
*/
responseStream?: StreamingResponseHandler
}
/**
* Registry for managing gRPC request lifecycles
* This class provides a centralized way to track active requests and their cleanup functions
*/
export class GrpcRequestRegistry {
/**
* Map of request IDs to request information
*/
private activeRequests = new Map<string, RequestInfo>()
/**
* Register a new request with its cleanup function
* @param requestId The unique ID of the request
* @param cleanup Function to clean up resources when the request is cancelled
* @param metadata Optional metadata about the request
* @param responseStream Optional streaming response handler
*/
public registerRequest(
requestId: string,
cleanup: () => void,
metadata?: any,
responseStream?: StreamingResponseHandler,
): void {
this.activeRequests.set(requestId, {
cleanup,
metadata,
timestamp: new Date(),
responseStream,
})
console.log(`[DEBUG] Registered request: ${requestId}`)
}
/**
* Cancel a request and clean up its resources
* @param requestId The ID of the request to cancel
* @returns True if the request was found and cancelled, false otherwise
*/
public cancelRequest(requestId: string): boolean {
const requestInfo = this.activeRequests.get(requestId)
if (requestInfo) {
try {
requestInfo.cleanup()
console.log(`[DEBUG] Cleaned up request: ${requestId}`)
} catch (error) {
console.error(`Error cleaning up request ${requestId}:`, error)
}
this.activeRequests.delete(requestId)
return true
}
return false
}
/**
* Get information about a request
* @param requestId The ID of the request
* @returns The request information, or undefined if not found
*/
public getRequestInfo(requestId: string): RequestInfo | undefined {
return this.activeRequests.get(requestId)
}
/**
* Check if a request exists in the registry
* @param requestId The ID of the request
* @returns True if the request exists, false otherwise
*/
public hasRequest(requestId: string): boolean {
return this.activeRequests.has(requestId)
}
/**
* Get all active requests
* @returns An array of [requestId, requestInfo] pairs
*/
public getAllRequests(): [string, RequestInfo][] {
return Array.from(this.activeRequests.entries())
}
/**
* Clean up stale requests that have been active for too long
* @param maxAgeMs Maximum age in milliseconds before a request is considered stale
* @returns The number of requests that were cleaned up
*/
public cleanupStaleRequests(maxAgeMs: number): number {
const now = new Date()
let cleanedCount = 0
for (const [requestId, info] of this.activeRequests.entries()) {
if (now.getTime() - info.timestamp.getTime() > maxAgeMs) {
this.cancelRequest(requestId)
cleanedCount++
}
}
return cleanedCount
}
}
@@ -0,0 +1,75 @@
// 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"
/**
* 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> = {
"clineShengsuan.AccountService": {
requestHandler: handleAccountServiceRequest,
streamingHandler: handleAccountServiceStreamingRequest,
},
"clineShengsuan.BrowserService": {
requestHandler: handleBrowserServiceRequest,
streamingHandler: handleBrowserServiceStreamingRequest,
},
"clineShengsuan.CheckpointsService": {
requestHandler: handleCheckpointsServiceRequest,
streamingHandler: handleCheckpointsServiceStreamingRequest,
},
"clineShengsuan.FileService": {
requestHandler: handleFileServiceRequest,
streamingHandler: handleFileServiceStreamingRequest,
},
"clineShengsuan.McpService": {
requestHandler: handleMcpServiceRequest,
streamingHandler: handleMcpServiceStreamingRequest,
},
"clineShengsuan.StateService": {
requestHandler: handleStateServiceRequest,
streamingHandler: handleStateServiceStreamingRequest,
},
"clineShengsuan.TaskService": {
requestHandler: handleTaskServiceRequest,
streamingHandler: handleTaskServiceStreamingRequest,
},
"clineShengsuan.WebService": {
requestHandler: handleWebServiceRequest,
streamingHandler: handleWebServiceStreamingRequest,
},
"clineShengsuan.ModelsService": {
requestHandler: handleModelsServiceRequest,
streamingHandler: handleModelsServiceStreamingRequest,
},
"clineShengsuan.SlashService": {
requestHandler: handleSlashServiceRequest,
streamingHandler: handleSlashServiceStreamingRequest,
},
}
+92 -4
View File
@@ -1,16 +1,36 @@
import { Controller } from "./index"
import { StreamingResponseHandler } from "./grpc-handler"
/**
* Generic type for service method handlers
*/
export type ServiceMethodHandler = (controller: Controller, message: any) => Promise<any>
/**
* Type for streaming method handlers
*/
export type StreamingMethodHandler = (
controller: Controller,
message: any,
responseStream: StreamingResponseHandler,
requestId?: string,
) => Promise<void>
/**
* Method metadata including streaming information
*/
export interface MethodMetadata {
isStreaming: boolean
}
/**
* Generic service registry for gRPC services
*/
export class ServiceRegistry {
private serviceName: string
private methodRegistry: Record<string, ServiceMethodHandler> = {}
private streamingMethodRegistry: Record<string, StreamingMethodHandler> = {}
private methodMetadata: Record<string, MethodMetadata> = {}
/**
* Create a new service registry
@@ -24,10 +44,37 @@ export class ServiceRegistry {
* Register a method handler
* @param methodName The name of the method to register
* @param handler The handler function for the method
* @param metadata Optional metadata about the method
*/
registerMethod(methodName: string, handler: ServiceMethodHandler): void {
this.methodRegistry[methodName] = handler
console.log(`Registered ${this.serviceName} method: ${methodName}`)
registerMethod(methodName: string, handler: ServiceMethodHandler | StreamingMethodHandler, metadata?: MethodMetadata): void {
const isStreaming = metadata?.isStreaming || false
if (isStreaming) {
this.streamingMethodRegistry[methodName] = handler as StreamingMethodHandler
} else {
this.methodRegistry[methodName] = handler as ServiceMethodHandler
}
this.methodMetadata[methodName] = { isStreaming, ...metadata }
console.log(`Registered ${this.serviceName} method: ${methodName}${isStreaming ? " (streaming)" : ""}`)
}
/**
* Check if a method is a streaming method
* @param method The method name
* @returns True if the method is a streaming method
*/
isStreamingMethod(method: string): boolean {
return this.methodMetadata[method]?.isStreaming || false
}
/**
* Get a streaming method handler
* @param method The method name
* @returns The streaming method handler or undefined if not found
*/
getStreamingHandler(method: string): StreamingMethodHandler | undefined {
return this.streamingMethodRegistry[method]
}
/**
@@ -41,11 +88,41 @@ export class ServiceRegistry {
const handler = this.methodRegistry[method]
if (!handler) {
if (this.isStreamingMethod(method)) {
throw new Error(`Method ${method} is a streaming method and should be handled with handleStreamingRequest`)
}
throw new Error(`Unknown ${this.serviceName} method: ${method}`)
}
return handler(controller, message)
}
/**
* Handle a streaming service request
* @param controller The controller instance
* @param method The method name
* @param message The request message
* @param responseStream The streaming response handler
* @param requestId The request ID for correlation and cleanup
*/
async handleStreamingRequest(
controller: Controller,
method: string,
message: any,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
const handler = this.streamingMethodRegistry[method]
if (!handler) {
if (this.methodRegistry[method]) {
throw new Error(`Method ${method} is not a streaming method and should be handled with handleRequest`)
}
throw new Error(`Unknown ${this.serviceName} streaming method: ${method}`)
}
await handler(controller, message, responseStream, requestId)
}
}
/**
@@ -57,9 +134,20 @@ export function createServiceRegistry(serviceName: string) {
const registry = new ServiceRegistry(serviceName)
return {
registerMethod: (methodName: string, handler: ServiceMethodHandler) => registry.registerMethod(methodName, handler),
registerMethod: (methodName: string, handler: ServiceMethodHandler | StreamingMethodHandler, metadata?: MethodMetadata) =>
registry.registerMethod(methodName, handler, metadata),
handleRequest: (controller: Controller, method: string, message: any) =>
registry.handleRequest(controller, method, message),
handleStreamingRequest: (
controller: Controller,
method: string,
message: any,
responseStream: StreamingResponseHandler,
requestId?: string,
) => registry.handleStreamingRequest(controller, method, message, responseStream, requestId),
isStreamingMethod: (method: string) => registry.isStreamingMethod(method),
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,32 @@
import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion"
import type { AddRemoteMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
import type { Controller } from "../index"
/**
* Adds a new remote MCP server via gRPC
* @param controller The controller instance
* @param request The request containing server name and URL
* @returns An array of McpServer objects
*/
export async function addRemoteMcpServer(controller: Controller, request: AddRemoteMcpServerRequest): Promise<McpServers> {
try {
// Validate required fields
if (!request.serverName) {
throw new Error("Server name is required")
}
if (!request.serverUrl) {
throw new Error("Server URL is required")
}
// Call the McpHub method to add the remote server
const servers = await controller.mcpHub?.addRemoteServer(request.serverName, request.serverUrl)
const protoServers = convertMcpServersToProtoMcpServers(servers)
return { mcpServers: protoServers }
} catch (error) {
console.error(`Failed to add remote MCP server ${request.serverName}:`, error)
throw error
}
}
+114
View File
@@ -0,0 +1,114 @@
import { Controller } from ".."
import { Empty, StringRequest } from "../../../shared/proto/common"
import { McpServer, McpDownloadResponse } from "@shared/mcp"
import axios from "axios"
import * as vscode from "vscode"
/**
* Download an MCP server from the marketplace
* @param controller The controller instance
* @param request The request containing the MCP ID
* @returns Empty response
*/
export async function downloadMcp(controller: Controller, request: StringRequest): Promise<Empty> {
try {
// Check if mcpId is provided
if (!request.value) {
throw new Error("MCP ID is required")
}
const mcpId = request.value
// Check if we already have this MCP server installed
const servers = controller.mcpHub?.getServers() || []
const isInstalled = servers.some((server: McpServer) => server.name === mcpId)
if (isInstalled) {
throw new Error("This MCP server is already installed")
}
// Fetch server details from marketplace
const response = await axios.post<McpDownloadResponse>(
"https://api.cline.bot/v1/mcp/download",
{ mcpId },
{
headers: { "Content-Type": "application/json" },
timeout: 10000,
},
)
if (!response.data) {
throw new Error("Invalid response from MCP marketplace API")
}
console.log("[downloadMcp] Response from download API", { response })
const mcpDetails = response.data
// Validate required fields
if (!mcpDetails.githubUrl) {
throw new Error("Missing GitHub URL in MCP download response")
}
if (!mcpDetails.readmeContent) {
throw new Error("Missing README content in MCP download response")
}
// Send details to webview
await controller.postMessageToWebview({
type: "mcpDownloadDetails",
mcpDownloadDetails: mcpDetails,
})
// Create task with context from README and added guidelines for MCP server installation
const task = `Set up the MCP server from ${mcpDetails.githubUrl} while adhering to these MCP server installation rules:
- Start by loading the MCP documentation.
- Use "${mcpDetails.mcpId}" as the server name in cline_mcp_settings.json.
- Create the directory for the new MCP server before starting installation.
- Make sure you read the user's existing cline_mcp_settings.json file before editing it with this new mcp, to not overwrite any existing servers.
- Use commands aligned with the user's shell and operating system best practices.
- The following README may contain instructions that conflict with the user's OS, in which case proceed thoughtfully.
- Once installed, demonstrate the server's capabilities by using one of its tools.
Here is the project's README to help you get started:\n\n${mcpDetails.readmeContent}\n${mcpDetails.llmsInstallationContent}`
const { chatSettings } = await controller.getStateToPostToWebview()
if (chatSettings.mode === "plan") {
await controller.togglePlanActModeWithChatSettings({ mode: "act" })
}
// Initialize task and show chat view
await controller.initTask(task)
await controller.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
// Return an empty response - the client only cares if the call succeeded
return Empty.create()
} catch (error) {
console.error("Failed to download MCP:", error)
let errorMessage = "Failed to download MCP"
if (axios.isAxiosError(error)) {
if (error.code === "ECONNABORTED") {
errorMessage = "Request timed out. Please try again."
} else if (error.response?.status === 404) {
errorMessage = "MCP server not found in marketplace."
} else if (error.response?.status === 500) {
errorMessage = "Internal server error. Please try again later."
} else if (!error.response && error.request) {
errorMessage = "Network error. Please check your internet connection."
}
} else if (error instanceof Error) {
errorMessage = error.message
}
// Show error in both notification and marketplace UI
vscode.window.showErrorMessage(errorMessage)
await controller.postMessageToWebview({
type: "mcpDownloadDetails",
error: errorMessage,
})
throw error
}
}
+11 -4
View File
@@ -1,15 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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
// Create mcp service registry
const mcpService = createServiceRegistry("mcp")
// Export the method handler type and registration function
// Export the method handler types and registration function
export type McpMethodHandler = ServiceMethodHandler
export type McpStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = mcpService.registerMethod
// Export the request handler
// Export the request handlers
export const handleMcpServiceRequest = mcpService.handleRequest
export const handleMcpServiceStreamingRequest = mcpService.handleStreamingRequest
export const isStreamingMethod = mcpService.isStreamingMethod
// Register all mcp methods
registerAllMethods()
+4
View File
@@ -3,12 +3,16 @@
// Import all method implementations
import { registerMethod } from "./index"
import { addRemoteMcpServer } from "./addRemoteMcpServer"
import { downloadMcp } from "./downloadMcp"
import { toggleMcpServer } from "./toggleMcpServer"
import { updateMcpTimeout } from "./updateMcpTimeout"
// Register all mcp service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("addRemoteMcpServer", addRemoteMcpServer)
registerMethod("downloadMcp", downloadMcp)
registerMethod("toggleMcpServer", toggleMcpServer)
registerMethod("updateMcpTimeout", updateMcpTimeout)
}
@@ -0,0 +1,27 @@
import { Controller } from ".."
import { StringArray, StringRequest } from "../../../shared/proto/common"
import axios from "axios"
/**
* Fetches available models from LM Studio
* @param controller The controller instance
* @param request The request containing the base URL (optional)
* @returns Array of model names
*/
export async function getLmStudioModels(controller: Controller, request: StringRequest): Promise<StringArray> {
try {
let baseUrl = request.value || "http://localhost:1234"
if (!URL.canParse(baseUrl)) {
return StringArray.create({ values: [] })
}
const response = await axios.get(`${baseUrl}/v1/models`)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return StringArray.create({ values: models })
} catch (error) {
return StringArray.create({ values: [] })
}
}
@@ -0,0 +1,27 @@
import { Controller } from ".."
import { StringArray, StringRequest } from "../../../shared/proto/common"
import axios from "axios"
/**
* Fetches available models from Ollama
* @param controller The controller instance
* @param request The request containing the base URL (optional)
* @returns Array of model names
*/
export async function getOllamaModels(controller: Controller, request: StringRequest): Promise<StringArray> {
try {
let baseUrl = request.value || "http://localhost:11434"
if (!URL.canParse(baseUrl)) {
return StringArray.create({ values: [] })
}
const response = await axios.get(`${baseUrl}/api/tags`)
const modelsArray = response.data?.models?.map((model: any) => model.name) || []
const models = [...new Set<string>(modelsArray)]
return StringArray.create({ values: models })
} catch (error) {
return StringArray.create({ values: [] })
}
}
@@ -0,0 +1,24 @@
import { Controller } from ".."
import { EmptyRequest } from "../../../shared/proto/common"
import { VsCodeLmModelsArray } from "../../../shared/proto/models"
import * as vscode from "vscode"
import { convertVsCodeNativeModelsToProtoModels } from "../../../shared/proto-conversions/models/vscode-lm-models-conversion"
/**
* Fetches available models from VS Code LM API
* @param controller The controller instance
* @param request Empty request
* @returns Array of VS Code LM models
*/
export async function getVsCodeLmModels(controller: Controller, request: EmptyRequest): Promise<VsCodeLmModelsArray> {
try {
const models = await vscode.lm.selectChatModels({})
const protoModels = convertVsCodeNativeModelsToProtoModels(models || [])
return VsCodeLmModelsArray.create({ models: protoModels })
} catch (error) {
console.error("Error fetching VS Code LM models:", error)
return VsCodeLmModelsArray.create({ 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 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()
+23
View File
@@ -0,0 +1,23 @@
// 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"
import { refreshShengSuanYunModels } from "./refreshShengSuanYunModels"
// 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)
registerMethod("refreshShengSuanYunModels", refreshShengSuanYunModels)
}
@@ -0,0 +1,37 @@
import { Controller } from ".."
import { OpenAiModelsRequest } from "../../../shared/proto/models"
import { StringArray } from "../../../shared/proto/common"
import axios from "axios"
import type { AxiosRequestConfig } from "axios"
/**
* Fetches available models from the OpenAI API
* @param controller The controller instance
* @param request Request containing the base URL and API key
* @returns Array of model names
*/
export async function refreshOpenAiModels(controller: Controller, request: OpenAiModelsRequest): Promise<StringArray> {
try {
if (!request.baseUrl) {
return StringArray.create({ values: [] })
}
if (!URL.canParse(request.baseUrl)) {
return StringArray.create({ values: [] })
}
const config: AxiosRequestConfig = {}
if (request.apiKey) {
config["headers"] = { Authorization: `Bearer ${request.apiKey}` }
}
const response = await axios.get(`${request.baseUrl}/models`, config)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return StringArray.create({ values: models })
} catch (error) {
console.error("Error fetching OpenAI models:", error)
return StringArray.create({ values: [] })
}
}
@@ -0,0 +1,175 @@
import { Controller } from ".."
import { EmptyRequest } from "../../../shared/proto/common"
import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "../../../shared/proto/models"
import axios from "axios"
import path from "path"
import fs from "fs/promises"
import { fileExistsAtPath } from "@utils/fs"
import { GlobalFileNames } from "@core/storage/disk"
/**
* Refreshes the OpenRouter models and returns the updated model list
* @param controller The controller instance
* @param request Empty request object
* @returns Response containing the OpenRouter models
*/
export async function refreshOpenRouterModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
const openRouterModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.openRouterModels)
let models: Record<string, Partial<OpenRouterModelInfo>> = {}
try {
const response = await axios.get("https://openrouter.ai/api/v1/models")
if (response.data?.data) {
const rawModels = response.data.data
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
for (const rawModel of rawModels) {
const modelInfo: Partial<OpenRouterModelInfo> = {
maxTokens: rawModel.top_provider?.max_completion_tokens,
contextWindow: rawModel.context_length,
supportsImages: rawModel.architecture?.modality?.includes("image"),
supportsPromptCache: false,
inputPrice: parsePrice(rawModel.pricing?.prompt),
outputPrice: parsePrice(rawModel.pricing?.completion),
description: rawModel.description,
}
switch (rawModel.id) {
case "anthropic/claude-3-7-sonnet":
case "anthropic/claude-3-7-sonnet:beta":
case "anthropic/claude-3.7-sonnet":
case "anthropic/claude-3.7-sonnet:beta":
case "anthropic/claude-3.7-sonnet:thinking":
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
// NOTE: this needs to be synced with api.ts/openrouter default model info
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
break
case "anthropic/claude-3.5-sonnet-20240620":
case "anthropic/claude-3.5-sonnet-20240620:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
break
case "anthropic/claude-3-5-haiku":
case "anthropic/claude-3-5-haiku:beta":
case "anthropic/claude-3-5-haiku-20241022":
case "anthropic/claude-3-5-haiku-20241022:beta":
case "anthropic/claude-3.5-haiku":
case "anthropic/claude-3.5-haiku:beta":
case "anthropic/claude-3.5-haiku-20241022":
case "anthropic/claude-3.5-haiku-20241022:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 1.25
modelInfo.cacheReadsPrice = 0.1
break
case "anthropic/claude-3-opus":
case "anthropic/claude-3-opus:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 18.75
modelInfo.cacheReadsPrice = 1.5
break
case "anthropic/claude-3-haiku":
case "anthropic/claude-3-haiku:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 0.3
modelInfo.cacheReadsPrice = 0.03
break
case "deepseek/deepseek-chat":
modelInfo.supportsPromptCache = true
// see api.ts/deepSeekModels for more info
modelInfo.inputPrice = 0
modelInfo.cacheWritesPrice = 0.14
modelInfo.cacheReadsPrice = 0.014
break
default:
if (rawModel.id.startsWith("openai/")) {
modelInfo.cacheReadsPrice = parsePrice(rawModel.pricing?.input_cache_read)
if (modelInfo.cacheReadsPrice) {
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = parsePrice(rawModel.pricing?.input_cache_write)
// openrouter charges no cache write pricing for openAI models
}
} else if (rawModel.id.startsWith("google/")) {
modelInfo.cacheReadsPrice = parsePrice(rawModel.pricing?.input_cache_read)
if (modelInfo.cacheReadsPrice) {
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = parsePrice(rawModel.pricing?.input_cache_write)
}
}
break
}
models[rawModel.id] = modelInfo
}
} else {
console.error("Invalid response from OpenRouter API")
}
await fs.writeFile(openRouterModelsFilePath, JSON.stringify(models))
console.log("OpenRouter models fetched and saved", models)
} catch (error) {
console.error("Error fetching OpenRouter models:", error)
// If we failed to fetch models, try to read cached models
const cachedModels = await readOpenRouterModels(controller)
if (cachedModels) {
models = cachedModels
}
}
// Convert the Record<string, Partial<OpenRouterModelInfo>> to Record<string, OpenRouterModelInfo>
// by filling in any missing required fields with defaults
const typedModels: Record<string, OpenRouterModelInfo> = {}
for (const [key, model] of Object.entries(models)) {
typedModels[key] = {
maxTokens: model.maxTokens ?? 0,
contextWindow: model.contextWindow ?? 0,
supportsImages: model.supportsImages ?? false,
supportsPromptCache: model.supportsPromptCache ?? false,
inputPrice: model.inputPrice ?? 0,
outputPrice: model.outputPrice ?? 0,
cacheWritesPrice: model.cacheWritesPrice ?? 0,
cacheReadsPrice: model.cacheReadsPrice ?? 0,
description: model.description ?? "",
}
}
return OpenRouterCompatibleModelInfo.create({ models: typedModels })
}
/**
* Reads cached OpenRouter models from disk
*/
async function readOpenRouterModels(controller: Controller): Promise<Record<string, Partial<OpenRouterModelInfo>> | undefined> {
const openRouterModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.openRouterModels)
const fileExists = await fileExistsAtPath(openRouterModelsFilePath)
if (fileExists) {
try {
const fileContents = await fs.readFile(openRouterModelsFilePath, "utf8")
return JSON.parse(fileContents)
} catch (error) {
console.error("Error reading cached OpenRouter models:", error)
return undefined
}
}
return undefined
}
/**
* Ensures the cache directory exists and returns its path
*/
async function ensureCacheDirectoryExists(controller: Controller): Promise<string> {
const cacheDir = path.join(controller.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
@@ -0,0 +1,59 @@
import { Controller } from ".."
import { EmptyRequest } from "../../../shared/proto/common"
import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "../../../shared/proto/models"
import axios from "axios"
import { getSecret } from "@core/storage/state"
/**
* Refreshes the Requesty models and returns the updated model list
* @param controller The controller instance
* @param request Empty request object
* @returns Response containing the Requesty models
*/
export async function refreshRequestyModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
let models: Record<string, OpenRouterModelInfo> = {}
try {
const apiKey = await getSecret(controller.context, "requestyApiKey")
const headers = {
Authorization: `Bearer ${apiKey}`,
}
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 = {
maxTokens: model.max_output_tokens || undefined,
contextWindow: model.context_window,
supportsImages: model.supports_vision || undefined,
supportsPromptCache: model.supports_caching || undefined,
inputPrice: parsePrice(model.input_price) || 0,
outputPrice: parsePrice(model.output_price) || 0,
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)
} else {
console.error("Invalid response from Requesty API")
}
} catch (error) {
console.error("Error fetching Requesty models:", error)
}
controller.postMessageToWebview({
type: "requestyModels",
shengSuanYunModels: models,
})
return OpenRouterCompatibleModelInfo.create({ models })
}
@@ -0,0 +1,112 @@
import { Controller } from ".."
import { EmptyRequest } from "../../../shared/proto/common"
import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "../../../shared/proto/models"
import axios from "axios"
import path from "path"
import fs from "fs/promises"
import { fileExistsAtPath } from "@utils/fs"
import { GlobalFileNames } from "@core/storage/disk"
/**
* Refreshes the ShengSuanYun models and returns the updated model list
* @param controller The controller instance
* @param request Empty request object
* @returns Response containing the ShengSuanYun models
*/
export async function refreshShengSuanYunModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
const shengSuanYunModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.shengSuanYunModels)
let models: Record<string, Partial<OpenRouterModelInfo>> = {}
try {
const response = await axios.get("https://router.shengsuanyun.com/api/v1/models/")
if (response.data?.data && Array.isArray(response.data?.data)) {
const rawModels = response.data.data
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
for (const model of rawModels) {
const modelInfo: Partial<OpenRouterModelInfo> = {
maxTokens: model.max_tokens || undefined,
contextWindow: model.context_window,
supportsImages: model.architecture?.input?.includes("image"),
supportsPromptCache: model.supports_prompt_cache,
inputPrice: parsePrice(model.pricing?.prompt),
outputPrice: parsePrice(model.pricing?.completion),
description: model.description,
cacheWritesPrice: model.pricing?.cache,
cacheReadsPrice: 0,
}
models[model.api_name] = modelInfo
}
} else {
console.error("Invalid response from ShengSuanYun API")
}
await fs.writeFile(shengSuanYunModelsFilePath, JSON.stringify(models))
console.log("ShengSuanYun models fetched and saved", models)
} catch (error) {
console.error("Error fetching ShengSuanYun models:", error)
// If we failed to fetch models, try to read cached models
const cachedModels = await readShengSuanYunModels(controller)
if (cachedModels) {
models = cachedModels
}
}
// Convert the Record<string, Partial<OpenRouterModelInfo>> to Record<string, OpenRouterModelInfo>
// by filling in any missing required fields with defaults
const typedModels: Record<string, OpenRouterModelInfo> = {}
for (const [key, model] of Object.entries(models)) {
typedModels[key] = {
maxTokens: model.maxTokens ?? 0,
contextWindow: model.contextWindow ?? 0,
supportsImages: model.supportsImages ?? false,
supportsPromptCache: model.supportsPromptCache ?? false,
inputPrice: model.inputPrice ?? 0,
outputPrice: model.outputPrice ?? 0,
cacheWritesPrice: model.cacheWritesPrice ?? 0,
cacheReadsPrice: model.cacheReadsPrice ?? 0,
description: model.description ?? "",
}
}
controller.postMessageToWebview({
type: "shengSuanYunModels",
shengSuanYunModels: typedModels,
})
return OpenRouterCompatibleModelInfo.create({ models: typedModels })
}
/**
* Reads cached ShengSuanYun models from disk
*/
async function readShengSuanYunModels(controller: Controller): Promise<Record<string, Partial<OpenRouterModelInfo>> | undefined> {
const shengSuanYunModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.shengSuanYunModels)
const fileExists = await fileExistsAtPath(shengSuanYunModelsFilePath)
if (fileExists) {
try {
const fileContents = await fs.readFile(shengSuanYunModelsFilePath, "utf8")
return JSON.parse(fileContents)
} catch (error) {
console.error("Error reading cached ShengSuanYun models:", error)
return undefined
}
}
return undefined
}
/**
* Ensures the cache directory exists and returns its path
*/
async function ensureCacheDirectoryExists(controller: Controller): Promise<string> {
const cacheDir = path.join(controller.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
+10
View File
@@ -0,0 +1,10 @@
import { Controller } from ".."
import { StringRequest, Empty } from "../../../shared/proto/common"
/**
* Command slash command logic
*/
export async function condense(controller: Controller, request: StringRequest): Promise<Empty> {
await controller.task?.handleWebviewAskResponse("yesButtonClicked")
return Empty.create()
}
+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)
}
+10
View File
@@ -0,0 +1,10 @@
import { Controller } from ".."
import { StringRequest, Empty } from "../../../shared/proto/common"
/**
* Report bug slash command logic
*/
export async function reportBug(controller: Controller, request: StringRequest): Promise<Empty> {
await controller.task?.handleWebviewAskResponse("yesButtonClicked")
return Empty.create()
}
@@ -0,0 +1,24 @@
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
* @param controller The controller instance
* @param request The empty request
* @returns The current extension state
*/
export async function getLatestState(controller: Controller, request: EmptyRequest): Promise<State> {
// Get the state using the existing method
const state = await controller.getStateToPostToWebview()
// Convert the state to a JSON string
const stateJson = JSON.stringify(state)
// Return the state as a JSON string
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()
+19
View File
@@ -0,0 +1,19 @@
// 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 { subscribeToState } from "./subscribeToState"
import { toggleFavoriteModel } from "./toggleFavoriteModel"
// 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("subscribeToState", subscribeToState, { isStreaming: true })
registerMethod("toggleFavoriteModel", toggleFavoriteModel)
}
@@ -0,0 +1,74 @@
import * as vscode from "vscode"
import { Controller } from "../index"
import { EmptyRequest } from "../../../shared/proto/common"
import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler"
// Keep track of active state subscriptions
const activeStateSubscriptions = new Set<StreamingResponseHandler>()
/**
* Subscribe to state updates
* @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 subscribeToState(
controller: Controller,
request: EmptyRequest,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
// Send the initial state
const initialState = await controller.getStateToPostToWebview()
const initialStateJson = JSON.stringify(initialState)
console.log("[DEBUG] set up state subscription")
await responseStream({
stateJson: initialStateJson,
})
// Add this subscription to the active subscriptions
activeStateSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeStateSubscriptions.delete(responseStream)
console.log("[DEBUG] Cleaned up state subscription")
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "state_subscription" }, responseStream)
}
}
/**
* Send a state update to all active subscribers
* @param state The state to send
*/
export async function sendStateUpdate(state: any): Promise<void> {
const stateJson = JSON.stringify(state)
// Send the update to all active subscribers
const promises = Array.from(activeStateSubscriptions).map(async (responseStream) => {
try {
// The issue might be that we're not properly formatting the response
// Let's ensure we're sending a properly formatted State message
await responseStream(
{
stateJson,
},
false, // Not the last message
)
console.log("[DEBUG] sending followup state", stateJson.length, "chars")
} catch (error) {
console.error("Error sending state update:", error)
// Remove the subscription if there was an error
activeStateSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
@@ -0,0 +1,46 @@
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { Controller } from ".."
import { Empty, StringRequest } from "../../../shared/proto/common"
import { updateGlobalState } from "@/core/storage/state"
/**
* Toggles a model's favorite status
* @param controller The controller instance
* @param request The request containing the model ID to toggle
* @returns An empty response
*/
export async function toggleFavoriteModel(controller: Controller, request: StringRequest): Promise<Empty> {
try {
if (!request.value) {
throw new Error("Model ID is required")
}
const modelId = request.value
const { apiConfiguration } = await controller.getStateToPostToWebview()
if (!apiConfiguration) {
throw new Error("API configuration not found")
}
const favoritedModelIds = apiConfiguration.favoritedModelIds || []
// Toggle favorite status
const updatedFavorites = favoritedModelIds.includes(modelId)
? favoritedModelIds.filter((id) => id !== modelId)
: [...favoritedModelIds, modelId]
await updateGlobalState(controller.context, "favoritedModelIds", updatedFavorites)
// Capture telemetry for model favorite toggle
const isFavorited = !favoritedModelIds.includes(modelId)
telemetryService.captureModelFavoritesUsage(modelId, isFavorited)
// Post state to webview without changing any other configuration
await controller.postStateToWebview()
return Empty.create()
} catch (error) {
console.error(`Failed to toggle favorite status for model ${request.value}:`, error)
throw error
}
}
+1
View File
@@ -8,6 +8,7 @@ import { Empty, EmptyRequest } from "../../../shared/proto/common"
* @returns Empty response
*/
export async function clearTask(controller: Controller, _request: EmptyRequest): Promise<Empty> {
// clearTask is called here when the user closes the task
await controller.clearTask()
await controller.postStateToWebview()
return Empty.create()
@@ -0,0 +1,88 @@
import path from "path"
import fs from "fs/promises"
import { Controller } from ".."
import { EmptyRequest } from "../../../shared/proto/common"
import { DeleteNonFavoritedTasksResults } from "../../../shared/proto/task"
import { getGlobalState, updateGlobalState } from "../../storage/state"
import { fileExistsAtPath } from "../../../utils/fs"
/**
* Deletes all non-favorited tasks, preserving only favorited ones
* @param controller The controller instance
* @param request Empty request
* @returns DeleteNonFavoritedTasksResults with counts of preserved and deleted tasks
*/
export async function deleteNonFavoritedTasks(
controller: Controller,
_request: EmptyRequest,
): Promise<DeleteNonFavoritedTasksResults> {
try {
// Clear current task first
await controller.clearTask()
// Get existing task history
const taskHistory = ((await getGlobalState(controller.context, "taskHistory")) as any[]) || []
// Filter out non-favorited tasks
const favoritedTasks = taskHistory.filter((task) => task.isFavorited === true)
const deletedCount = taskHistory.length - favoritedTasks.length
console.log(`[deleteNonFavoritedTasks] Found ${favoritedTasks.length} favorited tasks to preserve`)
// Update global state
if (favoritedTasks.length > 0) {
await updateGlobalState(controller.context, "taskHistory", favoritedTasks)
} else {
await updateGlobalState(controller.context, "taskHistory", undefined)
}
// Handle file system cleanup for deleted tasks
const preserveTaskIds = favoritedTasks.map((task) => task.id)
await cleanupTaskFiles(controller, preserveTaskIds)
// Update webview
try {
await controller.postStateToWebview()
} catch (webviewErr) {
console.error("Error posting to webview:", webviewErr)
}
return {
tasksPreserved: favoritedTasks.length,
tasksDeleted: deletedCount,
}
} catch (error) {
console.error("Error in deleteNonFavoritedTasks:", error)
throw error
}
}
/**
* Helper function to cleanup task files while preserving specified tasks
*/
async function cleanupTaskFiles(controller: Controller, preserveTaskIds: string[]) {
const taskDirPath = path.join(controller.context.globalStorageUri.fsPath, "tasks")
try {
if (await fileExistsAtPath(taskDirPath)) {
if (preserveTaskIds.length > 0) {
const taskDirs = await fs.readdir(taskDirPath)
console.debug(`[cleanupTaskFiles] Found ${taskDirs.length} task directories`)
// Delete only non-preserved task directories
for (const dir of taskDirs) {
if (!preserveTaskIds.includes(dir)) {
await fs.rm(path.join(taskDirPath, dir), { recursive: true, force: true })
}
}
} else {
// No tasks to preserve, delete everything
await fs.rm(taskDirPath, { recursive: true, force: true })
}
}
} catch (error) {
console.error("Error cleaning up task files:", error)
}
return true
}
@@ -0,0 +1,23 @@
import { Controller } from ".."
import { Empty, StringArrayRequest } from "../../../shared/proto/common"
import { TaskMethodHandler } from "./index"
/**
* Deletes tasks with the specified IDs
* @param controller The controller instance
* @param request The request containing an array of task IDs to delete
* @returns Empty response
* @throws Error if operation fails
*/
export const deleteTasksWithIds: TaskMethodHandler = async (
controller: Controller,
request: StringArrayRequest,
): Promise<Empty> => {
if (!request.value || request.value.length === 0) {
throw new Error("Missing task IDs")
}
await Promise.all(request.value.map((value) => controller.deleteTaskWithId(value)))
return Empty.create()
}
@@ -0,0 +1,22 @@
import { Controller } from ".."
import { Empty, StringRequest } from "@shared/proto/common"
import { TaskMethodHandler } from "./index"
/**
* Exports a task with the given ID to markdown
* @param controller The controller instance
* @param request The request containing the task ID in the value field
* @returns Empty response
*/
export const exportTaskWithId: TaskMethodHandler = async (controller: Controller, request: StringRequest): Promise<Empty> => {
try {
if (request.value) {
await controller.exportTaskWithId(request.value)
}
return Empty.create()
} catch (error) {
// Log the error but allow it to propagate for proper gRPC error handling
console.error(`Error exporting task with ID ${request.value}:`, error)
throw error
}
}
@@ -0,0 +1,89 @@
import { Controller } from ".."
import { GetTaskHistoryRequest, TaskHistoryArray } from "../../../shared/proto/task"
import { getGlobalState } from "../../storage/state"
/**
* Gets filtered task history
* @param controller The controller instance
* @param request Filter parameters for task history
* @returns TaskHistoryArray with filtered task list
*/
export async function getTaskHistory(controller: Controller, request: GetTaskHistoryRequest): Promise<TaskHistoryArray> {
try {
const { favoritesOnly, searchQuery, sortBy } = request
// Get task history from global state
const taskHistory = ((await getGlobalState(controller.context, "taskHistory")) as any[]) || []
// Apply filters
let filteredTasks = taskHistory.filter((item) => {
// Basic filter: must have timestamp and task content
const hasRequiredFields = item.ts && item.task
// Apply favorites filter if requested
if (favoritesOnly && hasRequiredFields) {
return item.isFavorited === true
}
return hasRequiredFields
})
// Apply search if provided
if (searchQuery) {
// Simple search implementation
const query = searchQuery.toLowerCase()
filteredTasks = filteredTasks.filter((item) => item.task.toLowerCase().includes(query))
}
// Calculate total count before sorting
const totalCount = filteredTasks.length
// Apply sorting
if (sortBy) {
filteredTasks.sort((a, b) => {
switch (sortBy) {
case "oldest":
return a.ts - b.ts
case "mostExpensive":
return (b.totalCost || 0) - (a.totalCost || 0)
case "mostTokens":
return (
(b.tokensIn || 0) +
(b.tokensOut || 0) +
(b.cacheWrites || 0) +
(b.cacheReads || 0) -
((a.tokensIn || 0) + (a.tokensOut || 0) + (a.cacheWrites || 0) + (a.cacheReads || 0))
)
case "newest":
default:
return b.ts - a.ts
}
})
} else {
// Default sort by newest
filteredTasks.sort((a, b) => b.ts - a.ts)
}
// Map to response format
const tasks = filteredTasks.map((item) => ({
id: item.id,
task: item.task,
ts: item.ts,
isFavorited: item.isFavorited || false,
size: item.size || 0,
totalCost: item.totalCost || 0,
tokensIn: item.tokensIn || 0,
tokensOut: item.tokensOut || 0,
cacheWrites: item.cacheWrites || 0,
cacheReads: item.cacheReads || 0,
}))
return {
tasks,
totalCount,
}
} catch (error) {
console.error("Error in getTaskHistory:", error)
throw error
}
}
+10 -3
View File
@@ -1,15 +1,22 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
// 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 task service registry
const taskService = createServiceRegistry("task")
// Export the method handler type and registration function
// Export the method handler types and registration function
export type TaskMethodHandler = ServiceMethodHandler
export type TaskStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = taskService.registerMethod
// Export the request handler
// Export the request handlers
export const handleTaskServiceRequest = taskService.handleRequest
export const handleTaskServiceStreamingRequest = taskService.handleStreamingRequest
export const isStreamingMethod = taskService.isStreamingMethod
// Register all task methods
registerAllMethods()
+12
View File
@@ -5,12 +5,24 @@
import { registerMethod } from "./index"
import { cancelTask } from "./cancelTask"
import { clearTask } from "./clearTask"
import { deleteNonFavoritedTasks } from "./deleteNonFavoritedTasks"
import { deleteTasksWithIds } from "./deleteTasksWithIds"
import { exportTaskWithId } from "./exportTaskWithId"
import { getTaskHistory } from "./getTaskHistory"
import { newTask } from "./newTask"
import { showTaskWithId } from "./showTaskWithId"
import { toggleTaskFavorite } from "./toggleTaskFavorite"
// Register all task service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("cancelTask", cancelTask)
registerMethod("clearTask", clearTask)
registerMethod("deleteNonFavoritedTasks", deleteNonFavoritedTasks)
registerMethod("deleteTasksWithIds", deleteTasksWithIds)
registerMethod("exportTaskWithId", exportTaskWithId)
registerMethod("getTaskHistory", getTaskHistory)
registerMethod("newTask", newTask)
registerMethod("showTaskWithId", showTaskWithId)
registerMethod("toggleTaskFavorite", toggleTaskFavorite)
}
@@ -0,0 +1,73 @@
import { Controller } from ".."
import { StringRequest } from "../../../shared/proto/common"
import { TaskResponse } from "../../../shared/proto/task"
/**
* Shows a task with the specified ID
* @param controller The controller instance
* @param request The request containing the task ID
* @returns TaskResponse with task details
*/
export async function showTaskWithId(controller: Controller, request: StringRequest): Promise<TaskResponse> {
try {
const id = request.value
// First check if task exists in global state for faster access
const taskHistory = ((await controller.context.globalState.get("taskHistory")) as any[]) || []
const historyItem = taskHistory.find((item) => item.id === id)
// We need to initialize the task before returning data
if (historyItem) {
// Always initialize the task with the history item
await controller.initTask(undefined, undefined, historyItem)
// Send UI update to show the chat view
await controller.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
// Return task data for gRPC response
return {
id: historyItem.id,
task: historyItem.task || "",
ts: historyItem.ts || 0,
isFavorited: historyItem.isFavorited || false,
size: historyItem.size || 0,
totalCost: historyItem.totalCost || 0,
tokensIn: historyItem.tokensIn || 0,
tokensOut: historyItem.tokensOut || 0,
cacheWrites: historyItem.cacheWrites || 0,
cacheReads: historyItem.cacheReads || 0,
}
}
// If not in global state, fetch from storage
const { historyItem: fetchedItem } = await controller.getTaskWithId(id)
// Initialize the task with the fetched item
await controller.initTask(undefined, undefined, fetchedItem)
// Send UI update to show the chat view
await controller.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
return {
id: fetchedItem.id,
task: fetchedItem.task || "",
ts: fetchedItem.ts || 0,
isFavorited: fetchedItem.isFavorited || false,
size: fetchedItem.size || 0,
totalCost: fetchedItem.totalCost || 0,
tokensIn: fetchedItem.tokensIn || 0,
tokensOut: fetchedItem.tokensOut || 0,
cacheWrites: fetchedItem.cacheWrites || 0,
cacheReads: fetchedItem.cacheReads || 0,
}
} catch (error) {
console.error("Error in showTaskWithId:", error)
throw error
}
}
@@ -0,0 +1,51 @@
import { Controller } from "../"
import { Empty } from "../../../shared/proto/common"
import { TaskFavoriteRequest } from "../../../shared/proto/task"
export async function toggleTaskFavorite(controller: Controller, request: TaskFavoriteRequest): Promise<Empty> {
if (!request.taskId || request.isFavorited === undefined) {
const errorMsg = `[toggleTaskFavorite] Invalid request: taskId or isFavorited missing`
console.error(errorMsg)
return {}
}
try {
// Update in-memory state only
try {
const history = ((await controller.context.globalState.get("taskHistory")) as any[]) || []
const taskIndex = history.findIndex((item) => item.id === request.taskId)
if (taskIndex === -1) {
console.log(`[toggleTaskFavorite] Task not found in history array!`)
} else {
// Create a new array instead of modifying in place to ensure state change
const updatedHistory = [...history]
updatedHistory[taskIndex] = {
...updatedHistory[taskIndex],
isFavorited: request.isFavorited,
}
// Update global state and wait for it to complete
try {
await controller.context.globalState.update("taskHistory", updatedHistory)
} catch (stateErr) {
console.error("Error updating global state:", stateErr)
}
}
} catch (historyErr) {
console.error("Error processing task history:", historyErr)
}
// Post to webview
try {
await controller.postStateToWebview()
} catch (webviewErr) {
console.error("Error posting to webview:", webviewErr)
}
} catch (error) {
console.error("Error in toggleTaskFavorite:", error)
}
return {}
}
@@ -0,0 +1,29 @@
import { Controller } from "../index"
import { StringRequest } from "../../../shared/proto/common"
import { IsImageUrl } from "../../../shared/proto/web"
import { detectImageUrl } from "@integrations/misc/link-preview"
/**
* Checks if a URL is an image URL
* @param controller The controller instance
* @param request The request containing the URL to check
* @returns A result indicating if the URL is an image and the URL that was checked
*/
export async function checkIsImageUrl(controller: Controller, request: StringRequest): Promise<IsImageUrl> {
try {
const url = request.value || ""
// Check if the URL is an image
const isImage = await detectImageUrl(url)
return {
isImage,
url,
}
} catch (error) {
console.error(`Error checking if URL is an image: ${request.value}`, error)
return {
isImage: false,
url: request.value || "",
}
}
}
+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 web service registry
const webService = createServiceRegistry("web")
// Export the method handler types and registration function
export type WebMethodHandler = ServiceMethodHandler
export type WebStreamingMethodHandler = StreamingMethodHandler
export const registerMethod = webService.registerMethod
// Export the request handlers
export const handleWebServiceRequest = webService.handleRequest
export const handleWebServiceStreamingRequest = webService.handleStreamingRequest
export const isStreamingMethod = webService.isStreamingMethod
// Register all web methods
registerAllMethods()
+12
View File
@@ -0,0 +1,12 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { checkIsImageUrl } from "./checkIsImageUrl"
// Register all web service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("checkIsImageUrl", checkIsImageUrl)
}