diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 91ed72164..d77313b92 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -79,7 +79,13 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ uriType: "file", fileUri: file.path, }); - rules.push({ ...rule, source: "rules-block", sourceFile: file.path }); + if (!rule.invokable) { + rules.push({ + ...rule, + source: "rules-block", + sourceFile: file.path, + }); + } } catch (e) { errors.push({ fatal: false, diff --git a/core/index.d.ts b/core/index.d.ts index c5e106b42..ed6237f7a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -359,11 +359,15 @@ export interface ToolResultChatMessage { role: "tool"; content: string; toolCallId: string; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface UserChatMessage { role: "user"; content: MessageContent; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface ThinkingChatMessage { @@ -372,6 +376,12 @@ export interface ThinkingChatMessage { signature?: string; redactedThinking?: string; toolCalls?: ToolCallDelta[]; + reasoning_details?: { + signature?: string; + [key: string]: any; + }[]; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } /** @@ -400,11 +410,15 @@ export interface AssistantChatMessage { content: MessageContent; toolCalls?: ToolCallDelta[]; usage?: Usage; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface SystemChatMessage { role: "system"; content: string; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export type ChatMessage = diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 2ccc325cf..2930678e8 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -63,6 +63,47 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ "watsonx", "nebius", "relace", + "openrouter", + "deepseek", + "xAI", + "groq", + "gemini", + "docker", + // TODO add these, change to inverted logic so only the ones that need templating are hardcoded + // Asksage.ts + // Azure.ts + // BedrockImport.ts + // Cerebras.ts + // Cloudflare.ts + // CometAPI.ts + // CustomLLM.ts + // DeepInfra.ts + // Fireworks.ts + // Flowise.ts + // FunctionNetwork.ts + // HuggingFaceInferenceAPI.ts + // HuggingFaceTEI.ts + // HuggingFaceTGI.ts + // Inception.ts + // Kindo.ts + // LlamaCpp.ts + // LlamaStack.ts + // Llamafile.ts + // Mock.ts + // Moonshot.ts + // NCompass.ts + // OVHcloud.ts + // Replicate.ts + // Scaleway.ts + // SiliconFlow.ts + // TARS.ts + // Test.ts + // TextGenWebUI.ts + // TransformersJsEmbeddingsProvider.ts + // Venice.ts + // Vllm.ts + // Voyage.ts + // etc ]; const PROVIDER_SUPPORTS_IMAGES: string[] = [ @@ -105,6 +146,8 @@ const MODEL_SUPPORTS_IMAGES: RegExp[] = [ /\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't! /\b(pali|med)gemma/, /qwen(.*)vl/, + /mistral-small/, + /mistral-medium/, ]; function modelSupportsImages( @@ -142,7 +185,12 @@ function modelSupportsReasoning( if (!model) { return false; } - if ("anthropic" === model.underlyingProviderName) { + // do not turn reasoning on by default for claude 3 models + if ( + model.model.includes("claude") && + !model.model.includes("-3-") && + !model.model.includes("-3.5-") + ) { return true; } if (model.model.includes("deepseek-r")) { diff --git a/core/llm/index.ts b/core/llm/index.ts index 39b6b127b..ceea1153d 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -87,6 +87,9 @@ type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; + // Provider capabilities (overridable by subclasses) + protected supportsReasoningField: boolean = false; + protected supportsReasoningDetailsField: boolean = false; get providerName(): string { return (this.constructor as typeof BaseLLM).providerName; @@ -993,6 +996,114 @@ export abstract class BaseLLM implements ILLM { return completionOptions; } + // Update the processChatChunk method: + private processChatChunk( + chunk: ChatMessage, + interaction: ILLMInteractionLog | undefined, + ): { + completion: string[]; + thinking: string[]; + usage: Usage | null; + chunk: ChatMessage; + } { + const completion: string[] = []; + const thinking: string[] = []; + let usage: Usage | null = null; + + if (chunk.role === "assistant") { + completion.push(this._formatChatMessage(chunk)); + } else if (chunk.role === "thinking" && typeof chunk.content === "string") { + thinking.push(chunk.content); + } + + interaction?.logItem({ + kind: "message", + message: chunk, + }); + + if (chunk.role === "assistant" && chunk.usage) { + usage = chunk.usage; + } + + return { + completion, + thinking, + usage, + chunk, + }; + } + + private canUseOpenAIResponses(options: CompletionOptions): boolean { + return ( + this.providerName === "openai" && + typeof (this as any)._streamResponses === "function" && + (this as any).isOSeriesOrGpt5Model(options.model) + ); + } + + private async *openAIAdapterStream( + body: ChatCompletionCreateParams, + signal: AbortSignal, + onCitations: (c: string[]) => void, + ): AsyncGenerator { + const stream = this.openaiAdapter!.chatCompletionStream( + { ...body, stream: true }, + signal, + ); + for await (const chunk of stream) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } + const chatChunk = fromChatCompletionChunk(chunk as any); + if (chatChunk) { + yield chatChunk; + } + if ((chunk as any).citations && Array.isArray((chunk as any).citations)) { + onCitations((chunk as any).citations); + } + } + } + + private async *openAIAdapterNonStream( + body: ChatCompletionCreateParams, + signal: AbortSignal, + ): AsyncGenerator { + const response = await this.openaiAdapter!.chatCompletionNonStream( + { ...body, stream: false }, + signal, + ); + this.lastRequestId = response.id ?? this.lastRequestId; + const messages = fromChatResponse(response as any); + for (const msg of messages) { + yield msg; + } + } + + private async *responsesStream( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const g = (this as any)._streamResponses( + messages, + signal, + options, + ) as AsyncGenerator; + for await (const m of g) { + yield m; + } + } + + private async *responsesNonStream( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const msg = await (this as any)._responses(messages, signal, options); + yield msg as ChatMessage; + } + + // Update the streamChat method: async *streamChat( _messages: ChatMessage[], signal: AbortSignal, @@ -1025,9 +1136,12 @@ export abstract class BaseLLM implements ILLM { messages = compiledChatMessages; } + const messagesCopy = [...messages]; // templateMessages may modify messages. + const prompt = this.templateMessages - ? this.templateMessages(messages) - : this._formatChatMessages(messages); + ? this.templateMessages(messagesCopy) + : this._formatChatMessages(messagesCopy); + if (logEnabled) { interaction?.logItem({ kind: "startChat", @@ -1040,9 +1154,14 @@ export abstract class BaseLLM implements ILLM { } } - let thinking = ""; - let completion = ""; + // Performance optimization: Use arrays instead of string concatenation. + // String concatenation in loops creates new string objects for each operation, + // which is O(n²) for n chunks. Arrays with push() are O(1) per operation, + // making the total O(n). We join() only once at the end. + const thinking: string[] = []; + const completion: string[] = []; let usage: Usage | undefined = undefined; + let citations: null | string[] = null; try { if (this.templateMessages) { @@ -1051,7 +1170,7 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - completion += chunk; + completion.push(chunk); interaction?.logItem({ kind: "chunk", chunk: chunk, @@ -1060,80 +1179,99 @@ export abstract class BaseLLM implements ILLM { } } else { if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) { - let body = toChatBody(messages, completionOptions); + let body = toChatBody(messages, completionOptions, { + includeReasoningField: this.supportsReasoningField, + includeReasoningDetailsField: this.supportsReasoningDetailsField, + }); body = this.modifyChatBody(body); - if (completionOptions.stream === false) { - // Stream false - const response = await this.openaiAdapter.chatCompletionNonStream( - { ...body, stream: false }, - signal, - ); - this.lastRequestId = response.id ?? this.lastRequestId; - const msg = fromChatResponse(response); - yield msg; - completion = this._formatChatMessage(msg); + if (logEnabled) { interaction?.logItem({ - kind: "message", - message: msg, + kind: "startChat", + messages, + options: { + ...completionOptions, + requestBody: body, + } as CompletionOptions, + provider: this.providerName, }); - } else { - // Stream true - const stream = this.openaiAdapter.chatCompletionStream( - { - ...body, - stream: true, - }, - signal, - ); - for await (const chunk of stream) { - if ( - !this.lastRequestId && - typeof (chunk as any).id === "string" - ) { - this.lastRequestId = (chunk as any).id; - } - const result = fromChatCompletionChunk(chunk); - if (result) { - completion += this._formatChatMessage(result); - interaction?.logItem({ - kind: "message", - message: result, - }); - yield result; - } + if (this.llmRequestHook) { + this.llmRequestHook(completionOptions.model, prompt); } } + + const canUseResponses = this.canUseOpenAIResponses(completionOptions); + const useStream = completionOptions.stream !== false; + + let iterable: AsyncIterable; + if (canUseResponses) { + iterable = useStream + ? this.responsesStream(messages, signal, completionOptions) + : this.responsesNonStream(messages, signal, completionOptions); + } else { + iterable = useStream + ? this.openAIAdapterStream(body, signal, (c) => { + if (!citations) { + citations = c; + } + }) + : this.openAIAdapterNonStream(body, signal); + } + + for await (const chunk of iterable) { + const result = this.processChatChunk(chunk, interaction); + completion.push(...result.completion); + thinking.push(...result.thinking); + if (result.usage !== null) { + usage = result.usage; + } + yield result.chunk; + } } else { + if (logEnabled) { + interaction?.logItem({ + kind: "startChat", + messages, + options: completionOptions, + provider: this.providerName, + }); + if (this.llmRequestHook) { + this.llmRequestHook(completionOptions.model, prompt); + } + } + for await (const chunk of this._streamChat( messages, signal, completionOptions, )) { - if (chunk.role === "assistant") { - completion += this._formatChatMessage(chunk); - } else if (chunk.role === "thinking") { - thinking += chunk.content; + const result = this.processChatChunk(chunk, interaction); + completion.push(...result.completion); + thinking.push(...result.thinking); + if (result.usage !== null) { + usage = result.usage; } - - interaction?.logItem({ - kind: "message", - message: chunk, - }); - - if (chunk.role === "assistant" && chunk.usage) { - usage = chunk.usage; - } - - yield chunk; + yield result.chunk; } } } + + if (citations) { + const cits = citations as string[]; + interaction?.logItem({ + kind: "message", + message: { + role: "assistant", + content: `\n\nCitations:\n${cits.map((c: string, i: number) => `${i + 1}: ${c}`).join("\n")}\n\n`, + }, + }); + } + status = this._logEnd( completionOptions.model, prompt, - completion, - thinking, + completion.join(""), + thinking.join(""), interaction, usage, ); @@ -1151,8 +1289,8 @@ export abstract class BaseLLM implements ILLM { status = this._logEnd( completionOptions.model, prompt, - completion, - thinking, + completion.join(""), + thinking.join(""), interaction, usage, e, @@ -1163,7 +1301,7 @@ export abstract class BaseLLM implements ILLM { this._logEnd( completionOptions.model, prompt, - completion, + completion.join(""), undefined, interaction, usage, @@ -1172,20 +1310,20 @@ export abstract class BaseLLM implements ILLM { } } /* - TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking - During tool use, you must pass thinking and redacted_thinking blocks back to the API, - and you must include the complete unmodified block back to the API. This is critical - for maintaining the model's reasoning flow and conversation integrity. + TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking + During tool use, you must pass thinking and redacted_thinking blocks back to the API, + and you must include the complete unmodified block back to the API. This is critical + for maintaining the model's reasoning flow and conversation integrity. - On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent - requests when not using tools, so it's the simplest option to always add to history. - */ + On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent + requests when not using tools, so it's the simplest option to always add to history. + */ return { modelTitle: this.title ?? completionOptions.model, modelProvider: this.underlyingProviderName, prompt, - completion, + completion: completion.join(""), }; } diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 305d177e7..01d16ec3d 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -6,6 +6,8 @@ import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { static providerName = "deepseek"; + protected supportsReasoningField = true; + protected supportsReasoningDetailsField = false; static defaultOptions: Partial = { apiBase: "https://api.deepseek.com/", model: "deepseek-coder", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 83166b6a2..90512ecfb 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -14,9 +14,18 @@ import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { fromChatCompletionChunk, + fromResponsesChunk, LlmApiRequestType, toChatBody, + toResponsesInput, } from "../openaiTypeConverters.js"; +import { + ResponseInput, + ResponseInputItem, + ResponseInputMessageContentList, + ResponseCreateParamsBase, + Tool as ResponsesTool, +} from "openai/resources/responses/responses.mjs"; const NON_CHAT_MODELS = [ "text-davinci-002", @@ -49,6 +58,139 @@ const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => { }); }; +const formatMessageForO1OrGpt5ForResponses = ( + messages: ChatCompletionMessageParam[], +): ResponseInputItem[] => { + const input: ResponseInputItem[] = []; + + const pushMessage = ( + role: "user" | "assistant" | "system" | "developer", + content: string | ResponseInputMessageContentList, + ) => { + // o-series / gpt-5 use `developer` instead of `system` + const normalizedRole: "user" | "assistant" | "system" | "developer" = + role === "system" ? "developer" : role; + + input.push({ role: normalizedRole, content }); + }; + + for (const message of messages) { + switch (message.role) { + case "system": + case "developer": { + const content = message.content; + if (typeof content === "string") { + pushMessage("developer", content); + } else if (Array.isArray(content)) { + const parts: ResponseInputMessageContentList = content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => ({ type: "input_text" as const, text: p.text })); + pushMessage("developer", parts.length ? parts : ""); + } + break; + } + + case "user": { + const content = message.content; + if (typeof content === "string") { + pushMessage("user", content); + } else if (Array.isArray(content)) { + const parts: ResponseInputMessageContentList = []; + for (const part of content) { + if (part.type === "text") { + parts.push({ type: "input_text", text: part.text }); + } else if (part.type === "image_url") { + parts.push({ + type: "input_image", + image_url: part.image_url.url, + detail: part.image_url.detail ?? "auto", + }); + } else if (part.type === "file") { + parts.push({ + type: "input_file", + file_data: part.file.file_data, + file_id: part.file.file_id ?? undefined, + filename: part.file.filename, + }); + } + } + if (parts.length) { + pushMessage("user", parts); + } + } + break; + } + + case "assistant": { + const content = message.content; + if (typeof content === "string") { + if (content.length) pushMessage("assistant", content); + } else if (Array.isArray(content)) { + const text = content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => p.text) + .join(""); + if (text.length) pushMessage("assistant", text); + } + + if (Array.isArray(message.tool_calls)) { + for (const tc of message.tool_calls) { + if (tc.type === "function") { + input.push({ + type: "function_call", + name: tc.function.name, + arguments: tc.function.arguments, + call_id: tc.id, + }); + } else if (tc.type === "custom") { + input.push({ + type: "custom_tool_call", + name: tc.custom.name, + input: tc.custom.input, + call_id: tc.id, + }); + } + } + } + break; + } + + case "tool": { + const content = message.content; + const output = + typeof content === "string" + ? content + : content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => p.text) + .join(""); + input.push({ + type: "function_call_output", + call_id: message.tool_call_id, + output, + }); + break; + } + + case "function": { + // Deprecated in Chat Completions; no safe mapping into Responses input + break; + } + + default: + break; + } + } + + return input; +}; + class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; @@ -134,7 +276,10 @@ class OpenAI extends BaseLLM { options: CompletionOptions, messages: ChatMessage[], ): ChatCompletionCreateParams { - const finalOptions = toChatBody(messages, options); + const finalOptions = toChatBody(messages, options, { + includeReasoningField: this.supportsReasoningField, + includeReasoningDetailsField: this.supportsReasoningDetailsField, + }); finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); @@ -171,6 +316,60 @@ class OpenAI extends BaseLLM { return finalOptions; } + protected _convertArgsResponses( + options: CompletionOptions, + messages: ChatMessage[], + ): ResponseCreateParamsBase { + // Specialized conversion for Responses API (strongly typed body) + const model = options.model; + + const input = toResponsesInput(messages); + + const body: ResponseCreateParamsBase = { + model, + input, + temperature: options.temperature ?? null, + top_p: options.topP ?? null, + reasoning: { + effort: "medium", + summary: "auto", + }, + include: ["reasoning.encrypted_content"], + }; + + // Tools support for Responses API (schema differs from Chat Completions) + if (options.tools?.length) { + body.tools = options.tools + .filter((t) => !t.type || t.type === "function") + .map( + (t) => + ({ + type: "function", + name: t.function.name, + description: t.function.description ?? undefined, + parameters: t.function.parameters ?? undefined, + strict: t.function.strict ?? undefined, + }) as ResponsesTool, + ); + } + if (options.toolChoice) { + body.tool_choice = { + type: "function", + name: options.toolChoice.function.name, + } as ResponseCreateParamsBase["tool_choice"]; + } + + if (typeof options.maxTokens === "number") { + body.max_output_tokens = options.maxTokens; + } + + if (model === "o1") { + body.stream = false; + } + + return body; + } + protected _getHeaders() { return { "Content-Type": "application/json", @@ -197,7 +396,7 @@ class OpenAI extends BaseLLM { } protected _getEndpoint( - endpoint: "chat/completions" | "completions" | "models", + endpoint: "chat/completions" | "completions" | "models" | "responses", ) { if (!this.apiBase) { throw new Error( @@ -368,6 +567,91 @@ class OpenAI extends BaseLLM { } } + // Minimal draft: Responses API support for select models + protected async *_streamResponses( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + if (!this.isOSeriesOrGpt5Model(options.model)) { + return; + } + + const body: any = this._convertArgsResponses(options, messages); + + // o1 does not support streaming + if (body.model === "o1") { + const res = await this._responses(messages, signal, options); + if (Array.isArray(res)) { + for (const m of res) { + if (m) yield m; + } + } else if (res) { + yield res; + } + return; + } + + const response = await this.fetch(this._getEndpoint("responses"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify({ + ...body, + stream: true, + ...this.extraBodyProperties(), + }), + signal, + }); + + for await (const evt of streamSse(response)) { + try { + const msg = fromResponsesChunk(evt); + if (Array.isArray(msg)) { + for (const m of msg) { + if (m) yield m; + } + } else if (msg) { + yield msg; + } + } catch { + // ignore malformed chunks + } + } + } + + protected async _responses( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): Promise { + if (!this.isOSeriesOrGpt5Model(options.model)) { + // Minimal draft: only handle supported models for now + return { role: "assistant", content: "" }; + } + + const body: any = this._convertArgsResponses(options, messages); + + const response = await this.fetch(this._getEndpoint("responses"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify({ + ...body, + stream: false, + ...this.extraBodyProperties(), + }), + signal, + }); + + if ((response as any).status === 499) { + return { role: "assistant", content: "" }; + } + + const data: any = await response.json().catch(() => ({})); + const msg = fromResponsesChunk(data); + if (msg) return msg; + return { role: "assistant", content: "" }; + } + protected async *_streamFim( prefix: string, suffix: string, diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts index f2ef6bde2..4672a4658 100644 --- a/core/llm/llms/OpenRouter.ts +++ b/core/llm/llms/OpenRouter.ts @@ -7,6 +7,8 @@ import OpenAI from "./OpenAI.js"; class OpenRouter extends OpenAI { static providerName = "openrouter"; + protected supportsReasoningField = true; + protected supportsReasoningDetailsField = true; static defaultOptions: Partial = { apiBase: "https://openrouter.ai/api/v1/", model: "gpt-4o-mini", diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 76dc897ad..1d1d473dd 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -5,6 +5,7 @@ import { Chunk, CompletionOptions, LLMOptions, + TextMessagePart, ToolCallDelta, ToolResultChatMessage, } from "../../index.js"; @@ -103,11 +104,30 @@ class WatsonX extends BaseLLM { })); delete message_.toolCalls; delete message_.content; - } else if ( - message_.role === "user" && - typeof message_.content === "string" - ) { - message_.content = [{ type: "text", text: message_.content }]; + } else if (message_.role === "user") { + if (typeof message.content === "string") { + message_.content = [{ type: "text", text: message_.content }]; + } else { + return { + role: "user", + content: !message.content.some((item) => item.type !== "text") + ? message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " " + : message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url" as const, + image_url: { + url: part.imageUrl.url, + detail: "auto" as const, + }, + }; + } + return part; + }), + }; + } } return message_; } diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 75ea7ee91..a7e3d6bac 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -4,15 +4,97 @@ import { ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionCreateParams, + ChatCompletionMessage, ChatCompletionMessageParam, CompletionCreateParams, } from "openai/resources/index"; +import type { + EasyInputMessage, + Response as OpenAIResponse, + ResponseFunctionToolCall, + ResponseInput, + ResponseInputItem, + ResponseInputMessageContentList, + ResponseOutputMessage, + ResponseOutputText, + ResponseReasoningItem, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, + ResponseReasoningTextDeltaEvent, + ResponseReasoningTextDoneEvent, + ResponseStreamEvent, + ResponseTextDeltaEvent, +} from "openai/resources/responses/responses.mjs"; -import { ChatMessage, CompletionOptions, TextMessagePart } from ".."; +import { + AssistantChatMessage, + ChatMessage, + CompletionOptions, + MessageContent, + MessagePart, + TextMessagePart, + ThinkingChatMessage, + ToolCallDelta, +} from ".."; + +function appendReasoningFieldsIfSupported( + msg: ChatCompletionAssistantMessageParam & { + reasoning?: string; + reasoning_details?: any[]; + }, + options: CompletionOptions, + prevMessage?: ChatMessage, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, +) { + if (!prevMessage || prevMessage.role !== "thinking") return; + + const includeReasoning = !!providerFlags?.includeReasoningField; + const includeReasoningDetails = !!providerFlags?.includeReasoningDetailsField; + if (!includeReasoning && !includeReasoningDetails) return; + + const reasoningDetailsValue = + prevMessage.reasoning_details || + (prevMessage.signature + ? [{ signature: prevMessage.signature }] + : undefined); + + // Claude-specific safeguard: prevent errors when switching to Claude after another model. + // Claude requires a signed reasoning_details block; if missing, we must omit both fields. + // This check is done before adding any fields to avoid deletes. + if ( + includeReasoningDetails && + options.model.includes("claude") && + !( + Array.isArray(reasoningDetailsValue) && + reasoningDetailsValue.some((d) => d && d.signature) + ) + ) { + console.warn( + "Omitting reasoning fields for Claude: no signature present in reasoning_details", + ); + return; + } + + if (includeReasoningDetails && reasoningDetailsValue) { + msg.reasoning_details = reasoningDetailsValue || []; + } + if (includeReasoning) { + msg.reasoning = prevMessage.content as string; + } +} export function toChatMessage( message: ChatMessage, -): ChatCompletionMessageParam { + options: CompletionOptions, + prevMessage?: ChatMessage, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, +): ChatCompletionMessageParam | null { if (message.role === "tool") { return { role: "tool", @@ -26,18 +108,30 @@ export function toChatMessage( content: message.content, }; } + if (message.role === "thinking") { + // Return null - thinking messages are merged into following assistant messages + return null; + } if (message.role === "assistant") { - const msg: ChatCompletionAssistantMessageParam = { + // Base assistant message + const msg: ChatCompletionAssistantMessageParam & { + reasoning?: string; + reasoning_details?: { + [key: string]: any; + signature?: string | undefined; + }[]; + } = { role: "assistant", content: typeof message.content === "string" ? message.content || " " // LM Studio (and other providers) don't accept empty content : message.content .filter((part) => part.type === "text") - .map((part) => part as TextMessagePart), // can remove with newer typescript version + .map((part) => part as TextMessagePart), }; + // Add tool calls if present if (message.toolCalls) { msg.tool_calls = message.toolCalls.map((toolCall) => ({ id: toolCall.id!, @@ -48,7 +142,16 @@ export function toChatMessage( }, })); } - return msg; + + // Preserving reasoning blocks + appendReasoningFieldsIfSupported( + msg as any, + options, + prevMessage, + providerFlags, + ); + + return msg as ChatCompletionMessageParam; } else { if (typeof message.content === "string") { return { @@ -62,11 +165,8 @@ export function toChatMessage( // that don't support multi-media format return { role: "user", - content: !message.content.some((item) => item.type !== "text") - ? message.content - .map((item) => (item as TextMessagePart).text) - .join("") || " " - : message.content.map((part) => { + content: message.content.some((item) => item.type !== "text") + ? message.content.map((part) => { if (part.type === "imageUrl") { return { type: "image_url" as const, @@ -77,7 +177,10 @@ export function toChatMessage( }; } return part; - }), + }) + : message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " ", }; } } @@ -85,9 +188,17 @@ export function toChatMessage( export function toChatBody( messages: ChatMessage[], options: CompletionOptions, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, ): ChatCompletionCreateParams { const params: ChatCompletionCreateParams = { - messages: messages.map(toChatMessage), + messages: messages + .map((m, index) => + toChatMessage(m, options, messages[index - 1], providerFlags), + ) + .filter((m) => m !== null) as ChatCompletionMessageParam[], model: options.model, max_tokens: options.maxTokens, temperature: options.temperature, @@ -153,11 +264,40 @@ export function toFimBody( } as any; } -export function fromChatResponse(response: ChatCompletion): ChatMessage { - const message = response.choices[0].message; +export function fromChatResponse(response: ChatCompletion): ChatMessage[] { + const messages: ChatMessage[] = []; + const message = response.choices[0].message as ChatCompletionMessage & { + reasoning?: string; + reasoning_content?: string; + reasoning_details?: { + signature?: string; + [key: string]: any; + }[]; + }; + + // Check for reasoning content first (similar to fromChatCompletionChunk) + if (message.reasoning_content || message.reasoning) { + const thinkingMessage: ChatMessage = { + role: "thinking", + content: (message as any).reasoning_content || (message as any).reasoning, + }; + + // Preserve reasoning_details if present + if (message.reasoning_details) { + thinkingMessage.reasoning_details = message.reasoning_details; + // Extract signature from reasoning_details if available + if (message.reasoning_details[0]?.signature) { + thinkingMessage.signature = message.reasoning_details[0].signature; + } + } + + messages.push(thinkingMessage); + } + + // Then add the assistant message const toolCall = message.tool_calls?.[0]; if (toolCall) { - return { + messages.push({ role: "assistant", content: "", toolCalls: message.tool_calls @@ -170,19 +310,29 @@ export function fromChatResponse(response: ChatCompletion): ChatMessage { arguments: (tc as any).function?.arguments, }, })), - }; + }); + } else { + messages.push({ + role: "assistant", + content: message.content ?? "", + }); } - return { - role: "assistant", - content: message.content ?? "", - }; + return messages; } export function fromChatCompletionChunk( chunk: ChatCompletionChunk, ): ChatMessage | undefined { - const delta = chunk.choices?.[0]?.delta; + const delta = chunk.choices?.[0]?.delta as + | (ChatCompletionChunk.Choice.Delta & { + reasoning?: string; + reasoning_content?: string; + reasoning_details?: { + signature?: string; + }[]; + }) + | undefined; if (delta?.content) { return { @@ -208,11 +358,568 @@ export function fromChatCompletionChunk( toolCalls, }; } + } else if ( + delta?.reasoning_content || + delta?.reasoning || + delta?.reasoning_details?.length + ) { + const message: ThinkingChatMessage = { + role: "thinking", + content: delta.reasoning_content || delta.reasoning || "", + signature: delta?.reasoning_details?.[0]?.signature, + reasoning_details: delta?.reasoning_details as any[], + }; + return message; } return undefined; } +function handleTextDeltaEvent( + e: ResponseTextDeltaEvent, +): ChatMessage | undefined { + return e.delta ? { role: "assistant", content: e.delta } : undefined; +} + +function handleFunctionCallArgsDelta(e: any): ChatMessage | undefined { + const ev: any = e as any; + const item = ev.item || {}; + const name = item && typeof item.name === "string" ? item.name : undefined; + const argDelta = + typeof ev.delta === "string" + ? ev.delta + : (ev.delta?.arguments ?? ev.arguments); + if (typeof argDelta === "string" && argDelta.length > 0) { + const call_id = + (item?.call_id as string | undefined) || + (item?.id as string | undefined) || + ""; + const toolCalls: ToolCallDelta[] = [ + { + id: call_id, + type: "function", + function: { name: name || "", arguments: argDelta }, + }, + ]; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + }; + return assistant; + } + return undefined; +} + +function handleOutputItemAdded( + e: ResponseStreamEvent, +): ChatMessage | undefined { + const item = (e as any).item as { + type?: string; + id?: string; + name?: string; + arguments?: string; + call_id?: string; + summary?: Array<{ type: string; text: string }>; + encrypted_content?: string; + }; + if (!item || !item.type) return undefined; + if (item.type === "reasoning") { + const details: Array<{ [k: string]: unknown }> = []; + if (item.id) details.push({ type: "reasoning_id", id: item.id }); + if (typeof item.encrypted_content === "string" && item.encrypted_content) { + details.push({ + type: "encrypted_content", + encrypted_content: item.encrypted_content, + }); + } + if (Array.isArray(item.summary)) { + for (const part of item.summary) { + if (part?.type === "summary_text" && typeof part.text === "string") { + details.push({ type: "summary_text", text: part.text }); + } + } + } + const thinking: ThinkingChatMessage = { + role: "thinking", + content: "", + reasoning_details: details, + metadata: { + reasoningId: item.id as string, + encrypted_content: item.encrypted_content as string | undefined, + }, + }; + return thinking; + } + if (item.type === "message" && typeof item.id === "string") { + return { + role: "assistant", + content: "", + metadata: { responsesOutputItemId: item.id }, + }; + } + if (item.type === "function_call" && typeof item.id === "string") { + const name = item.name as string | undefined; + const args = typeof item.arguments === "string" ? item.arguments : ""; + const call_id = item.call_id as string | undefined; + const toolCalls: ToolCallDelta[] = name + ? [ + { + id: call_id || (item.id as string), + type: "function", + function: { name, arguments: args }, + }, + ] + : []; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + metadata: { responsesOutputItemId: item.id as string }, + }; + return assistant; + } + return undefined; +} + +function handleReasoningSummaryDelta( + e: ResponseReasoningSummaryTextDeltaEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = [ + { type: "summary_text", text: e.delta }, + ]; + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.delta, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningSummaryDone( + e: ResponseReasoningSummaryTextDoneEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = []; + if (e.text) details.push({ type: "summary_text", text: e.text }); + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.text, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningTextDelta( + e: ResponseReasoningTextDeltaEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = [ + { type: "reasoning_text", text: e.delta }, + ]; + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.delta, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningTextDone( + e: ResponseReasoningTextDoneEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = []; + if (e.text) details.push({ type: "reasoning_text", text: e.text }); + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.text, + reasoning_details: details, + }; + return thinking; +} + +function handleResponsesStreamEvent( + e: ResponseStreamEvent, +): ChatMessage | undefined { + const t = (e as any).type as string; + if (t === "response.output_text.delta") { + return handleTextDeltaEvent(e as ResponseTextDeltaEvent); + } + if (t === "response.output_text.done") { + return undefined; // avoid duplicate final text + } + if (t === "response.function_call_arguments.delta") { + return handleFunctionCallArgsDelta(e); + } + if (t === "response.function_call_arguments.done") { + return undefined; + } + if (t === "response.output_item.added") { + return handleOutputItemAdded(e); + } + if (t === "response.reasoning_summary_text.delta") { + return handleReasoningSummaryDelta( + e as ResponseReasoningSummaryTextDeltaEvent, + ); + } + if (t === "response.reasoning_summary_text.done") { + return handleReasoningSummaryDone( + e as ResponseReasoningSummaryTextDoneEvent, + ); + } + if (t === "response.reasoning_text.delta") { + return handleReasoningTextDelta(e as ResponseReasoningTextDeltaEvent); + } + if (t === "response.reasoning_text.done") { + return handleReasoningTextDone(e as ResponseReasoningTextDoneEvent); + } + return undefined; +} + +function handleResponsesFinal( + resp: OpenAIResponse, +): ChatMessage | ChatMessage[] | undefined { + // Prefer structured output items when present + if (Array.isArray(resp.output) && resp.output.length > 0) { + const result: ChatMessage[] = []; + for (const raw of resp.output as any[]) { + const item = raw as any; + if (!item || typeof item !== "object") continue; + if (item.type === "reasoning") { + const details: Array<{ [k: string]: unknown }> = []; + if (typeof item.id === "string") { + details.push({ type: "reasoning_id", id: item.id }); + } + if (Array.isArray(item.summary)) { + for (const s of item.summary) { + if (s?.type === "summary_text" && typeof s.text === "string") { + details.push({ type: "summary_text", text: s.text }); + } + } + } + if (Array.isArray(item.content)) { + for (const c of item.content) { + if (c?.type === "reasoning_text" && typeof c.text === "string") { + details.push({ type: "reasoning_text", text: c.text }); + } + } + } + if ( + typeof item.encrypted_content === "string" && + item.encrypted_content + ) { + details.push({ + type: "encrypted_content", + encrypted_content: item.encrypted_content, + }); + } + const thinking: ThinkingChatMessage = { + role: "thinking", + content: "", + reasoning_details: details, + metadata: { + reasoningId: item.id as string, + encrypted_content: item.encrypted_content as string | undefined, + }, + }; + result.push(thinking); + continue; + } + if (item.type === "message") { + let text = ""; + if (Array.isArray(item.content)) { + text = (item.content as any[]) + .map((c) => (typeof c?.text === "string" ? c.text : "")) + .join(""); + } else if (typeof item.content === "string") { + text = item.content; + } + const assistant: AssistantChatMessage = { + role: "assistant", + content: text || "", + metadata: + typeof item.id === "string" + ? { responsesOutputItemId: item.id } + : undefined, + }; + result.push(assistant); + continue; + } + if (item.type === "function_call") { + const name = item.name as string | undefined; + const args = + typeof item.arguments === "string" + ? item.arguments + : JSON.stringify(item.arguments ?? ""); + const call_id = + (item.call_id as string | undefined) || + (item.id as string | undefined) || + ""; + const toolCalls: ToolCallDelta[] = name + ? [ + { + id: call_id, + type: "function", + function: { name, arguments: args || "" }, + }, + ] + : []; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + metadata: + typeof item.id === "string" + ? { responsesOutputItemId: item.id } + : undefined, + }; + result.push(assistant); + continue; + } + } + if (result.length > 0) return result; + } + + // Fallback to output_text when no structured output is present + if (typeof resp.output_text === "string" && resp.output_text.length > 0) { + return { role: "assistant", content: resp.output_text }; + } + + return undefined; +} + +export function fromResponsesChunk( + event: ResponseStreamEvent | OpenAIResponse, +): ChatMessage | ChatMessage[] | undefined { + if (typeof (event as any).type === "string") { + return handleResponsesStreamEvent(event as ResponseStreamEvent); + } + return handleResponsesFinal(event as OpenAIResponse); +} + +export function mergeReasoningDetails( + existing: any[] | undefined, + delta: any[] | undefined, +): any[] | undefined { + if (!delta) return existing; + if (!existing) return delta; + + const result = [...existing]; + + for (const deltaItem of delta) { + // Skip items without a type + if (!deltaItem.type) { + continue; + } + + // Find existing item with the same type + const existingIndex = result.findIndex( + (item) => item.type === deltaItem.type, + ); + + if (existingIndex === -1) { + // No existing item with this type, add new item + result.push({ ...deltaItem }); + } else { + // Merge with existing item of the same type + const existingItem = result[existingIndex]; + + for (const [key, value] of Object.entries(deltaItem)) { + if (value === null || value === undefined) continue; + + if (key === "text" || key === "signature" || key === "summary") { + // Concatenate text and signature fields + existingItem[key] = (existingItem[key] || "") + value; + } else if (key !== "type") { + // Don't overwrite type + // Overwrite other fields + existingItem[key] = value; + } + } + } + } + + return result; +} + +function getTextFromMessageContent(content: MessageContent): string { + if (typeof content === "string") return content; + return content + .filter((p): p is TextMessagePart => p.type === "text") + .map((p) => p.text) + .join(""); +} + +function toResponseInputContentList( + parts: MessagePart[], +): ResponseInputMessageContentList { + const list: ResponseInputMessageContentList = []; + for (const part of parts) { + if (part.type === "text") { + list.push({ type: "input_text", text: part.text }); + } else if (part.type === "imageUrl") { + list.push({ + type: "input_image", + image_url: part.imageUrl.url, + detail: "auto", + }); + } + } + return list; +} + +export function toResponsesInput(messages: ChatMessage[]): ResponseInput { + const input: ResponseInput = []; + + const pushMessage = ( + role: "user" | "assistant" | "system" | "developer", + content: string | ResponseInputMessageContentList, + ) => { + const normalizedRole: "user" | "assistant" | "system" | "developer" = + role === "system" ? "developer" : role; + const easyMsg: EasyInputMessage = { + role: normalizedRole, + content, + type: "message", + }; + input.push(easyMsg as ResponseInputItem); + }; + + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + switch (msg.role) { + case "system": { + const content = getTextFromMessageContent(msg.content); + pushMessage("developer", content || ""); + break; + } + case "user": { + if (typeof msg.content === "string") { + pushMessage("user", msg.content); + } else if (Array.isArray(msg.content)) { + const parts = toResponseInputContentList( + msg.content as MessagePart[], + ); + pushMessage("user", parts.length ? parts : ""); + } + break; + } + case "assistant": { + const text = getTextFromMessageContent(msg.content); + + const respId = msg.metadata?.responsesOutputItemId as + | string + | undefined; + const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined; + + if (respId && Array.isArray(toolCalls) && toolCalls.length > 0) { + // Emit full function_call output item + const tc = toolCalls[0]; + const name = tc?.function?.name as string | undefined; + const args = tc?.function?.arguments as string | undefined; + const call_id = tc?.id as string | undefined; + const functionCallItem: ResponseFunctionToolCall = { + id: respId, + type: "function_call", + name: name || "", + arguments: typeof args === "string" ? args : "{}", + call_id: call_id || respId, + }; + input.push(functionCallItem); + } else if (respId) { + // Emit full assistant output message item + const outputMessageItem: ResponseOutputMessage = { + id: respId, + role: "assistant", + type: "message", + status: "completed", + content: [ + { + type: "output_text", + text: text || "", + annotations: [], + } satisfies ResponseOutputText, + ], + }; + input.push(outputMessageItem); + } else { + // Fallback to EasyInput assistant message + pushMessage("assistant", text || ""); + } + break; + } + case "tool": { + const call_id = msg.toolCallId; + const output = + typeof msg.content === "string" + ? msg.content + : JSON.stringify(msg.content); + const functionCallOutput: ResponseInputItem = { + type: "function_call_output", + call_id, + output, + } as ResponseInputItem; + input.push(functionCallOutput); + break; + } + case "thinking": { + const details = (msg as ThinkingChatMessage).reasoning_details ?? []; + if (details.length) { + let id: string | undefined; + let summaryText = ""; + let encrypted: string | undefined; + let reasoningText = ""; + for (const raw of details as Array>) { + const d = raw as { + type?: string; + id?: string; + text?: string; + encrypted_content?: string; + }; + if (d.type === "reasoning_id" && d.id) id = d.id; + else if (d.type === "encrypted_content" && d.encrypted_content) + encrypted = d.encrypted_content; + else if (d.type === "summary_text" && typeof d.text === "string") + summaryText += d.text; + else if (d.type === "reasoning_text" && typeof d.text === "string") + reasoningText += d.text; + } + if (id) { + const reasoningItem: ResponseReasoningItem = { + id, + type: "reasoning", + summary: [], + } as ResponseReasoningItem; + if (summaryText) { + reasoningItem.summary = [ + { type: "summary_text", text: summaryText }, + ]; + } + if (reasoningText) { + reasoningItem.content = [ + { type: "reasoning_text", text: reasoningText }, + ]; + } + if (encrypted) { + reasoningItem.encrypted_content = encrypted; + } + input.push(reasoningItem as ResponseInputItem); + } + } + break; + } + } + } + + return input; +} + export type LlmApiRequestType = | "chat" | "streamChat" diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index 6a3837e3a..da6628d2f 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -24,7 +24,9 @@ export async function getPromptFilesFromDir( const uris = await walkDir(dir, ide, { source: "get dir prompt files", }); - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const promptFilePaths = uris.filter( + (p) => p.endsWith(".prompt") || p.endsWith(".md"), + ); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch return { path: uri, content }; @@ -68,10 +70,11 @@ export async function getAllPromptFiles( ); promptFiles.push(...promptFilesFromRulesDirectory); - return await Promise.all( + const result = await Promise.all( promptFiles.map(async (file) => { const content = await ide.readFile(file.path); return { path: file.path, content }; }), ); + return result; } diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index c9e78d62d..bac426f71 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -13,7 +13,7 @@ export const grepSearchTool: Tool = { function: { name: BuiltInToolNames.GrepSearch, description: - "Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries", + "Performs a regex search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries", parameters: { type: "object", required: ["query"], @@ -21,7 +21,7 @@ export const grepSearchTool: Tool = { query: { type: "string", description: - "The search query to use. Must be a valid ripgrep regex expression, escaped where needed", + "The search query to use. Must be the exact string to be searched or a valid ripgrep expression. Use regex with alternation (e.g., 'word1|word2|word3) or character classes to find multiple potential words in a single search.", }, }, }, diff --git a/docs/docs.json b/docs/docs.json index 644544d1f..88cea7782 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -260,9 +260,11 @@ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", "guides/github-mcp-continue-cookbook", + "guides/atlassian-mcp-continue-cookbook", "guides/sanity-mcp-continue-cookbook", "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", + "guides/supabase-mcp-database-workflow", "guides/dlt-mcp-continue-cookbook", "guides/netlify-mcp-continuous-deployment", "guides/chrome-devtools-mcp-performance" diff --git a/docs/guides/atlassian-mcp-continue-cookbook.mdx b/docs/guides/atlassian-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..9b4b8cc9c --- /dev/null +++ b/docs/guides/atlassian-mcp-continue-cookbook.mdx @@ -0,0 +1,511 @@ +--- +title: "Jira Issues and Confluence Pages with Atlassian MCP and Continue" +description: "Use Continue and the Atlassian Rovo MCP to search, summarize, and manage Jira issues, Confluence pages, and Compass components with natural language prompts." +sidebarTitle: "Atlassian Workflows with Continue" +--- + + + An Atlassian workflow assistant that uses Continue with the Atlassian Rovo MCP to: + - Search and summarize Jira issues across projects + - Find and digest Confluence documentation + - Create and update Jira issues with natural language + - Query Compass components and service dependencies + - Automate Atlassian workflows with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Node.js 18+ installed locally +- An Atlassian Cloud site with Jira, Confluence, and/or Compass +- Access to the Atlassian products you want to integrate with + + + The Atlassian Rovo MCP Server is currently in **Beta**. Core functionality is available, but some features are still under development. + + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + The Atlassian MCP uses **OAuth 2.1** for authentication. The first time you connect, you'll complete a browser-based authorization flow that respects your existing Atlassian permissions. + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + All data access respects your existing Jira, Confluence, and Compass user permissions. + + +## Choose Your Atlassian Agent + + + We've created two ready-to-use agents to help you get started fast - they come pre-configured with optimized prompts, rules, and the Atlassian MCP. You don't have to use these agents, but they're designed to give you the best experience right away. Choose the agent that matches your needs, or create your own custom agent. + + +### Agent Quick Reference + +| Agent | Best For | Use Cases | Link | +|-------|----------|-----------|------| +| **Jira Agent** | Issue Management | Search issues, create stories, sprint planning, status updates, bulk operations | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) | +| **Confluence Agent** | Documentation | Search pages, summarize docs, create/update pages, manage spaces | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) | + + + **Cross-product workflows**: Both agents can work with Jira, Confluence, and Compass. Choose based on your primary focus area, or create your own agent using the [Atlassian MCP](https://hub.continue.dev/atlassian/atlassian-mcp). The Atlassian MCP can work with Jira, Compass, or Confluence. + + + + + + + Visit the [Atlassian Continuous AI - Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) on Continue Hub. This agent is optimized for: + - Searching and filtering Jira issues + - Creating and updating issues + - Sprint planning and workload analysis + - Issue transitions and status updates + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me my open issues assigned to me" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Jira agent: + ```bash + alias jira-ai='cn --agent continuedev/atlassian-continuous-ai-jira-agent' + ``` + Then use: `jira-ai "your prompt"` + + + + + + + Visit the [Atlassian Continuous AI - Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) on Continue Hub. This agent is optimized for: + - Searching and summarizing documentation + - Creating and updating Confluence pages + - Managing spaces and content + - Documentation discovery + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Confluence agent: + ```bash + alias confluence-ai='cn --agent continuedev/atlassian-continuous-ai-confluence-agent' + ``` + Then use: `confluence-ai "your prompt"` + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: Atlassian Rovo MCP + type: sse + url: https://mcp.atlassian.com/v1/sse + connectionTimeout: 30 + ``` + + Notes: + - The Atlassian MCP uses **Server-Sent Events (SSE)** transport type + - OAuth is handled automatically on first connection + - No API keys or tokens needed in the config + + + + Launch Continue and ask: + ``` + List my Jira projects + ``` + You'll be prompted to authorize in your browser if this is your first time. + + + + + + + To use Atlassian MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the Atlassian MCP for Jira, Confluence, and Compass operations. + + + +--- + +## Jira Workflows + + + **Using the Jira Agent**: All examples below use the [Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) which is optimized for issue management. + + +Use natural language to explore, triage, and manage Jira issues. The agent calls Atlassian MCP tools under the hood. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Discovery + + + + Search for bugs across your projects. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Find all open bugs in Project Alpha" + ``` + + + + Get a list of issues assigned to you. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me all issues assigned to me that are in progress" + ``` + + + + Analyze sprint workload and priorities. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "List all issues in the current sprint. Group by assignee and priority. Summarize the workload distribution and flag any overloaded team members." + ``` + + + +### Create and Update + + + + Turn natural language into a Jira story. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a story titled 'Redesign onboarding flow' in Project Alpha. Description: We need to simplify the user registration process by reducing steps from 5 to 3. Target completion: Q3." + ``` + + + + Create multiple issues from meeting notes or specs. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create five Jira issues from these meeting notes: 1) Fix login timeout bug 2) Update API documentation 3) Implement dark mode toggle 4) Review security audit findings 5) Optimize database queries" + ``` + + + + Transition issues with natural language. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Move PROJ-123 to In Progress and add a comment: Starting work on this today. ETA: end of week." + ``` + + + +--- + +## Confluence Workflows + + + **Using the Confluence Agent**: All examples below use the [Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) which is optimized for documentation management. + + +Access, search, and manage your team's documentation directly from Continue. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Summarize + + + + Get a quick summary of a Confluence page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page from the Engineering space" + ``` + + + + Search for specific information across Confluence. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Find all pages about API authentication in our developer docs" + ``` + + + + Discover what Confluence spaces you have access to. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "What Confluence spaces do I have access to?" + ``` + + + +### Create and Update + + + + Generate a new Confluence page with structured content. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Create a page titled 'Team Goals Q3' in the Engineering space. Include sections for: Objectives, Key Results, and Timeline." + ``` + + + + Modify content on an existing page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Update the 'Onboarding Guide' page to add a new section about our code review process" + ``` + + + +--- + +## Compass Workflows + + + **Using Either Agent**: Compass workflows work with both agents. Use the Jira agent for component-to-issue workflows, or the Confluence agent for component-to-docs workflows. + + +Query and manage your service architecture with Compass integration. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + +### Service Discovery + + + + Understand service relationships. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "What services depend on the api-gateway component?" + ``` + + + + Register a new service in Compass. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a service component for the current repository. Use the package.json to infer details." + ``` + + + + Import multiple components from structured data. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components and custom fields from this CSV: [paste CSV data]" + ``` + + Or reference a file: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components from services.csv in the current directory" + ``` + + + +--- + +## Combined Workflows + + + **Cross-Product Workflows**: These workflows span multiple Atlassian products. Choose the agent based on your primary focus: + - Use **Jira Agent** when the workflow is issue-centric + - Use **Confluence Agent** when the workflow is documentation-centric + + +Integrate actions across Jira, Confluence, and Compass for powerful cross-product workflows. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + + + + Connect related content across products. + + ```bash + # Using Jira Agent for issue-centric workflow + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Link Jira tickets PROJ-123, PROJ-456, and PROJ-789 to the 'Sprint 23 Release Plan' Confluence page" + ``` + + + + Find documentation for a specific component. + + ```bash + # Using Confluence Agent for docs-centric workflow + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Fetch the Confluence documentation page linked to the user-authentication Compass component" + ``` + + + + Create release documentation from completed work. + + ```bash + # Using Jira Agent to pull issue data and create in Confluence + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Generate release notes for all Jira issues completed in Sprint 23. Create a Confluence page in the Release Notes space with: New features (grouped by epic), Bug fixes, Known issues, Deployment instructions" + ``` + + + +--- + +## Troubleshooting + + + + - **"Your site admin must authorize this app"**: A site admin needs to complete the OAuth flow first before other users can connect + - **Can't complete browser authorization**: Ensure you're logged into the correct Atlassian Cloud site and have necessary permissions + - **Connection timeout**: Increase `connectionTimeout` in your MCP config or check your network connection + + + + - **"Access denied" or "Forbidden"**: The MCP respects your existing Atlassian permissions. Verify you have access to the project/space/component you're trying to access + - **Can't create issues**: Ensure you have "Create issues" permission in the target Jira project + - **Can't edit Confluence pages**: Verify you have edit permissions in the target Confluence space + + + + - **Standard plan**: Moderate usage thresholds + - **Premium/Enterprise plans**: Higher quotas (1,000 requests/hour plus per-user limits) + - If you hit rate limits, reduce query frequency or batch operations + + + + - Bulk operations may be constrained by rate limits + - Custom Jira fields may not be recognized without explicit setup + - Workspace/site switching not available within a single session + - Check [Atlassian Community](https://community.atlassian.com/) for known issues + + + +### Admin Considerations + + + **Installation**: The Atlassian Rovo MCP is automatically installed on first OAuth authorization (JIT installation) - no Marketplace installation needed. + + **Managing Access**: + - View connected apps in [Admin Hub](https://admin.atlassian.com) + - Users can revoke access from their [profile settings](https://id.atlassian.com/manage-profile/apps) + - Block user-installed apps via "user-installed apps" control in Admin Hub + + **Security**: All traffic is encrypted via HTTPS (TLS 1.2+), and access respects existing user permissions. + + +--- + +## What You've Built + +After completing this guide, you have a complete **AI-powered Atlassian workflow system** that: + +- āœ… Uses natural language — Simple prompts for complex Atlassian operations +- āœ… Spans multiple products — Seamlessly works across Jira, Confluence, and Compass +- āœ… Respects permissions — Secure OAuth-based access with existing role enforcement +- āœ… Runs headlessly — Integrate into CI/CD pipelines and automation scripts + + + Your Atlassian workflows now operate at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine project management tasks with human oversight through + review and approval. + + +## Next Steps + +1. **Explore your projects** - Try the Jira search and triage prompts +2. **Organize documentation** - Use Confluence workflows to summarize and create pages +3. **Map your services** - Query Compass for service dependencies +4. **Customize prompts** - Tailor workflows to your team's specific needs +5. **Monitor usage** - Track how AI improves your Atlassian workflows + +## Additional Resources + + + + Official Atlassian MCP documentation + + + How MCP works with Continue agents + + + Create and manage your agents + + + Get help and share feedback + + + +## Example Use Cases + + + + Automate release notes generation, link issues to documentation, and track deployment status across Jira and Confluence. + + + Analyze workload distribution, identify blockers, and generate sprint summaries automatically. + + + Map service dependencies in Compass, link to technical documentation in Confluence, and track related issues in Jira. + + + Create standardized Jira onboarding tickets, link to Confluence guides, and track new hire progress. + + diff --git a/docs/guides/github-pr-review-bot.mdx b/docs/guides/github-pr-review-bot.mdx index 4609da384..d95a7c120 100644 --- a/docs/guides/github-pr-review-bot.mdx +++ b/docs/guides/github-pr-review-bot.mdx @@ -42,6 +42,12 @@ Before starting, ensure you have: - A Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) - Continue assistant configured for code reviews (or use our recommended default) + + **Want to customize the review bot?** + + You can remix the default review bot configuration at [hub.continue.dev/continuedev/review-bot](https://hub.continue.dev/continuedev/review-bot) to create your own personalized version with custom prompts, rules, and behaviors. + + ## Quick Setup (10 Minutes) @@ -181,7 +187,7 @@ jobs: Format as markdown suitable for a GitHub pull request comment." # Run Continue CLI in headless mode - cn --config continuedev/code-reviewer \ + cn --config continuedev/review-bot \ -p "$PROMPT" \ --auto > review_output.md @@ -336,7 +342,7 @@ The workflow will respond with a targeted review based on your request. - By default, the workflow uses the `continuedev/code-reviewer` config optimized for code reviews. Replace `continuedev/code-reviewer` with your own config: + By default, the workflow uses the `continuedev/review-bot` config optimized for code reviews. Replace `continuedev/review-bot` with your own config: ```yaml - name: Run Continue Review diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index 0598d7d11..70afbfef9 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -23,12 +23,14 @@ Step-by-step guides for integrating Model Context Protocol (MCP) servers with Co - [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows - [GitHub MCP Cookbook](/guides/github-mcp-continue-cookbook) - Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments +- [Atlassian MCP Cookbook](/guides/atlassian-mcp-continue-cookbook) - Use Atlassian Rovo MCP to search and manage Jira issues, Confluence pages, and Compass components with natural language - [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation - [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP - [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets - [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP - [Sentry Error Monitoring Cookbook](/guides/sentry-mcp-error-monitoring) - Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues - [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers +- [Supabase Database Workflow Cookbook](/guides/supabase-mcp-database-workflow) - Audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Supabase MCP - [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging ## What Advanced Tutorials Are Available diff --git a/docs/guides/sanity-mcp-continue-cookbook.mdx b/docs/guides/sanity-mcp-continue-cookbook.mdx index 3f28479d6..54342921e 100644 --- a/docs/guides/sanity-mcp-continue-cookbook.mdx +++ b/docs/guides/sanity-mcp-continue-cookbook.mdx @@ -72,7 +72,7 @@ After ensuring you meet the **Prerequisites** above, you have two paths to get s - Visit the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) on Continue Hub and click **"Install Agent"** or run: + Visit the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) on Continue Hub and click **"Install Config"** or run: ```bash cn --config continuedev/sanity-agent-config diff --git a/docs/guides/supabase-mcp-database-workflow.mdx b/docs/guides/supabase-mcp-database-workflow.mdx new file mode 100644 index 000000000..b6f68ba2b --- /dev/null +++ b/docs/guides/supabase-mcp-database-workflow.mdx @@ -0,0 +1,512 @@ +--- +title: "Supabase RLS Security Audit and Fixes with MCP" +description: "Learn how to audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Continue CLI and Supabase MCP." +sidebarTitle: "Supabase RLS Security Audit" +--- + + + A security audit workflow that uses Continue CLI with Supabase MCP to identify RLS vulnerabilities, generate secure policies, fix permission issues, and ensure your database follows security best practices. + + +## What You'll Learn + +This cookbook teaches you to: + +- Use [Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp) to audit database security +- Identify tables without Row Level Security (RLS) enabled +- Find and fix overly permissive or missing RLS policies +- Generate secure RLS migrations following best practices +- Automate security audits with GitHub Actions + +## Prerequisites + +Before starting, ensure you have: + +- [Supabase account](https://supabase.com) with an active project +- Node.js 18+ installed locally +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- Basic understanding of SQL and database concepts + + + + ```bash + npm i -g @continuedev/cli + ``` + + + + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) + 2. Sign up or log in to your Continue account + 3. Navigate to your organization settings + 4. Click **"API Keys"** and then **"+ New API Key"** + 5. Copy the API key immediately (you won't see it again!) + 6. Login to the CLI: `cn login` + + + + + Continue CLI can analyze your database schema and generate complex SQL queries - you just need to describe what you want in plain language! + + +## Step 1: Set Up Your Credentials + +First, you'll need to set up access to your Supabase project. + + + + + + **Security First**: Follow [Supabase's security best practices](https://supabase.com/docs/guides/getting-started/mcp#security-risks) when using MCP: + - Never connect to production databases directly + - Use development or staging environments + - Enable read-only mode when possible + - Scope MCP access to specific projects + + + The Supabase MCP supports OAuth authentication for secure access: + + **OAuth Configuration (Recommended)** + + The Supabase MCP will prompt for OAuth authentication when first used. Simply follow the authorization flow. + + **Remote MCP URL** + ``` + https://mcp.supabase.com/mcp + ``` + + + The MCP server can be scoped to a specific project for better security. Configure this during setup. + + + + + To use Supabase MCP effectively, ensure your project has: + + 1. **Development Environment** - Create a separate development project: + - Go to [Supabase Dashboard](https://supabase.com/dashboard) + - Create a new project for development/testing + - Copy the project URL and anon key + + 2. **Database Schema** - Set up some initial tables for testing: + ```sql + -- Example schema for testing + CREATE TABLE users ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + created_at TIMESTAMPTZ DEFAULT NOW() + ); + + CREATE TABLE posts ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + user_id UUID REFERENCES users(id), + title TEXT NOT NULL, + content TEXT, + published BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT NOW() + ); + ``` + + 3. **Row Level Security (RLS)** - Enable RLS for security: + ```sql + ALTER TABLE users ENABLE ROW LEVEL SECURITY; + ALTER TABLE posts ENABLE ROW LEVEL SECURITY; + ``` + + + Use [Supabase Branching](https://supabase.com/docs/guides/deployment/branching) to create isolated development branches for safe testing. + + + + + +## Supabase Database Workflow Options + + + Skip the manual setup and use our pre-built Supabase Continuous AI agent that includes + optimized prompts, rules, and the Supabase MCP for intelligent database management. + + + + **How Supabase MCP Works**: + - Connects to your Supabase project via OAuth + - Provides tools for database queries, schema inspection, and migrations + - Supports read-only mode for safer operations + - Can be scoped to specific projects for security + + + + + **Perfect for:** Immediate database analysis with AI-powered query optimization and schema insights + + + + Visit the [Supabase Continuous AI Agent](https://hub.continue.dev/continuedev/supabase-continuous-ai) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/supabase-continuous-ai + ``` + + This agent includes: + - **Optimized prompts** for database analysis and query generation + - **Built-in rules** for SQL best practices and security + - **[Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp)** for secure database access + - **Automatic authentication** via OAuth flow + + + + Navigate to your project directory and enter this prompt in the Continue CLI TUI: + + ``` + Analyze my Supabase database schema and suggest performance optimizations + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Get consistent results with pre-tested prompts and built-in SQL optimization rules. + + + + + + + + Configure the [Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp) using OAuth: + + The MCP server will automatically prompt for OAuth authentication when you first use it. + + + + Test your Supabase MCP connection with this prompt: + + ``` + List all tables in my Supabase database + ``` + + + + Use this prompt template with Continue CLI to analyze your database: + + ``` + Analyze my Supabase database: + - List all tables with row counts + - Identify tables without indexes + - Find potential N+1 query patterns + - Suggest missing foreign key constraints + - Recommend index optimizations based on table structure + - Generate SQL migrations for suggested improvements + - Check for security issues (missing RLS policies) + ``` + + + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration. For Supabase MCP: + - **Supabase account** with at least one project + - **OAuth authentication** (handled automatically) + - Development or staging environment (not production) + + +--- + + + **Security Best Practices**: + - **Never use MCP with production databases** - Always use development or staging environments + - **Enable read-only mode** when analyzing data to prevent accidental modifications + - **Scope to specific projects** to limit access + - **Use branch databases** for testing schema changes + + +## Step 2: Analyze Your Database with AI + +Use Continue CLI to perform intelligent database analysis. Enter these prompts in the Continue CLI TUI: + + + + **Prompt:** + ``` + Analyze my Supabase database schema and provide: + - Complete table structure with data types + - Relationships between tables + - Missing indexes that could improve performance + - Unused or redundant columns + - Suggestions for normalization improvements + ``` + + + + **Prompt:** + ``` + Perform a comprehensive RLS (Row Level Security) audit on my Supabase database: + + For each table: + - Check if RLS is enabled + - List all existing RLS policies + - Identify tables without any RLS policies (security risk) + - Find overly permissive policies (e.g., allowing all operations) + - Suggest missing policies based on common patterns + - Generate SQL to fix identified security issues + + Prioritize findings by risk level: + 1. Critical: Tables with sensitive data but no RLS + 2. High: Overly permissive policies + 3. Medium: Missing common policies (e.g., users can only see own data) + 4. Low: Policy optimization opportunities + ``` + + + + **Prompt:** + ``` + Based on the RLS audit, generate SQL migrations to fix all security issues: + + 1. Enable RLS on all tables that don't have it: + - Include ALTER TABLE statements + - Add comment explaining why RLS is needed + + 2. Create secure default policies for common patterns: + - Users can only read/update their own records + - Admins have full access (with role checking) + - Public read-only access where appropriate + - Proper INSERT policies for new records + + 3. Fix overly permissive policies: + - Replace 'true' conditions with proper checks + - Add user_id or role-based restrictions + - Include USING clauses for read operations + - Include WITH CHECK clauses for write operations + + 4. For each policy, include: + - Clear naming convention (e.g., 'users_select_own') + - Comments explaining the security model + - Rollback statements + + Generate the complete migration file with all fixes. + ``` + + + + + **Available Supabase MCP Capabilities**: + - **Database Queries**: Execute SQL queries and analyze results + - **Schema Inspection**: View table structures, relationships, and constraints + - **Performance Analysis**: Identify slow queries and optimization opportunities + - **Security Review**: Check RLS policies and access controls + - **Migration Generation**: Create SQL migrations for schema changes + + +## Step 3: Generate Database Migrations + +Create and apply database migrations based on AI recommendations. Enter this prompt in the Continue CLI TUI: + +**Example: Complete RLS Security Fix** + +``` +I need to secure my Supabase database. Please: + +1. First, audit all tables for RLS security issues +2. Generate a complete migration to fix all issues found +3. Create a security report I can share with my team + +Here's what I need fixed: +- Enable RLS on all tables +- Create policies so users can only access their own data +- Ensure admins (role = 'admin') have full access +- Add policies for service accounts (role = 'service') +- Include audit logging for sensitive operations + +For the users table specifically: +- Users can read their own profile +- Users can update their own profile (except role field) +- Only admins can view all users +- Only admins can delete users +- New users can insert their own record during signup + +Generate the complete migration with: +- All SQL statements +- Clear policy names and comments +- Rollback statements +- A summary of what each policy does +``` + +**Expected Output:** +The AI will generate a complete SQL migration file that: +- Enables RLS on all tables +- Creates secure, well-documented policies +- Follows Supabase security best practices +- Includes rollback capabilities +- Provides a security summary for your team + + + **Best Practice**: Always review AI-generated migrations before applying them. Test in a development branch first using Supabase's branching feature. + + +## Step 4: Set Up Automated Database Monitoring + +Automate database health checks with Continue CLI and GitHub Actions: + +```yaml +name: Database Health Monitor + +on: + schedule: + # Run daily at 2 AM UTC + - cron: "0 2 * * *" + workflow_dispatch: # Allow manual triggers + +jobs: + monitor-database: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "āœ… Continue CLI installed" + + - name: Analyze Database Security + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + echo "šŸ” Performing security audit..." + + # Use Continue CLI to audit RLS and generate fixes + cn -p "Using Supabase MCP, perform a comprehensive RLS security audit: + 1. Check all tables for RLS enablement + 2. Identify tables with missing or weak RLS policies + 3. Find overly permissive policies (e.g., 'true' conditions) + 4. Check for common security anti-patterns: + - Missing user_id checks + - No role-based access control + - Unrestricted DELETE operations + - Missing WITH CHECK clauses + 5. Generate fixes for all security issues found + 6. Create a security report with: + - Critical vulnerabilities (tables without RLS) + - High-risk policies that need immediate fixes + - SQL migrations to fix all issues + - Best practice recommendations + - Compliance checklist (GDPR, SOC2, etc.) + + If critical security issues are found: + - Generate the complete fix migration + - Create a GitHub issue with severity labels + - Tag security team members for review" + + - name: Save Health Report + run: | + echo "## šŸ“Š Database Health Report" >> $GITHUB_STEP_SUMMARY + echo "Generated at $(date)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Check the 'Analyze Database Security' step for the full report" >> $GITHUB_STEP_SUMMARY + + - name: Upload Health Report + uses: actions/upload-artifact@v4 + with: + name: database-health-report + path: | + *.md + *.sql +``` + + + **Required GitHub Secrets**: + - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + + Add this at: **Repository Settings → Secrets and variables → Actions** + + +## What You've Built + +After completing this guide, you have a complete **AI-powered database management system** that: + +- **Analyzes schema design** - Identifies optimization opportunities and best practices +- **Optimizes queries** - Suggests indexes and query rewrites for better performance +- **Generates migrations** - Creates SQL code for schema improvements +- **Monitors health** - Runs automated checks for performance and security issues +- **Provides insights** - Delivers actionable recommendations based on data patterns + + + Your system now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine database analysis and optimization with human oversight for migration approval. + + +## Advanced Database Prompts + +Enhance your workflow with these advanced Continue CLI prompts: + + + + Monitor query performance in real-time and get alerts for slow queries exceeding threshold times + + + Automatically validate data integrity, find duplicates, and ensure consistency across related tables + + + Analyze API logs to understand data access patterns and optimize indexes accordingly + + + Review database usage and suggest ways to reduce costs while maintaining performance + + + +## Security Best Practices + + + **Database Security Guidelines**: + - Always use development/staging environments with MCP + - Enable read-only mode for analysis tasks + - Never store production credentials in code + - Review all AI-generated SQL before execution + - Use RLS policies to enforce access control + - Regularly audit database permissions + + +## Troubleshooting + +### Supabase MCP Connection Issues + +If you encounter connection issues: + +1. Verify OAuth authentication is complete +2. Check your Supabase project is accessible +3. Ensure you're not connecting to a production database +4. Verify the MCP URL is correct: `https://mcp.supabase.com/mcp` + +### Common Database Analysis Issues + +| Issue | Solution | +|:------|:---------| +| No tables found | Verify your database has tables created | +| Permission denied | Check OAuth scopes and project permissions | +| Slow query analysis | Ensure your database has query logs enabled | +| Migration failures | Test migrations in a branch database first | + +## Next Steps + +- Set up [Supabase Edge Functions](https://supabase.com/docs/guides/functions) for automated workflows +- Configure [Supabase Realtime](https://supabase.com/docs/guides/realtime) for live data monitoring +- Implement [Database Webhooks](https://supabase.com/docs/guides/database/webhooks) for event-driven automation +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Supabase MCP Documentation](https://supabase.com/docs/guides/getting-started/mcp) +- [Supabase Database Guide](https://supabase.com/docs/guides/database) +- [Supabase Security Best Practices](https://supabase.com/docs/guides/database/security) +- [Model Context Protocol Docs](https://modelcontextprotocol.io/introduction) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) \ No newline at end of file diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 0aaa45506..4e2bc9fd3 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -7,7 +7,8 @@ description: "Comprehensive guide to resolving common issues with Continue, incl 2. [Try the latest pre-release](#download-the-latest-pre-release) 3. [Download an older version](#download-an-older-version) 4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving) -5. [Check FAQs for common issues](/faqs) +5. [MCP Server connection issues](#mcp-server-connection-issues) +6. [Check FAQs for common issues](/faqs) ## Check the logs @@ -79,6 +80,30 @@ If your keyboard shortcuts are not resolving, you may have other commands that a - [VSCode keyboard shortcuts docs](https://code.visualstudio.com/docs/getstarted/keybindings) - [IntelliJ keyboard shortcut docs](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html) +## MCP Server connection issues + +### "spawn ENAMETOOLONG" error on macOS + +If you're seeing an error like `Failed to connect to ""` with `Error: spawn ENAMETOOLONG` when using MCP servers on macOS, this is due to the environment being too large when spawning the MCP process. + +**Workaround:** Use the full path to the command instead of relying on PATH resolution: + +```yaml +mcpServers: + - name: Memory MCP server + command: /usr/local/bin/npx # Use full path instead of just "npx" + args: + - -y + - "@modelcontextprotocol/server-memory" +``` + +To find the full path to a command on your system: +- For `npx`: run `which npx` +- For `docker`: run `which docker` +- For `uv`/`uvx`: run `which uv` or `which uvx` + +This issue typically affects macOS users with large development environments and is being tracked in [#7870](https://github.com/continuedev/continue/issues/7870) and [#6699](https://github.com/continuedev/continue/issues/6699). + ## Still having trouble? diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 216595799..4b7a998a9 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -30,6 +30,7 @@ import { gracefulExit } from "../util/exit.js"; import { formatAnthropicError, formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; import { question } from "../util/prompt.js"; +import { prependPrompt } from "../util/promptProcessor.js"; import { calculateContextUsagePercentage, countChatHistoryTokens, @@ -481,9 +482,11 @@ async function runHeadlessMode( const agentFileState = await serviceContainer.get( SERVICE_NAMES.AGENT_FILE, ); - const initialPrompt = - `${agentFileState?.agentFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || - undefined; + + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + prompt, + ); const initialUserInput = await processAndCombinePrompts( options.prompt, initialPrompt, @@ -556,9 +559,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { SERVICE_NAMES.AGENT_FILE, ); - const initialPrompt = - `${agentFileState?.agentFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || - undefined; + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + prompt, + ); // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index bba7efa00..5f78155b2 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -4,6 +4,7 @@ import express, { Request, Response } from "express"; import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { posthogService } from "src/telemetry/posthogService.js"; +import { prependPrompt } from "src/util/promptProcessor.js"; import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; import { runEnvironmentInstallSafe } from "../environment/environmentHandler.js"; @@ -16,6 +17,7 @@ import { services, } from "../services/index.js"; import { + AgentFileServiceState, AuthServiceState, ConfigServiceState, ModelServiceState, @@ -73,11 +75,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); // Get initialized services from the service container - const [configState, modelState, permissionsState] = await Promise.all([ - getService(SERVICE_NAMES.CONFIG), - getService(SERVICE_NAMES.MODEL), - getService(SERVICE_NAMES.TOOL_PERMISSIONS), - ]); + const [configState, modelState, permissionsState, agentFileState] = + await Promise.all([ + getService(SERVICE_NAMES.CONFIG), + getService(SERVICE_NAMES.MODEL), + getService(SERVICE_NAMES.TOOL_PERMISSIONS), + getService(SERVICE_NAMES.AGENT_FILE), + ]); if (!configState.config || !modelState.llmApi || !modelState.model) { throw new Error("Failed to initialize required services"); @@ -389,9 +393,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { runEnvironmentInstallSafe(); // If initial prompt provided, queue it for processing - if (actualPrompt) { + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + actualPrompt, + ); + if (initialPrompt) { console.log(chalk.dim("\nProcessing initial prompt...")); - await messageQueue.enqueueMessage(actualPrompt); + await messageQueue.enqueueMessage(initialPrompt); processMessages(state, llmApi); } }); diff --git a/extensions/cli/src/e2e/headless-permission-error.test.ts b/extensions/cli/src/e2e/headless-permission-error.test.ts index 60a10d16f..baacb86b6 100644 --- a/extensions/cli/src/e2e/headless-permission-error.test.ts +++ b/extensions/cli/src/e2e/headless-permission-error.test.ts @@ -32,63 +32,6 @@ describe("E2E: Headless Mode Permission Errors", () => { } await cleanupTestContext(context); }); - it("should display error message with --auto suggestion when tool requires permission", async () => { - // Set up mock LLM to return a tool call that requires permission (Write tool) - mockServer = await setupMockLLMTest(context, { - customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { - let body = ""; - req.on("data", (chunk) => { - body += chunk.toString(); - }); - - req.on("end", () => { - if (req.method === "POST" && req.url === "/chat/completions") { - res.writeHead(200, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - Connection: "keep-alive", - }); - - // Send a Write tool call (requires permission by default) - res.write( - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, - ); - res.write( - `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, - ); - - // Send usage data - res.write( - `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, - ); - - // End the stream - res.write(`data: [DONE]\n\n`); - res.end(); - } else { - res.writeHead(404); - res.end("Not found"); - } - }); - }, - }); - - // Run CLI in headless mode without permission flags - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath, "Create a file test.txt"], - timeout: 15000, - }); - - // Expect non-zero exit code - expect(result.exitCode).toBe(1); - - // Verify the error message contains the expected information - expect(result.stderr).toContain("requires permission"); - expect(result.stderr).toContain("headless mode"); - expect(result.stderr).toContain("--auto"); - expect(result.stderr).toContain("--allow"); - expect(result.stderr).toContain("--exclude"); - }, 20000); it("should succeed with --auto flag when tool requires permission", async () => { // Set up mock LLM to return a Write tool call diff --git a/extensions/cli/src/onboarding.test.ts b/extensions/cli/src/onboarding.test.ts index 1dee85c8d..036d56097 100644 --- a/extensions/cli/src/onboarding.test.ts +++ b/extensions/cli/src/onboarding.test.ts @@ -108,11 +108,8 @@ name: "Incomplete Config" }); test("should handle empty string config path", async () => { - // Empty string should be treated differently from undefined - // Note: empty string triggers onboarding flow, but should still fail in our error format - await expect( - initializeWithOnboarding(mockAuthConfig, ""), - ).rejects.toThrow(); + // Loads default agent with no error + await initializeWithOnboarding(mockAuthConfig, ""); }); test("should not fall back to default config when explicit config fails", async () => { diff --git a/extensions/cli/src/permissions/README.md b/extensions/cli/src/permissions/README.md index 56846da52..3251b4ce5 100644 --- a/extensions/cli/src/permissions/README.md +++ b/extensions/cli/src/permissions/README.md @@ -47,7 +47,7 @@ Tools with "allow" permission are executed immediately without user intervention ### Data Flow -1. **Tool Loading**: `getAllTools()` in `streamChatResponse.ts` filters out excluded tools +1. **Tool Loading**: `getAllowedTools()` in `streamChatResponse.ts` filters out excluded tools 2. **Tool Execution**: Before executing each tool call, permissions are checked 3. **User Interaction**: For "ask" policies, UI displays permission request 4. **Execution**: Tool is executed or denied based on permission result @@ -82,11 +82,4 @@ const result = checkToolPermission({ if (result.permission === "ask") { // Request user permission } - -// Filter excluded tools -const allowedTools = filterExcludedTools([ - "readFile", - "dangerousTool", - "writeFile", -]); ``` diff --git a/extensions/cli/src/permissions/index.ts b/extensions/cli/src/permissions/index.ts index 7e5fca074..dbb352f90 100644 --- a/extensions/cli/src/permissions/index.ts +++ b/extensions/cli/src/permissions/index.ts @@ -9,7 +9,6 @@ export type { export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; export { checkToolPermission, - filterExcludedTools, matchesArguments, matchesToolPattern, } from "./permissionChecker.js"; diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts index 259dd06c5..e21b80f02 100644 --- a/extensions/cli/src/permissions/permissionChecker.test.ts +++ b/extensions/cli/src/permissions/permissionChecker.test.ts @@ -1,15 +1,35 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import * as toolsModule from "../tools/index.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; import { checkToolPermission, - filterExcludedTools, matchesArguments, matchesToolPattern, } from "./permissionChecker.js"; import { ToolPermissions } from "./types.js"; +// Create a mock function for evaluateToolCallPolicy +const mockEvaluateToolCallPolicy = vi.fn(); + +// Create a mock Bash tool +const mockBashTool = { + name: "Bash", + displayName: "Bash", + description: "Execute bash commands", + parameters: { + type: "object" as const, + properties: {}, + }, + isBuiltIn: true, + evaluateToolCallPolicy: mockEvaluateToolCallPolicy, + run: vi.fn(), +}; + +// Replace the array contents with our mock tool +ALL_BUILT_IN_TOOLS.length = 0; +ALL_BUILT_IN_TOOLS.push(mockBashTool as any); + describe("Permission Checker", () => { describe("matchesToolPattern", () => { it("should match exact tool names", () => { @@ -448,16 +468,6 @@ describe("Permission Checker", () => { expect(normalResult.permission).toBe("allow"); }); - it("should use default policies when no custom permissions provided", () => { - const result = checkToolPermission({ - name: "Read", - arguments: { path: "/test.txt" }, - }); - - // Should match the default policies (Read should be "allow") - expect(result.permission).toBe("allow"); - }); - it("should fall back to ask when no policy matches", () => { const permissions: ToolPermissions = { policies: [{ tool: "specificTool", permission: "allow" }], @@ -556,76 +566,10 @@ describe("Permission Checker", () => { }); }); - describe("filterExcludedTools", () => { - it("should filter out excluded tools", () => { - const permissions: ToolPermissions = { - policies: [ - { tool: "runTerminalCommand", permission: "exclude" }, - { tool: "writeFile", permission: "ask" }, - { tool: "*", permission: "allow" }, - ], - }; - - const tools = [ - "readFile", - "writeFile", - "runTerminalCommand", - "searchCode", - ]; - const filtered = filterExcludedTools(tools, permissions); - - expect(filtered).toEqual(["readFile", "writeFile", "searchCode"]); - expect(filtered).not.toContain("runTerminalCommand"); - }); - - it("should return all tools when none are excluded", () => { - const permissions: ToolPermissions = { - policies: [{ tool: "*", permission: "allow" }], - }; - - const tools = ["readFile", "writeFile", "runTerminalCommand"]; - const filtered = filterExcludedTools(tools, permissions); - - expect(filtered).toEqual(tools); - }); - - it("should use default policies when no permissions provided", () => { - const tools = ["readFile", "writeFile", "runTerminalCommand"]; - const filtered = filterExcludedTools(tools); - - // All tools should be included (none excluded by default) - expect(filtered).toEqual(tools); - }); - }); - describe("Hybrid Permission Model with Dynamic Evaluation", () => { - // Mock the runTerminalCommand tool with evaluateToolCallPolicy - const mockBashTool = { - name: "Bash", - displayName: "Bash", - description: "Execute bash commands", - parameters: { - type: "object" as const, - properties: {}, - }, - isBuiltIn: true, - evaluateToolCallPolicy: vi.fn(), - run: vi.fn(), - }; - beforeEach(() => { - vi.clearAllMocks(); - // Mock getAllBuiltinTools to return our test tool - vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([ - mockBashTool, - ]); - // Reset mock between tests - mockBashTool.evaluateToolCallPolicy.mockClear(); - }); - - afterEach(() => { - vi.restoreAllMocks(); + mockEvaluateToolCallPolicy.mockClear(); }); describe("User has Bash in 'allow' mode", () => { @@ -637,9 +581,7 @@ describe("Permission Checker", () => { }; it("should allow safe commands (echo hello)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -647,16 +589,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); // User preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "echo hello" }, ); }); it("should allow risky commands based on user preference (curl)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "curl https://example.com" } }, @@ -664,14 +604,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); // User preference wins over "ask" - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "curl https://example.com" }, ); }); it("should block dangerous commands despite user preference (eval)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "eval 'echo safe'" } }, @@ -679,14 +619,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // Security wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "eval 'echo safe'" }, ); }); it("should block sudo commands despite user preference", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "sudo rm -rf /" } }, @@ -706,9 +646,7 @@ describe("Permission Checker", () => { }; it("should ask for safe commands based on user preference (echo)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -716,16 +654,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // User preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "echo hello" }, ); }); it("should ask for risky commands (curl)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "curl https://example.com" } }, @@ -733,14 +669,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // Both agree on "ask" - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "curl https://example.com" }, ); }); it("should block dangerous commands (eval)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "eval 'echo safe'" } }, @@ -748,14 +684,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // Security wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "eval 'echo safe'" }, ); }); it("should block rm -rf commands", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "rm -rf /tmp/important" } }, @@ -773,9 +709,7 @@ describe("Permission Checker", () => { it("should always exclude regardless of dynamic evaluation", () => { // Even if dynamic evaluation would allow it - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -783,7 +717,7 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // User excluded the tool entirely - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "disabled", // converted from "exclude" { command: "echo hello" }, ); @@ -866,7 +800,7 @@ describe("Permission Checker", () => { testCases.forEach(({ command, dynamicResult, expected }) => { it(`should handle '${command}' correctly`, () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult); + mockEvaluateToolCallPolicy.mockReturnValue(dynamicResult); const result = checkToolPermission( { name: "Bash", arguments: { command } }, @@ -880,24 +814,6 @@ describe("Permission Checker", () => { describe("Edge cases", () => { it("should handle tools without dynamic evaluation", () => { - // Mock a Read tool without evaluateToolCallPolicy - const mockReadTool = { - name: "Read", - displayName: "Read", - description: "Read files", - parameters: { - type: "object" as const, - properties: {}, - }, - isBuiltIn: true, - run: vi.fn(), - // No evaluateToolCallPolicy - }; - vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([ - mockReadTool, - mockBashTool, - ]); - const permissions: ToolPermissions = { policies: [{ tool: "Read", permission: "allow" }], }; @@ -908,7 +824,7 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); - expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled(); + expect(mockEvaluateToolCallPolicy).not.toHaveBeenCalled(); }); it("should use default 'ask' when no policy matches", () => { @@ -916,9 +832,7 @@ describe("Permission Checker", () => { policies: [], }; - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo test" } }, @@ -926,16 +840,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // Default fallback, user preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from default "ask" { command: "echo test" }, ); }); it("should handle null/undefined arguments gracefully", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const permissions: ToolPermissions = { policies: [{ tool: "Bash", permission: "allow" }], @@ -947,16 +859,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", {}, ); }); it("should maintain matched policy information", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const policy = { tool: "Bash", permission: "allow" as const }; const permissions: ToolPermissions = { diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 738de9a56..093137d30 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,12 +1,7 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; -import { getServiceSync } from "../services/index.js"; -import { SERVICE_NAMES } from "../services/types.js"; -import { getAllBuiltinTools } from "../tools/index.js"; - -import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, PermissionPolicy, @@ -132,25 +127,9 @@ function permissionPolicyToToolPolicy( */ export function checkToolPermission( toolCall: ToolCallRequest, - permissions?: ToolPermissions, + permissions: ToolPermissions, ): PermissionCheckResult { - // Get permissions from service if not provided - let policies = permissions?.policies; - - if (!policies) { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - - // Only use defaults if service is not ready, not registered, or has no value - // This allows critical runtime errors to propagate properly - if (serviceResult.state !== "ready" || !serviceResult.value) { - policies = DEFAULT_TOOL_POLICIES; - } else { - policies = - serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES; - } - } + const policies = permissions.policies; // First, get the base permission from static policies let basePermission: PermissionPolicy = "ask"; @@ -168,9 +147,7 @@ export function checkToolPermission( } // Check if tool has dynamic policy evaluation - const builtinTools = getAllBuiltinTools(); - const tool = builtinTools.find((t) => t.name === toolCall.name); - + const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolCall.name); if (tool?.evaluateToolCallPolicy) { // Convert CLI permission to core policy const basePolicy = permissionPolicyToToolPolicy(basePermission); @@ -202,19 +179,3 @@ export function checkToolPermission( matchedPolicy, }; } - -/** - * Filters out tools that have "exclude" permission from a list of tool names. - */ -export function filterExcludedTools( - toolNames: string[], - permissions?: ToolPermissions, -): string[] { - return toolNames.filter((toolName) => { - const result = checkToolPermission( - { name: toolName, arguments: {} }, - permissions, - ); - return result.permission !== "exclude"; - }); -} diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 08190e267..15e30e50c 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -52,7 +52,7 @@ export class MCPService private isShuttingDown = false; getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG]; + return [SERVICE_NAMES.CONFIG]; } constructor() { super("MCPService", { diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index fb22f5a07..3b0af61d8 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,4 +1,4 @@ -import { parseAgentFileTools } from "@continuedev/config-yaml"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; @@ -11,7 +11,11 @@ import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { AgentFileServiceState, SERVICE_NAMES } from "./types.js"; +import { + AgentFileServiceState, + MCPServiceState, + SERVICE_NAMES, +} from "./types.js"; export interface InitializeToolServiceOverrides { allow?: string[]; @@ -61,55 +65,94 @@ export class ToolPermissionService * Declare dependencies on other services */ getDependencies(): string[] { - return [SERVICE_NAMES.AGENT_FILE]; + return [SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP]; } /** * Generate agent-file-specific policies if an agent file is active */ - private generateAgentFilePolicies( + generateAgentFilePolicies( agentFileServiceState?: AgentFileServiceState, + mcpServiceState?: MCPServiceState, ): undefined | ToolPermissionPolicy[] { - if (!agentFileServiceState?.agentFile?.tools) { + const parsedTools = agentFileServiceState?.parsedTools; + if (!parsedTools?.tools.length) { return undefined; } - const parsedTools = parseAgentFileTools( - agentFileServiceState.agentFile.tools, - ); - if (parsedTools.tools.length === 0) { - return undefined; - } const policies: ToolPermissionPolicy[] = []; + const servers = Array.from(mcpServiceState?.connections?.values() ?? []); + for (const mcpServer of parsedTools.mcpServers) { + const server = servers?.find( + (s) => s.config?.sourceSlug && s.config.sourceSlug === mcpServer, + ); + if (!server) { + logger.warn("No connected MCP server found "); + continue; + } - for (const toolRef of parsedTools.tools) { - if (toolRef.mcpServer) { - if (toolRef.toolName) { - policies.push({ - tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`, - permission: "allow", - }); - } else { - policies.push({ - tool: `mcp:${toolRef.mcpServer}:*`, - permission: "allow", - }); - } - } else if (toolRef.toolName) { - policies.push({ tool: toolRef.toolName, permission: "allow" }); + const specificTools = parsedTools.tools.filter( + (t) => t.mcpServer && t.toolName && t.mcpServer === mcpServer, + ); + + // In the `tools` key of an agent is comma separated strings like + // mcp/server, mcp/server2:tool_name, Bash + // - this would give the agent access to ALL tools from mcp/server, ONLY tool_name from mcp/server2, and Bash, and no other tools + // mcp/server + // - this would give the agent access to ALL tools from mcp/server, and no built-ins + // built_in, mcp/server + // - "built_in" keyword can be used to include all built ins + // Blank = all built-in tools + + // Handle MCP first + // If ANY mcp tools are specifically called out, only allow those ones for that mcp server + // Otherwise the blanket allow will cover all MCP tools + if (specificTools.length) { + const specificSet = new Set(specificTools.map((t) => t.toolName)); + const notMentioned = server.tools.filter( + (t) => !specificSet.has(t.name), + ); + const allowed: ToolPermissionPolicy[] = specificTools.map((t) => ({ + tool: t.toolName!, + permission: "allow", + })); + policies.push(...allowed); + const disallowed: ToolPermissionPolicy[] = notMentioned.map((t) => ({ + tool: t.name, + permission: "exclude", + })); + policies.push(...disallowed); } } - if (policies.length > 0) { - logger.debug(`Generated ${policies.length} agent file tool policies`); + // If mcp servers or specific built-in tools are specified + // then we only inclue listed built-in tools and exclude all others + const hasMcp = !!parsedTools.mcpServers?.length; + const specificBuiltIns = parsedTools.tools + .filter((t) => !t.mcpServer) + .map((t) => t.toolName!); + if (specificBuiltIns.length || (hasMcp && !parsedTools.allBuiltIn)) { + const allowed: ToolPermissionPolicy[] = specificBuiltIns.map((tool) => ({ + tool, + permission: "allow", + })); + policies.push(...allowed); + const specificBuiltInSet = new Set(specificBuiltIns); + const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter( + (name) => !specificBuiltInSet.has(name), + ); + const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({ + tool, + permission: "exclude", + })); + policies.push(...disallowed); } - if (parsedTools.allBuiltIn) { - policies.push({ tool: "*", permission: "allow" }); - policies.push({ tool: "mcp:*", permission: "exclude" }); - } else { - policies.push({ tool: "*", permission: "exclude" }); - } + // Allow all other tools + policies.push({ + tool: "*", + permission: "allow", + }); return policies; } @@ -165,6 +208,7 @@ export class ToolPermissionService initializeSync( runtimeOverrides?: InitializeToolServiceOverrides, agentFileServiceState?: AgentFileServiceState, + mcpServiceState?: MCPServiceState, ): ToolPermissionServiceState { logger.debug("Synchronously initializing ToolPermissionService"); @@ -180,6 +224,7 @@ export class ToolPermissionService const agentFilePolicies = this.generateAgentFilePolicies( agentFileServiceState, + mcpServiceState, ); const modePolicies = this.generateModePolicies(); @@ -224,11 +269,16 @@ export class ToolPermissionService async doInitialize( runtimeOverrides?: InitializeToolServiceOverrides, agentFileServiceState?: AgentFileServiceState, + mcpServiceState?: MCPServiceState, ): Promise { await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides, agentFileServiceState); + return this.initializeSync( + runtimeOverrides, + agentFileServiceState, + mcpServiceState, + ); } /** diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 7450476a6..3e80fdf67 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,71 +1,10 @@ -import { Configuration, DefaultApi } from "@continuedev/sdk/dist/api"; import { vi } from "vitest"; +import { MCPService } from "./MCPService.js"; + import { initializeServices, services } from "./index.js"; -// Mock the onboarding module -vi.mock("../onboarding.js", () => ({ - initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }), - createOrUpdateConfig: vi.fn().mockResolvedValue(undefined), -})); - -// Mock auth module -vi.mock("../auth/workos.js", () => ({ - loadAuthConfig: vi.fn().mockReturnValue({}), - getConfigUri: vi.fn().mockReturnValue(null), -})); - -// Mock the config loader -vi.mock("../configLoader.js", () => ({ - loadConfiguration: vi.fn().mockResolvedValue({ - config: { name: "test", version: "1.0.0" }, - source: { type: "test" }, - }), -})); - describe("initializeServices", () => { - // let mockToolPermissionsService: any; - - beforeEach(() => { - // Reset all mocks - vi.clearAllMocks(); - - // Mock service methods to avoid actual initialization - vi.spyOn(services.auth, "initialize").mockResolvedValue({ - authConfig: { - accessToken: "", - expiresAt: 123, - organizationId: "", - refreshToken: "", - userEmail: "", - }, - isAuthenticated: false, - }); - vi.spyOn(services.apiClient, "initialize").mockResolvedValue({ - apiClient: new DefaultApi( - new Configuration({ - basePath: "", - accessToken: "", - }), - ), - }); - vi.spyOn(services.agentFile, "initialize").mockResolvedValue({ - slug: null, - agentFile: null, - agentFileModel: null, - parsedRules: null, - parsedTools: null, - }); - vi.spyOn(services.config, "initialize").mockResolvedValue({ - config: { name: "test", version: "1.0.0" }, - configPath: undefined, - }); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - describe("mode conversion", () => { it("should pass only auto flag for auto mode", async () => { const spy = vi.spyOn(services.toolPermissions, "initialize"); @@ -94,6 +33,12 @@ describe("initializeServices", () => { parsedRules: null, parsedTools: null, }, + { + connections: [], + mcpService: expect.any(MCPService), + prompts: [], + tools: [], + }, ); }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index bb3a50df6..0f5a1face 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -113,9 +113,10 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, async () => { - const agentFileState = await serviceContainer.get( - SERVICE_NAMES.AGENT_FILE, - ); + const [mcpState, agentFileState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.MCP), + serviceContainer.get(SERVICE_NAMES.AGENT_FILE), + ]); // Initialize mode service with tool permission overrides if (initOptions.toolPermissionOverrides) { @@ -128,13 +129,16 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { exclude: overrides.exclude, isHeadless: initOptions.headless, }; - // Only set the boolean flag that corresponds to the mode if (overrides.mode) { initArgs.mode = overrides.mode; } // If mode is "normal" or undefined, no flags are set - return await toolPermissionService.initialize(initArgs, agentFileState); + return await toolPermissionService.initialize( + initArgs, + agentFileState, + mcpState, + ); } else { // Even if no overrides, we need to initialize with defaults return await toolPermissionService.initialize( @@ -142,10 +146,11 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { isHeadless: initOptions.headless, }, agentFileState, + mcpState, ); } }, - [SERVICE_NAMES.AGENT_FILE], + [SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP], ); // Initialize SystemMessageService with command options @@ -257,7 +262,10 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { if (!configState.config) { throw new Error("Config not available for MCP service"); } - return mcpService.initialize(configState.config, initOptions.headless); + return mcpService.initialize( + configState.config, + initOptions.headless || initOptions.options?.agent, + ); }, [SERVICE_NAMES.CONFIG], // Depends on config ); diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index 8cf3352d7..4e4ec89d8 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -1,18 +1,21 @@ import type { ChatHistoryItem, ToolStatus } from "core/index.js"; import { stripImages } from "core/util/messageContent.js"; import { createHistoryItem } from "core/util/messageConversion.js"; -import type { ChatCompletionTool } from "openai/resources.mjs"; -import { filterExcludedTools } from "../permissions/index.js"; +import { checkToolPermission } from "src/permissions/permissionChecker.js"; + import { - getServiceSync, - MCPServiceState, - MCPTool, SERVICE_NAMES, + serviceContainer, services, } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; +import { + convertToolToChatCompletionTool, + getAllAvailableTools, + Tool, + ToolCall, +} from "../tools/index.js"; import { logger } from "../util/logger.js"; import { @@ -91,7 +94,7 @@ export async function handleToolCalls( // First preprocess the tool calls const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(isHeadless, toolCalls, callbacks); // Add any preprocessing errors to chat history // Convert error entries from OpenAI format to ChatHistoryItem format @@ -175,85 +178,28 @@ export async function handleToolCalls( return false; } -export async function getAllTools() { - // Get all available tool names - const allBuiltinTools = getAllBuiltinTools(); - const builtinToolNames = allBuiltinTools.map((tool) => tool.name); +export async function getRequestTools(isHeadless: boolean) { + const availableTools = await getAllAvailableTools(isHeadless); - let mcpTools: MCPTool[] = []; - let mcpToolNames: string[] = []; - const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP); - if (mcpServiceResult.state === "ready") { - mcpTools = mcpServiceResult?.value?.tools ?? []; - mcpToolNames = mcpTools.map((t) => t.name); - } else { - // MCP is lazy - // throw new Error("MCP Service not initialized"); + const permissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const allowedTools: Tool[] = []; + for (const tool of availableTools) { + const result = checkToolPermission( + { name: tool.name, arguments: {} }, + permissionsState.permissions, + ); + + if ( + result.permission === "allow" || + (result.permission === "ask" && !isHeadless) + ) { + allowedTools.push(tool); + } } - const allToolNames = [...builtinToolNames, ...mcpToolNames]; - - // Check if the ToolPermissionService is ready - const permissionsServiceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - - let allowedToolNames: string[]; - if ( - permissionsServiceResult.state === "ready" && - permissionsServiceResult.value - ) { - // Filter out excluded tools based on permissions - allowedToolNames = filterExcludedTools( - allToolNames, - permissionsServiceResult.value.permissions, - ); - } else { - // Service not ready - this is a critical error since tools should only be - // requested after services are properly initialized - logger.error( - "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", - ); - throw new Error( - "ToolPermissionService not initialized. Services must be initialized before requesting tools.", - ); - } - - const allowedToolNamesSet = new Set(allowedToolNames); - - // Filter builtin tools - const allowedBuiltinTools = allBuiltinTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: { - type: "object", - required: tool.parameters.required, - properties: tool.parameters.properties, - }, - }, - })); - - // Add filtered MCP tools - const allowedMcpTools = mcpTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - allTools.push( - ...allowedMcpTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: tool.inputSchema, - }, - })), - ); - - return allTools; + return allowedTools.map(convertToolToChatCompletionTool); } diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 24b83ee04..800ae9aa9 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -8,9 +8,9 @@ import { } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import { getAllTools } from "./streamChatResponse.js"; +import { getRequestTools } from "./handleToolCalls.js"; -describe("getAllTools - Tool Filtering", () => { +describe("getRequestTools - Tool Filtering", () => { beforeEach(() => { // Clean up service container state before each test Object.values(SERVICE_NAMES).forEach((service) => { @@ -24,7 +24,7 @@ describe("getAllTools - Tool Filtering", () => { test("should exclude Bash tool in plan mode after service initialization", async () => { // Initialize services in plan mode (simulating `cn -p`) await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "plan", }, @@ -38,7 +38,7 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("plan"); // Get available tools - this should include Bash in plan mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Bash should be allowed in plan mode @@ -59,7 +59,7 @@ describe("getAllTools - Tool Filtering", () => { test("should include Bash tool in normal mode", async () => { // Initialize services in normal mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", }, @@ -73,7 +73,7 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("normal"); // Get available tools - Bash should be available in normal mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // All tools should be available in normal mode @@ -86,7 +86,7 @@ describe("getAllTools - Tool Filtering", () => { test("should include all tools in auto mode", async () => { // Initialize services in auto mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "auto", }, @@ -100,7 +100,7 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("auto"); // Get available tools - all tools should be available in auto mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // All tools should be available in auto mode @@ -113,14 +113,14 @@ describe("getAllTools - Tool Filtering", () => { test("should respect explicit exclude in normal mode", async () => { // Initialize services in normal mode with Read tool explicitly excluded await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", exclude: ["Read"], }, }); - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Read should be excluded due to explicit exclude @@ -137,14 +137,14 @@ describe("getAllTools - Tool Filtering", () => { // This test specifically addresses the original issue where plan mode // wasn't properly excluding tools despite being in plan mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "plan", allow: ["Write", "Edit"], // These should be ignored in plan mode }, }); - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Plan mode should still exclude write tools despite --allow flags diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.test.ts b/extensions/cli/src/stream/streamChatResponse.helpers.test.ts deleted file mode 100644 index 4b13eec25..000000000 --- a/extensions/cli/src/stream/streamChatResponse.helpers.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import type { PreprocessedToolCall } from "../tools/types.js"; - -import { handleHeadlessPermission } from "./streamChatResponse.helpers.js"; - -describe("streamChatResponse.helpers", () => { - describe("handleHeadlessPermission", () => { - it("should display error message and exit when tool requires permission in headless mode", async () => { - // Mock the tool call - const toolCall: PreprocessedToolCall = { - id: "call_123", - name: "Write", - arguments: { filepath: "test.txt", content: "hello" }, - argumentsStr: '{"filepath":"test.txt","content":"hello"}', - startNotified: false, - tool: { - name: "Write", - displayName: "Write", - description: "Write to a file", - parameters: { - type: "object", - properties: {}, - }, - run: vi.fn(), - isBuiltIn: true, - }, - }; - - // Mock safeStderr to capture output - const stderrOutputs: string[] = []; - vi.doMock("../init.js", () => ({ - safeStderr: (message: string) => { - stderrOutputs.push(message); - }, - })); - - // Mock gracefulExit to prevent actual process exit - let exitCode: number | undefined; - vi.doMock("../util/exit.js", () => ({ - gracefulExit: async (code: number) => { - exitCode = code; - }, - })); - - // Call the function (it should exit gracefully) - try { - await handleHeadlessPermission(toolCall); - } catch (error) { - // Expected to throw after exit - } - - // Verify error message was displayed - const fullOutput = stderrOutputs.join(""); - expect(fullOutput).toContain("requires permission"); - expect(fullOutput).toContain("headless mode"); - expect(fullOutput).toContain("--auto"); - expect(fullOutput).toContain("--allow"); - expect(fullOutput).toContain("--exclude"); - expect(fullOutput).toContain("Write"); - - // Verify it tried to exit with code 1 - expect(exitCode).toBe(1); - }); - }); -}); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 74f4b8b8f..6121e3426 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -3,17 +3,22 @@ import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + import { checkToolPermission } from "../permissions/permissionChecker.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; -import { ToolCallRequest } from "../permissions/types.js"; -import { services } from "../services/index.js"; +import { ToolCallRequest, ToolPermissions } from "../permissions/types.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { calculateTokenCost } from "../telemetry/utils.js"; import { executeToolCall, - getAllBuiltinTools, - getAvailableTools, + getAllAvailableTools, Tool, validateToolCallArgsPresent, } from "../tools/index.js"; @@ -50,34 +55,6 @@ export function handlePermissionDenied( logger.debug(`Tool call rejected (${reason}) - stopping stream`); } -// Helper function to handle headless mode permission -export async function handleHeadlessPermission( - toolCall: PreprocessedToolCall, -): Promise { - const allBuiltinTools = getAllBuiltinTools(); - const tool = allBuiltinTools.find((t) => t.name === toolCall.name); - const toolName = tool?.displayName || toolCall.name; - - // Import safeStderr to bypass console blocking in headless mode - const { safeStderr } = await import("../init.js"); - safeStderr( - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.\n`, - ); - safeStderr( - `If you want to allow all tools without asking, use cn -p --auto "your prompt".\n`, - ); - safeStderr(`If you want to allow this tool, use --allow ${toolName}.\n`); - safeStderr( - `If you don't want the tool to be included, use --exclude ${toolName}.\n`, - ); - - // Use graceful exit to flush telemetry even in headless denial - const { gracefulExit } = await import("../util/exit.js"); - await gracefulExit(1); - // This line will never be reached, but TypeScript needs it for the 'never' return type - throw new Error("Exiting due to headless permission requirement"); -} - // Helper function to request user permission export async function requestUserPermission( toolCall: PreprocessedToolCall, @@ -128,17 +105,19 @@ export async function requestUserPermission( // Helper function to check if tool permission is needed export async function checkToolPermissionApproval( + permissions: ToolPermissions, toolCall: PreprocessedToolCall, callbacks?: StreamCallbacks, isHeadless?: boolean, ): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> { - const permissionCheck = checkToolPermission(toolCall); + const permissionCheck = checkToolPermission(toolCall, permissions); if (permissionCheck.permission === "allow") { return { approved: true }; } else if (permissionCheck.permission === "ask") { if (isHeadless) { - await handleHeadlessPermission(toolCall); + // "ask" tools are excluded in headless so can only get here by policy evaluation + return { approved: false, denialReason: "policy" }; } const userApproved = await requestUserPermission(toolCall, callbacks); return userApproved @@ -318,6 +297,7 @@ export function recordStreamTelemetry(options: { * @returns - Preprocessed tool calls that are ready for execution */ export async function preprocessStreamedToolCalls( + isHeadless: boolean, toolCalls: ToolCall[], callbacks?: StreamCallbacks, ): Promise<{ @@ -328,12 +308,12 @@ export async function preprocessStreamedToolCalls( const errorChatEntries: ChatCompletionToolMessageParam[] = []; // Get all available tools - const availableTools: Tool[] = await getAvailableTools(); // Process each tool call for (const toolCall of toolCalls) { const startTime = Date.now(); try { + const availableTools: Tool[] = await getAllAvailableTools(isHeadless); const tool = availableTools.find((t) => t.name === toolCall.name); if (!tool) { throw new Error(`Tool ${toolCall.name} not found`); @@ -447,7 +427,12 @@ export async function executeStreamedToolCalls( callbacks?.onToolStart?.(call.name, call.arguments); // Check tool permissions using helper + const permissionState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); const permissionResult = await checkToolPermissionApproval( + permissionState.permissions, call, callbacks, isHeadless, diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index 6f97f9872..37b958c7f 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -7,7 +7,7 @@ import { services, } from "../services/index.js"; -import { getAllTools } from "./handleToolCalls.js"; +import { getRequestTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { const toolPermissionService = services.toolPermissions; @@ -21,7 +21,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Initialize services in normal mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", }, @@ -30,7 +30,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { test("should recompute tools on each iteration to handle mode switches", async () => { // Start in normal mode - let tools = await getAllTools(); + let tools = await getRequestTools(false); let toolNames = tools.map((t) => t.function.name); // Should include write tools in normal mode @@ -45,7 +45,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Recompute tools - should now exclude write tools - tools = await getAllTools(); + tools = await getRequestTools(true); toolNames = tools.map((t) => t.function.name); // Should exclude write tools in plan mode @@ -58,10 +58,10 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { expect(toolNames).toContain("List"); }); - test("getAllTools reflects current mode immediately", async () => { + test("getRequestTools reflects current mode immediately", async () => { // Start in normal mode expect(toolPermissionService.getCurrentMode()).toBe("normal"); - let tools = await getAllTools(); + let tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).toContain("Write"); // Switch to plan mode @@ -70,8 +70,8 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); expect(toolPermissionService.getCurrentMode()).toBe("plan"); - // getAllTools should immediately reflect the new mode - tools = await getAllTools(); + // getRequestTools should immediately reflect the new mode + tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).not.toContain("Write"); // Switch to auto mode @@ -80,8 +80,8 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); expect(toolPermissionService.getCurrentMode()).toBe("auto"); - // getAllTools should immediately reflect auto mode (all tools allowed) - tools = await getAllTools(); + // getRequestTools should immediately reflect auto mode (all tools allowed) + tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).toContain("Write"); expect(tools.map((t) => t.function.name)).toContain("MultiEdit"); expect(tools.map((t) => t.function.name)).toContain("Read"); @@ -151,7 +151,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { const abortController = new AbortController(); // Start in normal mode - tools should include Write - const initialTools = await getAllTools(); + const initialTools = await getRequestTools(false); expect(initialTools.map((t) => t.function.name)).toContain("Write"); // During streaming, if mode switches, subsequent iterations should use new tools diff --git a/extensions/cli/src/stream/streamChatResponse.test.ts b/extensions/cli/src/stream/streamChatResponse.test.ts index 05fd1a6cf..ccff36d0f 100644 --- a/extensions/cli/src/stream/streamChatResponse.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.test.ts @@ -423,7 +423,7 @@ describe.skip("preprocessStreamedToolCalls", () => { }; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(true, toolCalls, callbacks); // Should have one preprocessed call and no errors expect(preprocessedCalls).toHaveLength(1); @@ -462,7 +462,7 @@ describe.skip("preprocessStreamedToolCalls", () => { }; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(true, toolCalls, callbacks); // Should have no preprocessed calls and one error expect(preprocessedCalls).toHaveLength(0); @@ -489,7 +489,7 @@ describe.skip("preprocessStreamedToolCalls", () => { ]; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls); + await preprocessStreamedToolCalls(true, toolCalls); // Should have no preprocessed calls and one error expect(preprocessedCalls).toHaveLength(0); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 1b74e8210..af4355070 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -20,7 +20,7 @@ import { import { logger } from "../util/logger.js"; import { validateContextLength } from "../util/tokenizer.js"; -import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; +import { getRequestTools, handleToolCalls } from "./handleToolCalls.js"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { processChunkContent, @@ -381,7 +381,7 @@ export async function streamChatResponse( } // Recompute tools on each iteration to handle mode changes during streaming - const tools = await getAllTools(); + const tools = await getRequestTools(isHeadless); logger.debug("Tools prepared", { toolCount: tools.length, @@ -473,4 +473,3 @@ export async function streamChatResponse( // Otherwise, return the full response return isHeadless ? finalResponse : fullResponse; } -export { getAllTools }; diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts new file mode 100644 index 000000000..c239c37fc --- /dev/null +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -0,0 +1,26 @@ +import { editTool } from "./edit.js"; +import { exitTool } from "./exit.js"; +import { fetchTool } from "./fetch.js"; +import { listFilesTool } from "./listFiles.js"; +import { multiEditTool } from "./multiEdit.js"; +import { readFileTool } from "./readFile.js"; +import { runTerminalCommandTool } from "./runTerminalCommand.js"; +import { searchCodeTool } from "./searchCode.js"; +import { statusTool } from "./status.js"; +import { writeChecklistTool } from "./writeChecklist.js"; +import { writeFileTool } from "./writeFile.js"; + +// putting in here for circular import issue +export const ALL_BUILT_IN_TOOLS = [ + readFileTool, + editTool, + multiEditTool, + writeFileTool, + listFilesTool, + searchCodeTool, + runTerminalCommandTool, + fetchTool, + writeChecklistTool, + exitTool, + statusTool, +]; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index c185fa57b..21da49321 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -1,20 +1,24 @@ // @ts-ignore import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; +import { ChatCompletionTool } from "openai/resources.mjs"; import { posthogService } from "src/telemetry/posthogService.js"; +import { isModelCapable } from "src/utils/modelCapability.js"; import { - getServiceSync, - MCPServiceState, SERVICE_NAMES, serviceContainer, services, } from "../services/index.js"; -import type { ModelServiceState } from "../services/types.js"; +import type { + MCPServiceState, + MCPTool, + ModelServiceState, +} from "../services/types.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; -import { isModelCapable } from "../utils/index.js"; +import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; @@ -39,10 +43,7 @@ export type { Tool, ToolCall, ToolParametersSchema }; // Base tools that are always available const BASE_BUILTIN_TOOLS: Tool[] = [ readFileTool, - editTool, - multiEditTool, writeFileTool, - // searchAndReplaceInFileTool, listFilesTool, searchCodeTool, runTerminalCommandTool, @@ -50,78 +51,57 @@ const BASE_BUILTIN_TOOLS: Tool[] = [ writeChecklistTool, ]; -// Export BUILTIN_TOOLS as the base set of tools -// Dynamic tools (like exit tool in headless mode) are added separately -export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; - -// Get dynamic tools based on current state -function getDynamicTools(): Tool[] { - const dynamicTools: Tool[] = []; - - if (services.toolPermissions.isHeadless()) { - dynamicTools.push(exitTool); - } - - // Add beta status tool if --beta-status-tool flag is present - if (process.argv.includes("--beta-status-tool")) { - dynamicTools.push(statusTool); - } - - return dynamicTools; -} - -// Check if the current model is capable and should exclude Edit tool -function shouldExcludeEditTool(): boolean { - try { - const modelServiceResult = getServiceSync( - SERVICE_NAMES.MODEL, - ); - - if ( - modelServiceResult.state === "ready" && - modelServiceResult.value?.model - ) { - const { name, provider, model } = modelServiceResult.value.model; - - // Check if model is capable - const isCapable = isModelCapable(provider, name, model); - - logger.debug("Capability-based tool filtering", { - provider, - name, - isCapable, - willExcludeEdit: isCapable, - }); - - return isCapable; - } - } catch (error) { - logger.debug("Error checking model capability for tool filtering", { - error, - }); - } - return false; -} - // Get all builtin tools including dynamic ones, with capability-based filtering -export function getAllBuiltinTools(): Tool[] { - let builtinTools = [...BUILTIN_TOOLS]; +export async function getAllAvailableTools( + isHeadless: boolean, +): Promise { + const tools = [...BASE_BUILTIN_TOOLS]; - // Apply capability-based filtering for edit tools // If model is capable, exclude editTool in favor of multiEditTool - if (shouldExcludeEditTool()) { - builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name); + const modelState = await serviceContainer.get( + SERVICE_NAMES.MODEL, + ); + if (!modelState.model) { + throw new Error("Model service is not initialized"); + } + + const { provider, name, model } = modelState.model; + + const isCapable = isModelCapable(provider, name, model); + if (isCapable) { + tools.push(multiEditTool); + } else { + tools.push(editTool); logger.debug( "Excluded Edit tool for capable model - MultiEdit will be used instead", ); } - return [...builtinTools, ...getDynamicTools()]; + logger.debug("Capability-based tool filtering", { + provider, + name, + isCapable, + }); + + if (isHeadless) { + tools.push(exitTool); + } + + // Add beta status tool if --beta-status-tool flag is present + if (process.argv.includes("--beta-status-tool")) { + tools.push(statusTool); + } + + const mcpState = await serviceContainer.get( + SERVICE_NAMES.MCP, + ); + tools.push(...mcpState.tools.map(convertMcpToolToContinueTool)); + + return tools; } export function getToolDisplayName(toolName: string): string { - const allTools = getAllBuiltinTools(); - const tool = allTools.find((t) => t.name === toolName); + const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolName); return tool?.displayName || toolName; } @@ -150,35 +130,43 @@ export function extractToolCalls( return toolCalls; } -export async function getAvailableTools() { - // Load MCP tools - const mcpState = await serviceContainer.get( - SERVICE_NAMES.MCP, - ); - const tools = mcpState.tools ?? []; - const mcpTools: Tool[] = - tools.map((t) => ({ - name: t.name, - displayName: t.name.replace("mcp__", "").replace("ide__", ""), - description: t.description ?? "", +export function convertToolToChatCompletionTool( + tool: Tool, +): ChatCompletionTool { + return { + type: "function" as const, + function: { + name: tool.name, + description: tool.description, parameters: { type: "object", - properties: (t.inputSchema.properties ?? {}) as Record< - string, - ParameterSchema - >, - required: t.inputSchema.required, + required: tool.parameters.required, + properties: tool.parameters.properties, }, - readonly: undefined, // MCP tools don't have readonly property - isBuiltIn: false, - run: async (args: any) => { - const result = await mcpState.mcpService?.runTool(t.name, args); - return JSON.stringify(result?.content) ?? ""; - }, - })) || []; + }, + }; +} - const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; - return allTools; +export function convertMcpToolToContinueTool(mcpTool: MCPTool): Tool { + return { + name: mcpTool.name, + displayName: mcpTool.name.replace("mcp__", "").replace("ide__", ""), + description: mcpTool.description ?? "", + parameters: { + type: "object", + properties: (mcpTool.inputSchema.properties ?? {}) as Record< + string, + ParameterSchema + >, + required: mcpTool.inputSchema.required, + }, + readonly: undefined, // MCP tools don't have readonly property + isBuiltIn: false, + run: async (args: any) => { + const result = await services.mcp?.runTool(mcpTool.name, args); + return JSON.stringify(result?.content) ?? ""; + }, + }; } export async function executeToolCall( diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index c7ab739e5..90d5fedf9 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -2,13 +2,7 @@ import { render } from "ink-testing-library"; import React from "react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { getAllTools } from "src/stream/handleToolCalls.js"; - -import { - SERVICE_NAMES, - serviceContainer, - services, -} from "../../services/index.js"; +import { services } from "../../services/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; const toolPermissionService = services.toolPermissions; @@ -141,41 +135,4 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { unmount(); } }); - - it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => { - // This test specifically tests the service container interaction - // that causes the actual bug in production - - // First, set up a realistic service state (not mocked) - await toolPermissionService.initialize({ isHeadless: false }); - - // Register the tool permissions service like the real app does - const initialState = toolPermissionService.getState(); - serviceContainer.registerValue( - SERVICE_NAMES.TOOL_PERMISSIONS, - initialState, - ); - - // Verify initial state works - expect(() => getAllTools()).not.toThrow(); - - // Switch modes WITHOUT updating the service container (this simulates the bug) - toolPermissionService.switchMode("plan"); - - // The service container still has the old state, so getAllTools() should not find - // the updated state with plan mode permissions. However, since the ToolPermissionService - // overrides isReady() to always return true, getAllTools() will actually work. - // The real bug would manifest when the service container has an out-of-sync state. - - // To reproduce the ACTUAL bug, we need to simulate the case where the service - // container has a stale state that doesn't match the ToolPermissionService - const staleState = { ...initialState, currentMode: "normal" as const }; - serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState); - - // Now getAllTools() should work because it gets the service state from the container - // and the container has a valid state (even if it's stale) - const tools = getAllTools(); - expect(tools).toBeDefined(); - expect(Array.isArray(tools)).toBe(true); - }); }); diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 3a31e458a..a11550ccf 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,6 +1,6 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; -import { getAllBuiltinTools } from "src/tools/index.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; import { logger } from "src/util/logger.js"; import { services } from "../../services/index.js"; @@ -65,6 +65,8 @@ export function createStreamCallbacks( }, onToolStart: (toolName: string, toolArgs?: any) => { + // TODO service should always be ready, get rid of this code. If it's not ready throw error + // When ChatHistoryService is ready, let handleToolCalls add entries const svc = services.chatHistory; const useService = typeof svc?.isReady === "function" && svc.isReady(); @@ -203,7 +205,7 @@ export function createStreamCallbacks( toolCallPreview?: any[], ) => { // Check if this tool has dynamic evaluation - const tool = getAllBuiltinTools().find((t: any) => t.name === toolName); + const tool = ALL_BUILT_IN_TOOLS.find((t: any) => t.name === toolName); const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy; setActivePermissionRequest({ diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 1b1a62086..605b6dd2d 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { processRule } from "../hubLoader.js"; -import { processAndCombinePrompts } from "./promptProcessor.js"; +import { prependPrompt, processAndCombinePrompts } from "./promptProcessor.js"; // Mock the args module vi.mock("../hubLoader.js", () => ({ @@ -125,3 +125,179 @@ describe("promptProcessor", () => { }); }); }); + +describe("prependPrompt", () => { + describe("normal cases", () => { + it("should combine two non-empty strings with double newlines", () => { + const result = prependPrompt("Hello", "World"); + expect(result).toBe("Hello\n\nWorld"); + }); + + it("should combine multi-line strings correctly", () => { + const prepend = "Line 1\nLine 2"; + const original = "Line 3\nLine 4"; + const result = prependPrompt(prepend, original); + expect(result).toBe("Line 1\nLine 2\n\nLine 3\nLine 4"); + }); + + it("should handle strings with special characters", () => { + const prepend = "Special: @#$%^&*()"; + const original = "Unicode: šŸš€ āˆ‘ āˆ†"; + const result = prependPrompt(prepend, original); + expect(result).toBe("Special: @#$%^&*()\n\nUnicode: šŸš€ āˆ‘ āˆ†"); + }); + }); + + describe("undefined parameter cases", () => { + it("should handle undefined prepend with defined original", () => { + const result = prependPrompt(undefined, "original"); + expect(result).toBe("original"); + }); + + it("should handle defined prepend with undefined original", () => { + const result = prependPrompt("prepend", undefined); + expect(result).toBe("prepend"); + }); + + it("should return undefined when both parameters are undefined", () => { + const result = prependPrompt(undefined, undefined); + expect(result).toBeUndefined(); + }); + }); + + describe("empty string cases", () => { + it("should handle empty prepend with non-empty original", () => { + const result = prependPrompt("", "original"); + expect(result).toBe("original"); + }); + + it("should handle non-empty prepend with empty original", () => { + const result = prependPrompt("prepend", ""); + expect(result).toBe("prepend"); + }); + + it("should return undefined when both parameters are empty strings", () => { + const result = prependPrompt("", ""); + expect(result).toBeUndefined(); + }); + + it("should handle mixed undefined and empty string", () => { + const result1 = prependPrompt(undefined, ""); + const result2 = prependPrompt("", undefined); + expect(result1).toBeUndefined(); + expect(result2).toBeUndefined(); + }); + }); + + describe("whitespace cases", () => { + it("should trim leading and trailing whitespace", () => { + const result = prependPrompt(" hello ", " world "); + expect(result).toBe("hello\n\nworld"); + }); + + it("should return undefined when result is only whitespace", () => { + const result = prependPrompt(" ", " "); + expect(result).toBeUndefined(); + }); + + it("should handle newlines in parameters", () => { + const prepend = "\nhello\n"; + const original = "\nworld\n"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n\nworld"); + }); + + it("should handle mixed whitespace characters", () => { + const prepend = "\t hello \t"; + const original = "\r\n world \r\n"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n\nworld"); + }); + + it("should preserve internal whitespace and newlines", () => { + const prepend = "hello\n world"; + const original = "foo\t\tbar"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n world\n\nfoo\t\tbar"); + }); + }); + + describe("edge cases", () => { + it("should handle very long strings", () => { + const longString = "a".repeat(10000); + const result = prependPrompt(longString, "short"); + expect(result).toBe(`${longString}\n\nshort`); + expect(result?.length).toBe(10000 + 2 + 5); // long + \n\n + short + }); + + it("should handle strings with only newlines", () => { + const result = prependPrompt("\n\n\n", "\n\n"); + expect(result).toBeUndefined(); + }); + + it("should handle one parameter with content and other with only whitespace", () => { + const result1 = prependPrompt("content", " \n "); + const result2 = prependPrompt(" \t ", "content"); + expect(result1).toBe("content"); + expect(result2).toBe("content"); + }); + }); + + describe("boundary conditions", () => { + it("should return undefined for whitespace-only result after trim", () => { + const cases = [ + ["", ""], + [" ", ""], + ["", " "], + [" ", " "], + ["\n", "\n"], + ["\t", "\r"], + [undefined, ""], + ["", undefined], + [undefined, undefined], + [" \n ", " \n "], + ] as const; + + cases.forEach(([prepend, original]) => { + const result = prependPrompt(prepend, original); + expect(result).toBeUndefined(); + }); + }); + + it("should return trimmed string for non-empty result", () => { + const cases = [ + ["a", "", "a"], + ["", "b", "b"], + ["a", "b", "a\n\nb"], + [" a ", "", "a"], + ["", " b ", "b"], + [" a ", " b ", "a\n\nb"], + [undefined, "content", "content"], + ["content", undefined, "content"], + ] as const; + + cases.forEach(([prepend, original, expected]) => { + const result = prependPrompt(prepend, original); + expect(result).toBe(expected); + }); + }); + }); + + describe("return type consistency", () => { + it("should always return string or undefined", () => { + const testCases = [ + ["hello", "world"], + [undefined, "world"], + ["hello", undefined], + [undefined, undefined], + ["", ""], + [" ", " "], + ] as const; + + testCases.forEach(([prepend, original]) => { + const result = prependPrompt(prepend, original); + expect(typeof result === "string" || result === undefined).toBe(true); + }); + }); + }); +}); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index b0d24b764..65452c480 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -36,3 +36,14 @@ export async function processAndCombinePrompts( ? `${combinedPrompts}\n\n${initialPrompt}` : combinedPrompts; } + +// Merges two prompts with new lines between them, handling undefined +export function prependPrompt( + prepend: string | undefined, + original: string | undefined, +) { + return ( + `${(prepend ?? "").trim()}\n\n${(original ?? "").trim()}`.trim() || + undefined + ); +} diff --git a/extensions/cli/vitest.setup.ts b/extensions/cli/vitest.setup.ts index e08c28e4b..2dcf0f8d0 100644 --- a/extensions/cli/vitest.setup.ts +++ b/extensions/cli/vitest.setup.ts @@ -6,6 +6,43 @@ import { resetConsoleOverrides } from "./src/init.js"; process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0"; +// Mock fetch to prevent actual API calls in tests +const originalFetch = global.fetch; +global.fetch = vi + .fn() + .mockImplementation(async (url: string | URL, ...args) => { + const urlString = url.toString(); + + // Mock the default-agent API call + if (urlString.includes("get-assistant/continuedev/default-agent")) { + return { + ok: true, + status: 200, + json: async () => ({ + configResult: { + config: { + name: "Default Agent", + version: "0.0.1", + schema: "v1", + models: [ + { + provider: "anthropic", + name: "claude-sonnet-4-5", + apiKey: "test-key", + roles: ["chat"], + }, + ], + rules: [], + mcpServers: [], + }, + errors: [], + }, + }), + }; + } + return originalFetch(url, ...args); + }); + // Mock the 'open' package to prevent browser opening during tests vi.mock("open", () => ({ default: vi.fn().mockResolvedValue(undefined), diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index c9680f84b..2fd1ea6b8 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,5 +1,5 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginVersion=1.0.50 +pluginVersion=1.0.52 platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8ba7ef1ce..28568c7fe 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.3.21", + "version": "1.3.23", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index d1f5b8ef2..67bd9cd8c 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -4,7 +4,6 @@ import { AutocompleteSnippetType, } from "core/autocomplete/snippets/types"; import { isSecurityConcern } from "core/indexing/ignore"; -import { PosthogFeatureFlag, Telemetry } from "core/util/posthog"; import { LRUCache } from "lru-cache"; import * as vscode from "vscode"; @@ -34,19 +33,18 @@ export class RecentlyVisitedRangesService { } private async initWithPostHog() { - const recentlyVisitedRangesNumSurroundingLines = - await Telemetry.getValueForFeatureFlag( - PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, - ); - - if (recentlyVisitedRangesNumSurroundingLines) { - this.isEnabled = true; - this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; - } - - vscode.window.onDidChangeTextEditorSelection( - this.cacheCurrentSelectionContext, - ); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // const recentlyVisitedRangesNumSurroundingLines = + // await Telemetry.getValueForFeatureFlag( + // PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, + // ); + // if (recentlyVisitedRangesNumSurroundingLines) { + // this.isEnabled = true; + // this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; + // } + // vscode.window.onDidChangeTextEditorSelection( + // this.cacheCurrentSelectionContext, + // ); } private cacheCurrentSelectionContext = async ( diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index fc4eab517..25791ffa1 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -24,25 +24,24 @@ export class RecentlyEditedTracker { private static maxRecentlyEditedDocuments = 10; constructor(private ideUtils: VsCodeIdeUtils) { - vscode.workspace.onDidChangeTextDocument((event) => { - event.contentChanges.forEach((change) => { - const editedRange = { - uri: event.document.uri, - range: new vscode.Range( - new vscode.Position(change.range.start.line, 0), - new vscode.Position(change.range.end.line + 1, 0), - ), - timestamp: Date.now(), - }; - this.insertRange(editedRange); - }); - - this.insertDocument(event.document.uri); - }); - - setInterval(() => { - this.removeOldEntries(); - }, 1000 * 15); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // vscode.workspace.onDidChangeTextDocument((event) => { + // event.contentChanges.forEach((change) => { + // const editedRange = { + // uri: event.document.uri, + // range: new vscode.Range( + // new vscode.Position(change.range.start.line, 0), + // new vscode.Position(change.range.end.line + 1, 0), + // ), + // timestamp: Date.now(), + // }; + // this.insertRange(editedRange); + // }); + // this.insertDocument(event.document.uri); + // }); + // setInterval(() => { + // this.removeOldEntries(); + // }, 1000 * 15); } private async insertRange( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 5bd039cd6..22f1aaad8 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -44,13 +44,10 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; -import { getAst } from "core/autocomplete/util/ast"; import { modelSupportsNextEdit } from "core/llm/autodetect"; import { NEXT_EDIT_MODELS } from "core/llm/constants"; -import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { isNextEditTest } from "core/nextEdit/utils"; -import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, @@ -534,16 +531,17 @@ export class VsCodeExtension { }); }); - vscode.workspace.onDidOpenTextDocument(async (event) => { - const ast = await getAst(event.fileName, event.getText()); - if (ast) { - DocumentHistoryTracker.getInstance().addDocument( - localPathOrUriToPath(event.fileName), - event.getText(), - ast, - ); - } - }); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // vscode.workspace.onDidOpenTextDocument(async (event) => { + // const ast = await getAst(event.fileName, event.getText()); + // if (ast) { + // DocumentHistoryTracker.getInstance().addDocument( + // localPathOrUriToPath(event.fileName), + // event.getText(), + // ast, + // ); + // } + // }); // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index d4ebe4868..6e723340c 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -24,6 +24,7 @@ import { ToolCallDelta, ToolCallState, } from "core"; +import { mergeReasoningDetails } from "core/llm/openaiTypeConverters"; import type { RemoteSessionMetadata } from "core/control-plane/client"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { @@ -649,6 +650,29 @@ export const sessionSlice = createSlice({ ) { handleStreamingToolCallUpdates(message, lastItem); } + + // Attach Responses API output item id to the current assistant message if present + // fromResponsesChunk sets message.metadata.responsesOutputItemId when it sees output_item.added for messages + if ( + message.role === "assistant" && + lastMessage.role === "assistant" && + message.metadata?.responsesOutputItemId + ) { + lastMessage.metadata = lastMessage.metadata || {}; + lastMessage.metadata.responsesOutputItemId = message.metadata + .responsesOutputItemId as string; + } + + if ( + message.role === "thinking" && + message.reasoning_details && + lastMessage.role === "thinking" + ) { + lastMessage.reasoning_details = mergeReasoningDetails( + lastMessage.reasoning_details, + message.reasoning_details, + ); + } } } }, diff --git a/packages/config-yaml/src/load/merge.ts b/packages/config-yaml/src/load/merge.ts index ebd2e9633..9b5b254a4 100644 --- a/packages/config-yaml/src/load/merge.ts +++ b/packages/config-yaml/src/load/merge.ts @@ -1,5 +1,6 @@ -import { RequestOptions } from "../browser.js"; +import { BLOCK_TYPES, RequestOptions } from "../browser.js"; import { AssistantUnrolled, ConfigYaml } from "../schemas/index.js"; +import { BlockDuplicationDetector } from "./blockDuplicationDetector.js"; export function mergePackages( current: ConfigYaml, @@ -26,21 +27,35 @@ export function mergeUnrolledAssistants( current: AssistantUnrolled, incoming: AssistantUnrolled, ): AssistantUnrolled { - return { + const assistant: AssistantUnrolled = { ...current, - rules: [...(current.rules ?? []), ...(incoming.rules ?? [])], - models: [...(current.models ?? []), ...(incoming.models ?? [])], - docs: [...(current.docs ?? []), ...(incoming.docs ?? [])], - context: [...(current.context ?? []), ...(incoming.context ?? [])], - data: [...(current.data ?? []), ...(incoming.data ?? [])], - mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])], - prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])], env: { ...current.env, ...incoming.env }, requestOptions: mergeConfigYamlRequestOptions( current.requestOptions, incoming.requestOptions, ), }; + + const duplicationDetector = new BlockDuplicationDetector(); + for (const blockType of BLOCK_TYPES) { + const allOfType = [ + ...(incoming[blockType] ?? []), + ...(current[blockType] ?? []), + ]; + const deduplicated: typeof allOfType = []; + for (const block of allOfType) { + if (block && !duplicationDetector.isDuplicated(block, blockType)) { + deduplicated.push(block); + } + } + if (deduplicated.length > 0) { + assistant[blockType] = deduplicated as any; + } else { + assistant[blockType] = undefined; + } + } + + return assistant; } export function mergeConfigYamlRequestOptions( diff --git a/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts b/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts new file mode 100644 index 000000000..9f7ec1d7f --- /dev/null +++ b/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts @@ -0,0 +1,562 @@ +import { describe, expect, it } from "@jest/globals"; +import { AssistantUnrolled } from "../schemas/index.js"; +import { mergeUnrolledAssistants } from "./merge.js"; + +describe("mergeUnrolledAssistants", () => { + const createBaseConfig = (): AssistantUnrolled => ({ + name: "Base Assistant", + version: "1.0.0", + models: [ + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + context: [ + { + provider: "file", + }, + ], + rules: [ + { + name: "typescript-style", + rule: "Use TypeScript best practices", + }, + ], + prompts: [ + { + name: "code-review", + description: "Review code for best practices", + prompt: "Please review this code", + }, + ], + docs: [ + { + name: "api-docs", + startUrl: "https://api.example.com/docs", + }, + ], + data: [ + { + name: "user-data", + destination: "memory", + schema: "0.1.0", + }, + ], + mcpServers: [ + { + name: "filesystem", + command: "npx", + args: ["@modelcontextprotocol/server-filesystem"], + env: { + ROOT_PATH: "/tmp", + }, + }, + ], + env: { + API_KEY: "base-key", + }, + requestOptions: { + timeout: 5000, + headers: { + "X-Base": "value", + }, + }, + }); + + const createIncomingConfig = (): AssistantUnrolled => ({ + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-3.5-turbo", + model: "gpt-3.5-turbo", + provider: "openai", + }, + ], + context: [ + { + provider: "git", + }, + ], + rules: [ + { + name: "code-formatting", + rule: "Use Prettier for code formatting", + }, + ], + prompts: [ + { + name: "bug-fix", + description: "Fix bugs in code", + prompt: "Please fix the bug in this code", + }, + ], + docs: [ + { + name: "user-guide", + startUrl: "https://docs.example.com/guide", + }, + ], + data: [ + { + name: "project-data", + destination: "filesystem", + schema: "0.1.0", + }, + ], + mcpServers: [ + { + name: "git-server", + command: "npx", + args: ["@modelcontextprotocol/server-git"], + }, + ], + env: { + API_TOKEN: "incoming-token", + API_KEY: "incoming-key", // This will override base via object spread + }, + requestOptions: { + timeout: 3000, + headers: { + "X-Incoming": "value", + "X-Base": "overridden", + }, + }, + }); + + it("should merge all block types without duplicates", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + // Should have models from both configs (incoming first due to priority) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + + // Should have context from both configs (incoming first due to priority) + expect(result.context).toHaveLength(2); + expect(result.context?.map((c) => c?.provider)).toEqual(["git", "file"]); + + // Should have rules from both configs (incoming first due to priority) + expect(result.rules).toHaveLength(2); + expect( + result.rules?.map((r) => (typeof r === "string" ? r : r?.name)), + ).toEqual(["code-formatting", "typescript-style"]); + + // Should have prompts from both configs (incoming first due to priority) + expect(result.prompts).toHaveLength(2); + expect(result.prompts?.map((p) => p?.name)).toEqual([ + "bug-fix", + "code-review", + ]); + + // Should have docs from both configs (incoming first due to priority) + expect(result.docs).toHaveLength(2); + expect(result.docs?.map((d) => d?.name)).toEqual([ + "user-guide", + "api-docs", + ]); + + // Should have data from both configs (incoming first due to priority) + expect(result.data).toHaveLength(2); + expect(result.data?.map((d) => d?.name)).toEqual([ + "project-data", + "user-data", + ]); + + // Should have mcpServers from both configs (incoming first due to priority) + expect(result.mcpServers).toHaveLength(2); + expect(result.mcpServers?.map((s) => s?.name)).toEqual([ + "git-server", + "filesystem", + ]); + }); + + it("should deduplicate models by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-4", // Duplicate name + model: "gpt-4", + provider: "openai", + }, + { + name: "claude-3", + model: "claude-3-sonnet-20240229", + provider: "anthropic", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 models (incoming gpt-4 and incoming claude-3) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual(["gpt-4", "claude-3"]); + // Should keep the incoming version of gpt-4 (base version filtered as duplicate) + expect(result.models?.[0]?.model).toBe("gpt-4"); + }); + + it("should deduplicate context by provider", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + context: [ + { + name: "file-context", // Different name but same provider + provider: "file", // Same provider as base + }, + { + name: "terminal", + provider: "terminal", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 context providers (incoming file and incoming terminal) + expect(result.context).toHaveLength(2); + expect(result.context?.map((c) => c?.provider)).toEqual([ + "file", + "terminal", + ]); + // Should keep the incoming version of file provider (base version filtered as duplicate) + expect(result.context?.[0]?.name).toBe("file-context"); + }); + + it("should deduplicate rules by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + { + name: "typescript-style", // Duplicate name + rule: "Use different TypeScript practices", + }, + { + name: "naming-convention", + rule: "Use camelCase for variables", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 rules (incoming typescript-style and incoming naming-convention) + expect(result.rules).toHaveLength(2); + expect( + result.rules?.map((r) => (typeof r === "string" ? r : r?.name)), + ).toEqual(["typescript-style", "naming-convention"]); + // Should keep the incoming version of typescript-style (base version filtered as duplicate) + const typescriptRule = result.rules?.[0] as any; + expect(typescriptRule.rule).toBe("Use different TypeScript practices"); + }); + + it("should deduplicate string rules", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + rules: ["Use semicolons", "Format with Prettier"], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + "Use semicolons", // Duplicate + "Use const instead of let", + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 3 unique rules (incoming first, then non-duplicates from base) + expect(result.rules).toHaveLength(3); + expect(result.rules).toEqual([ + "Use semicolons", + "Use const instead of let", + "Format with Prettier", + ]); + }); + + it("should deduplicate prompts by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + prompts: [ + { + name: "code-review", // Duplicate name + description: "Different review process", + prompt: "Different review prompt", + }, + { + name: "documentation", + description: "Generate documentation", + prompt: "Create docs for this code", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 prompts (incoming code-review and incoming documentation) + expect(result.prompts).toHaveLength(2); + expect(result.prompts?.map((p) => p?.name)).toEqual([ + "code-review", + "documentation", + ]); + // Should keep the incoming version of code-review (base version filtered as duplicate) + expect(result.prompts?.[0]?.description).toBe("Different review process"); + }); + + it("should deduplicate docs by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + docs: [ + { + name: "api-docs", // Duplicate name + startUrl: "https://different-api.example.com/docs", + }, + { + name: "tutorials", + startUrl: "https://tutorials.example.com", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 docs (incoming api-docs and incoming tutorials) + expect(result.docs).toHaveLength(2); + expect(result.docs?.map((d) => d?.name)).toEqual(["api-docs", "tutorials"]); + // Should keep the incoming version of api-docs (base version filtered as duplicate) + expect(result.docs?.[0]?.startUrl).toBe( + "https://different-api.example.com/docs", + ); + }); + + it("should deduplicate data by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + data: [ + { + name: "user-data", // Duplicate name + destination: "different-provider", + schema: "0.1.0", + }, + { + name: "system-data", + destination: "system", + schema: "0.1.0", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 data sources (incoming user-data and incoming system-data) + expect(result.data).toHaveLength(2); + expect(result.data?.map((d) => d?.name)).toEqual([ + "user-data", + "system-data", + ]); + // Should keep the incoming version of user-data (base version filtered as duplicate) + expect(result.data?.[0]?.destination).toBe("different-provider"); + }); + + it("should deduplicate mcpServers by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + mcpServers: [ + { + name: "filesystem", // Duplicate name + command: "different-command", + args: ["different-args"], + }, + { + name: "database", + command: "db-server", + args: ["--port", "5432"], + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 MCP servers (incoming filesystem and incoming database) + expect(result.mcpServers).toHaveLength(2); + expect(result.mcpServers?.map((s) => s?.name)).toEqual([ + "filesystem", + "database", + ]); + // Should keep the incoming version of filesystem (base version filtered as duplicate) + const firstMcpServer = result.mcpServers?.[0]; + if (firstMcpServer && "command" in firstMcpServer) { + expect(firstMcpServer.command).toBe("different-command"); + } + }); + + it("should handle null values in arrays", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + models: [ + null, + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "claude-3", + model: "claude-3-sonnet-20240229", + provider: "anthropic", + }, + null, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should filter out null values and have only 2 models (incoming first due to priority) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual(["claude-3", "gpt-4"]); + }); + + it("should merge env variables with incoming overriding base", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.env).toEqual({ + API_KEY: "incoming-key", // Should be overridden by incoming + API_TOKEN: "incoming-token", // New from incoming + }); + }); + + it("should merge requestOptions correctly", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.requestOptions).toEqual({ + timeout: 5000, // Base overrides incoming + headers: { + "X-Base": "value", // Base overrides incoming in headers too + "X-Incoming": "value", // New from incoming + }, + }); + }); + + it("should handle empty arrays and undefined fields", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + models: [], + context: undefined, + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + rules: [], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.models).toHaveLength(1); + expect(result.models?.[0]?.name).toBe("gpt-4"); + expect(result.context).toBeUndefined(); + expect(result.rules).toBeUndefined(); + }); + + it("should preserve name and version from base config", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.name).toBe("Base Assistant"); + expect(result.version).toBe("1.0.0"); + }); + + it("should handle complex deduplication scenario with mixed types", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + rules: [ + "Simple rule 1", + { + name: "complex-rule", + rule: "Complex rule description", + }, + "Simple rule 2", + ], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + "Simple rule 1", // Duplicate + { + name: "complex-rule", // Duplicate by name + rule: "Different complex rule description", + }, + { + name: "new-complex-rule", + rule: "New complex rule", + }, + "Simple rule 3", + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.rules).toHaveLength(5); // 4 incoming + 1 from base (2 duplicates filtered) + expect(result.rules).toEqual([ + "Simple rule 1", // From incoming (base duplicate filtered) + { + name: "complex-rule", + rule: "Different complex rule description", // Should keep incoming version + }, + { + name: "new-complex-rule", + rule: "New complex rule", + }, + "Simple rule 3", + "Simple rule 2", // From base (only non-duplicate left) + ]); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index cc05ccaf0..6aa8c5cc0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -721,7 +721,17 @@ export async function resolveBlock( secrets: extractFQSNMap(rawYaml, [id]), }); - return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); + // Add source slug for mcp servers + const parsed = parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); + if ( + id.uriType === "slug" && + "mcpServers" in parsed && + parsed.mcpServers?.[0] + ) { + parsed.mcpServers[0].sourceSlug = `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + } + + return parsed; } export function parseMarkdownRuleOrAssistantUnrolled( diff --git a/packages/config-yaml/src/schemas/mcp/index.ts b/packages/config-yaml/src/schemas/mcp/index.ts index b0ede8778..5d7430355 100644 --- a/packages/config-yaml/src/schemas/mcp/index.ts +++ b/packages/config-yaml/src/schemas/mcp/index.ts @@ -6,6 +6,7 @@ const baseMcpServerSchema = z.object({ serverName: z.string().optional(), faviconUrl: z.string().optional(), sourceFile: z.string().optional(), // Added during loading + sourceSlug: z.string().optional(), // Added during loading connectionTimeout: z.number().gt(0).optional(), });