Merge branch 'main' into dallin/tool-prompt

This commit is contained in:
Dallin Romney 2025-03-19 10:10:37 -07:00 • committed by GitHub
commit 9c3e366812
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 502 additions and 580 deletions

View file

@ -17,7 +17,7 @@ export function constructMcpSlashCommand(
const userInput = context.input.split(" ").slice(1).join(" ");
if (args) {
args.forEach((arg, i) => {
argsObject[arg] = userInput;
argsObject[arg] = ""; // userInput
});
}
@ -35,9 +35,22 @@ export function constructMcpSlashCommand(
};
});
if (messages.length === 0) {
yield "The MCP prompt returned no messages";
return;
}
const reversedMessages = [...messages].reverse();
const messageToAppendInput =
reversedMessages.find((m) => m.role === "user") ??
reversedMessages.find((m) => m.role === "assistant") ??
reversedMessages[0];
messageToAppendInput.content += ` ${userInput}`;
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

@ -28,6 +28,7 @@ import {
IdeType,
ILLM,
LLMOptions,
MCPOptions,
ModelDescription,
RerankerDescription,
SerializedContinueConfig,
@ -542,40 +543,39 @@ async function intermediateToFinalConfig(
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
function getMcpId(options: MCPOptions) {
return JSON.stringify(options);
}
if (config.experimental?.modelContextProtocolServers) {
await mcpManager.removeUnusedConnections(
config.experimental.modelContextProtocolServers.map(getMcpId),
);
}
if (config.experimental?.modelContextProtocolServers) {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
4000,
5000,
);
await Promise.allSettled(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
try {
const mcpId = index.toString();
const mcpId = getMcpId(server);
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const mcpError = await mcpConnection.modifyConfig(
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e) {
let errorMessage = "Failed to load MCP server";
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
errorMessage += ": " + e.message;
}
errors.push({
fatal: false,
@ -998,6 +998,5 @@ export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig
type BrowserSerializedContinueConfig,
};

View file

@ -369,12 +369,18 @@ async function configYamlToContinueConfig(
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.mcpServers) {
await mcpManager.removeUnusedConnections(
config.mcpServers.map((s) => s.name),
);
}
await Promise.allSettled(
config.mcpServers?.map(async (server) => {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
4000,
5000,
);
try {
@ -386,28 +392,18 @@ async function configYamlToContinueConfig(
...server,
},
});
if (!mcpConnection) {
return;
}
const mcpError = await mcpConnection.modifyConfig(
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
server.name,
server.faviconUrl,
);
if (mcpError) {
localErrors.push(mcpError);
}
} catch (e) {
let errorMessage = `Failed to load MCP server ${server.name}`;
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
errorMessage += ": " + e.message;
}
localErrors.push({
fatal: false,

View file

@ -4,7 +4,6 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { encodeMCPToolUri } from "../../tools/callTool";
@ -24,13 +23,13 @@ export class MCPManagerSingleton {
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection | undefined {
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id);
return this.connections.get(id)!;
}
}
@ -46,6 +45,13 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
async removeUnusedConnections(keepIds: string[]) {
const toRemove = Array.from(this.connections.keys()).filter(
(k) => !keepIds.includes(k),
);
await Promise.all(toRemove.map((id) => this.removeConnection(id)));
}
}
class MCPConnection {
@ -123,25 +129,32 @@ class MCPConnection {
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
): Promise<ConfigValidationError | undefined> {
) {
try {
await Promise.race([
this.connectClient(),
new Promise((_, reject) => {
signal.addEventListener("abort", () =>
reject(new Error("Connection aborted")),
reject(new Error("Connection timed out")),
);
}),
]);
} catch (error: any) {
if (signal.aborted) {
throw new Error("Operation aborted");
}
if (!error.message.startsWith("StdioClientTransport already started")) {
return {
fatal: false,
message: `Failed to connect to MCP: ${error.message}`,
};
} catch (error) {
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
throw new Error(
`command "${command}" not found. To use this MCP server, install the ${command} CLI.`,
);
} else if (
!error.message.startsWith("StdioClientTransport already started")
) {
// don't throw error if it's just a "server already running" case
throw error;
}
} else {
throw error;
}
}

View file

@ -36,9 +36,7 @@ import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import {
ChatMessage,
DiffLine,
PromptLog,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
@ -47,6 +45,7 @@ import {
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -486,111 +485,14 @@ export class Core {
}
});
async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
void TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return({
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
...msg.data.completionOptions,
model: model.model,
},
});
break;
}
const chunk = next.value;
yield chunk;
next = await gen.next();
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
on("llm/streamChat", (msg) =>
llmStreamChat(this.configHandler, this.abortedMessageIds, msg),
);
async function* llmStreamComplete(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
): AsyncGenerator<string, PromptLog> {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return({
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
...msg.data.completionOptions,
model: model.model,
},
});
break;
}
yield next.value;
next = await gen.next();
}
if (!next.done) {
throw new Error("This will never happen");
}
return next.value;
}
on("llm/streamComplete", (msg) =>
llmStreamComplete(this.configHandler, this.abortedMessageIds, msg),
llmStreamChat(
this.configHandler,
this.abortedMessageIds,
msg,
ide,
this.messenger,
),
);
on("llm/complete", async (msg) => {
@ -643,96 +545,6 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
async function* runNodeJsSlashCommand(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
): AsyncGenerator<string> {
const {
input,
history,
modelTitle,
slashCommandName,
contextItems,
params,
historyIndex,
selectedCode,
completionOptions,
} = msg.data;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const llm = await configHandler.llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
void Telemetry.capture(
"useSlashCommand",
{
name: slashCommandName,
},
true,
);
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
}
}, 100);
try {
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
break;
}
if (content) {
yield content;
}
}
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
this.configHandler,
this.abortedMessageIds,
msg,
this.messenger,
),
);
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =

149
core/llm/streamChat.ts Normal file
View file

@ -0,0 +1,149 @@
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { ChatMessage, IDE, PromptLog } from "..";
import { ConfigHandler } from "../config/ConfigHandler";
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import { IMessenger, Message } from "../protocol/messenger";
import { Telemetry } from "../util/posthog";
import { TTS } from "../util/tts";
export async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
ide: IDE,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
void TTS.kill();
}
const { title, legacySlashCommandData, completionOptions, messages } =
msg.data;
const model = await configHandler.llmFromTitle(title);
// Log to return in case of error
const errorPromptLog = {
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
...msg.data.completionOptions,
model: model.model,
},
};
if (legacySlashCommandData) {
const { command, contextItems, historyIndex, input, selectedCode } =
legacySlashCommandData;
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === command.name,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${command.name}`);
}
void Telemetry.capture(
"useSlashCommand",
{
name: command.name,
},
true,
);
const gen = slashCommand.run({
input,
history: messages,
llm: model,
contextItems,
params: command.params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
});
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
}
}, 100);
try {
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
clearInterval(checkActiveInterval);
break;
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
} else {
const gen = model.streamChat(
messages,
new AbortController().signal,
completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
break;
}
const chunk = next.value;
yield chunk;
next = await gen.next();
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
}

View file

@ -79,6 +79,7 @@ export function slashCommandFromPromptFileV1(
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

@ -26,6 +26,7 @@ import type {
Session,
SessionMetadata,
SiteIndexingConfig,
SlashCommandDescription,
ToolCall,
} from "../";
import { GlobalContextModelSelections } from "../util/GlobalContext";
@ -101,20 +102,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"context/indexDocs": [{ reIndex: boolean }, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"command/run": [
{
input: string;
history: ChatMessage[];
modelTitle: string;
slashCommandName: string;
contextItems: ContextItemWithId[];
params: any;
historyIndex: number;
selectedCode: RangeInFile[];
completionOptions?: LLMFullCompletionOptions;
},
AsyncGenerator<string>,
];
"llm/complete": [
{
prompt: string;
@ -124,19 +111,18 @@ export type ToCoreFromIdeOrWebviewProtocol = {
string,
];
"llm/listModels": [{ title: string }, string[] | undefined];
"llm/streamComplete": [
{
prompt: string;
completionOptions: LLMFullCompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
"llm/streamChat": [
{
messages: ChatMessage[];
completionOptions: LLMFullCompletionOptions;
title: string;
legacySlashCommandData?: {
command: SlashCommandDescription;
input: string;
contextItems: ContextItemWithId[];
historyIndex: number;
selectedCode: RangeInFile[];
};
},
AsyncGenerator<ChatMessage, PromptLog>,
];

View file

@ -35,10 +35,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",

View file

@ -86,20 +86,44 @@ async function callToolFromUri(
throw new Error(`Failed to call tool: ${toolName}`);
}
return (response.content as any).map((item: any): ContextItem => {
if (item.type !== "text") {
throw new Error(
`Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`,
);
const contextItems: ContextItem[] = [];
(response.content as any).forEach((item: any) => {
if (item.type === "text") {
contextItems.push({
name: extras.tool.displayTitle,
description: "Tool output",
content: item.text,
icon: extras.tool.faviconUrl,
});
} else if (item.type === "resource") {
// TODO resource change subscribers https://modelcontextprotocol.io/docs/concepts/resources
if (item.resource?.blob) {
contextItems.push({
name: extras.tool.displayTitle,
description: "MCP Item Error",
content:
"Error: tool call received unsupported blob resource item",
icon: extras.tool.faviconUrl,
});
}
// TODO account for mimetype? // const mimeType = item.resource.mimeType
// const uri = item.resource.uri;
contextItems.push({
name: extras.tool.displayTitle,
description: "Tool output",
content: item.resource.text,
icon: extras.tool.faviconUrl,
});
} else {
contextItems.push({
name: extras.tool.displayTitle,
description: "MCP Item Error",
content: `Error: tool call received unsupported item of type "${item.type}"`,
icon: extras.tool.faviconUrl,
});
}
return {
name: extras.tool.displayTitle,
description: "Tool output",
content: item.text,
icon: extras.tool.faviconUrl,
};
});
return contextItems;
default:
throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`);
}

View file

@ -103,10 +103,8 @@ class MessageTypes {
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",

View file

@ -1,15 +1,18 @@
import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core";
import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { ChatMessage, IDE, PromptLog } from "core";
import type {
FromWebviewProtocol,
ToCoreProtocol,
ToWebviewProtocol,
} from "core/protocol";
import { Message } from "core/protocol/messenger";
import { MessageIde } from "core/protocol/messenger/messageIde";
import {
GeneratorReturnType,
GeneratorYieldType,
WebviewMessage,
WebviewProtocolGeneratorMessage,
WebviewSingleMessage,
WebviewSingleProtocolMessage,
} from "core/protocol/util";
import { MessageIde } from "core/protocol/messenger/messageIde";
import { Message } from "core/protocol/messenger";
import { createContext } from "react";
import { v4 as uuidv4 } from "uuid";
import "vscode-webview";
@ -50,10 +53,8 @@ export interface IIdeMessenger {
>;
llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined>;
ide: IDE;
@ -247,20 +248,10 @@ export class IdeMessenger implements IIdeMessenger {
}
async *llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options: LLMFullCompletionOptions = {},
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
const gen = this.streamRequest(
"llm/streamChat",
{
messages,
title: modelTitle,
completionOptions: options,
},
cancelToken,
);
const gen = this.streamRequest("llm/streamChat", msg, cancelToken);
let next = await gen.next();
while (!next.done) {

View file

@ -33,7 +33,7 @@ export default function ConfigErrorPage() {
<div className="py-5">
<h3 className="mb-2 mt-0 text-xl">Config Errors</h3>
<p className="text-md mb-4">
Please resolve the following errors in your config.json file.
Please resolve the following errors in your assistant configuration.
</p>
<div className="flex flex-col gap-5">
{sortedErrors.length > 0 ? (

View file

@ -1,75 +0,0 @@
import { Tool, ToolCallDelta, ToolCallState } from "core";
import Mustache from "mustache";
import styled from "styled-components";
import { useAppSelector } from "../../../redux/hooks";
interface ThreadDivProps {
children: React.ReactNode;
icon: React.ReactNode;
toolCall: ToolCallDelta;
toolCallState: ToolCallState;
}
const Container = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
position: relative;
padding: 8px;
padding-bottom: 0;
`;
const ChildrenDiv = styled.div``;
const W = 16;
const HeaderDiv = styled.div`
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
`;
export function ThreadDiv(props: ThreadDivProps) {
const availableTools = useAppSelector((state) => state.config.config.tools);
function renderWouldLikeToMessage(
tool: Tool | undefined,
toolCallState: ToolCallState,
): string {
if (!tool) return "";
const rendered = Mustache.render(
tool.wouldLikeTo,
toolCallState.parsedArgs,
);
return rendered;
}
const tool = availableTools.find(
(tool) => props.toolCall.function?.name === tool.function.name,
);
return (
<Container>
<HeaderDiv>
<div
style={{
width: `${W}px`,
height: `${W}px`,
fontWeight: "bolder",
marginTop: "1px",
flexShrink: 0,
}}
>
{props.icon}
</div>
{tool?.faviconUrl && (
<img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
)}
Continue wants to {renderWouldLikeToMessage(tool, props.toolCallState)}
</HeaderDiv>
<ChildrenDiv>{props.children}</ChildrenDiv>
</Container>
);
}

View file

@ -0,0 +1,100 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import { ToolCallDelta, ToolCallState } from "core";
import Mustache from "mustache";
import { useMemo, useState } from "react";
import { ToolTip } from "../../../components/gui/Tooltip";
import { useAppSelector } from "../../../redux/hooks";
interface ToolCallDisplayProps {
children: React.ReactNode;
icon: React.ReactNode;
toolCall: ToolCallDelta;
toolCallState: ToolCallState;
}
export function ToolCallDisplay(props: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const availableTools = useAppSelector((state) => state.config.config.tools);
const tool = useMemo(() => {
return availableTools.find(
(tool) => props.toolCall.function?.name === tool.function.name,
);
}, [availableTools, props.toolCall]);
const wouldLikeToMessage = useMemo(() => {
if (!tool) return "";
const rendered = Mustache.render(
tool.wouldLikeTo,
props.toolCallState.parsedArgs,
);
return rendered;
}, [props.toolCallState, tool]);
const args: [string, any][] = useMemo(() => {
return Object.entries(props.toolCallState.parsedArgs);
}, [props.toolCallState.parsedArgs]);
const argsTooltipId = useMemo(() => {
return "args-hover-" + props.toolCallState.toolCallId;
}, [props.toolCallState]);
return (
<>
<div className="relative flex flex-col justify-center p-4 pb-0">
<div className="mb-4 flex flex-col">
<div className="flex flex-row items-center justify-between gap-3">
<div className="flex flex-row gap-2">
<div
style={{
width: `16px`,
height: `16px`,
fontWeight: "bolder",
marginTop: "1px",
flexShrink: 0,
}}
>
{props.icon}
</div>
{tool?.faviconUrl && (
<img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
)}
<div className="">
Continue wants to <span>{wouldLikeToMessage.trim()}</span>
</div>
</div>
{!!args.length ? (
<div
data-tooltip-id={argsTooltipId}
onClick={() => setIsExpanded(!isExpanded)}
className="ml-2 cursor-pointer hover:opacity-80"
>
{isExpanded ? (
<ChevronUpIcon className="h-4 w-4" />
) : (
<ChevronDownIcon className="h-4 w-4" />
)}
</div>
) : null}
<ToolTip id={argsTooltipId}>
{isExpanded ? "Hide args" : "Show args"}
</ToolTip>
</div>
{isExpanded && !!args.length && (
<div className="ml-7 mt-1">
{args.map(([key, value]) => (
<div key={key} className="flex gap-2 py-0.5">
<span className="text-lightgray">{key}:</span>
<code className="lines lines-1">{value}</code>
</div>
))}
</div>
)}
</div>
<div>{props.children}</div>
</div>
</>
);
}

View file

@ -3,11 +3,11 @@ import {
CheckIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ToolCall, ToolCallDelta, ToolCallState, ToolStatus } from "core";
import { ToolCallDelta, ToolCallState, ToolStatus } from "core";
import { vscButtonBackground } from "../../../components";
import Spinner from "../../../components/gui/Spinner";
import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv";
import { ThreadDiv } from "./ThreadDiv";
import { ToolCallDisplay } from "./ToolCall";
interface ToolCallDivProps {
toolCall: ToolCallDelta;
@ -30,7 +30,7 @@ export function ToolCallDiv(props: ToolCallDivProps) {
}
return (
<ThreadDiv
<ToolCallDisplay
icon={getIcon(props.toolCallState.status)}
toolCall={props.toolCall}
toolCallState={props.toolCallState}
@ -39,6 +39,6 @@ export function ToolCallDiv(props: ToolCallDivProps) {
toolCall={props.toolCall}
toolCallState={props.toolCallState}
/>
</ThreadDiv>
</ToolCallDisplay>
);
}

View file

@ -1,8 +1,7 @@
export { exitEditMode } from "./exitEditMode";
export { gatherContext } from "./gatherContext";
export { streamThunkWrapper } from "./streamThunkWrapper";
export { resetStateForNewMessage } from "./resetStateForNewMessage";
export { streamNormalInput } from "./streamNormalInput";
export { streamResponseThunk } from "./streamResponse";
export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export { streamSlashCommand } from "./streamSlashCommand";
export { streamThunkWrapper } from "./streamThunkWrapper";

View file

@ -1,5 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, PromptLog } from "core";
import { ChatMessage } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { ToCoreProtocol } from "core/protocol";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectDefaultModel } from "../slices/configSlice";
import {
@ -10,98 +12,109 @@ import {
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { callTool } from "./callTool";
import { modelSupportsTools } from "core/llm/autodetect";
export const streamNormalInput = createAsyncThunk<
void,
ChatMessage[],
{
messages: ChatMessage[];
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
},
ThunkApiType
>("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => {
// Gather state
const state = getState();
const defaultModel = selectDefaultModel(state);
const toolSettings = state.ui.toolSettings;
const streamAborter = state.session.streamAborter;
const useTools = state.ui.useTools;
if (!defaultModel) {
throw new Error("Default model not defined");
}
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
// Send request
const gen = extra.ideMessenger.llmStreamChat(
defaultModel.title,
streamAborter.signal,
messages,
includeTools
? {
tools: state.config.config.tools.filter(
(tool) => toolSettings[tool.function.name] !== "disabled",
),
}
: {},
);
// Stream response
let next = await gen.next();
while (!next.done) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
>(
"chat/streamNormalInput",
async (
{ messages, legacySlashCommandData },
{ dispatch, extra, getState },
) => {
// Gather state
const state = getState();
const defaultModel = selectDefaultModel(state);
const toolSettings = state.ui.toolSettings;
const streamAborter = state.session.streamAborter;
const useTools = state.ui.useTools;
if (!defaultModel) {
throw new Error("Default model not defined");
}
dispatch(streamUpdate(next.value));
next = await gen.next();
}
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
// Attach prompt log
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
// Send request
const gen = extra.ideMessenger.llmStreamChat(
{
completionOptions: includeTools
? {
tools: state.config.config.tools.filter(
(tool) => toolSettings[tool.function.name] !== "disabled",
),
}
: {},
title: defaultModel.title,
messages,
legacySlashCommandData,
},
streamAborter.signal,
);
try {
if (state.session.mode === "chat") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {
prompt: next.value.prompt,
completion: next.value.completion,
modelProvider: defaultModel.provider,
modelTitle: defaultModel.title,
sessionId: state.session.id,
},
});
// Stream response
let next = await gen.next();
while (!next.done) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
}
// else if (state.session.mode === "edit") {
// extra.ideMessenger.post("devdata/log", {
// name: "editInteraction",
// data: {
// prompt: next.value.prompt,
// completion: next.value.completion,
// modelProvider: defaultModel.provider,
// modelTitle: defaultModel.title,
// },
// });
// }
} catch (e) {
console.error("Failed to send dev data interaction log", e);
}
}
// If it's a tool call that is automatically accepted, we should call it
const toolCallState = selectCurrentToolCall(getState());
if (toolCallState) {
dispatch(setToolGenerated());
if (
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission"
) {
const response = await dispatch(callTool());
unwrapResult(response);
dispatch(streamUpdate(next.value));
next = await gen.next();
}
}
});
// Attach prompt log
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
try {
if (state.session.mode === "chat") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {
prompt: next.value.prompt,
completion: next.value.completion,
modelProvider: defaultModel.provider,
modelTitle: defaultModel.title,
sessionId: state.session.id,
},
});
}
// else if (state.session.mode === "edit") {
// extra.ideMessenger.post("devdata/log", {
// name: "editInteraction",
// data: {
// prompt: next.value.prompt,
// completion: next.value.completion,
// modelProvider: defaultModel.provider,
// modelTitle: defaultModel.title,
// },
// });
// }
} catch (e) {
console.error("Failed to send dev data interaction log", e);
}
}
// If it's a tool call that is automatically accepted, we should call it
const toolCallState = selectCurrentToolCall(getState());
if (toolCallState) {
dispatch(setToolGenerated());
if (
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission"
) {
const response = await dispatch(callTool());
unwrapResult(response);
}
}
},
);

View file

@ -19,7 +19,6 @@ import { ThunkApiType } from "../store";
import { gatherContext } from "./gatherContext";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
import { streamNormalInput } from "./streamNormalInput";
import { streamSlashCommand } from "./streamSlashCommand";
import { streamThunkWrapper } from "./streamThunkWrapper";
import { updateFileSymbolsFromFiles } from "./updateFileSymbols";
@ -132,27 +131,30 @@ export const streamResponseThunk = createAsyncThunk<
let commandAndInput = getSlashCommandForInput(content, slashCommands);
if (!commandAndInput) {
unwrapResult(await dispatch(streamNormalInput(messages)));
unwrapResult(await dispatch(streamNormalInput({ messages })));
} else {
const [slashCommand, commandInput] = commandAndInput;
posthog.capture("step run", {
step_name: slashCommand.name,
params: {},
});
// if (slashCommand.name === "multifile-edit") {
// dispatch(setIsInMultifileEdit(true));
// }
await dispatch(
streamSlashCommand({
messages,
slashCommand,
input: commandInput,
historyIndex: inputIndex,
selectedCode,
contextItems: [],
}),
// TODO - handle non-legacy slash commands, update messages if relevant
// Pass around isFromConfigTs
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: {
command: slashCommand,
contextItems: selectedContextItems,
historyIndex: inputIndex,
input: commandInput,
selectedCode,
},
}),
),
);
}
}),

View file

@ -61,8 +61,7 @@ export const streamResponseAfterToolCall = createAsyncThunk<
const updatedHistory = getState().session.history;
const messages = constructMessages([...updatedHistory]);
const output = await dispatch(streamNormalInput(messages));
unwrapResult(output);
unwrapResult(await dispatch(streamNormalInput({ messages })));
}),
);
},

View file

@ -1,96 +0,0 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
ChatMessage,
ContextItemWithId,
RangeInFile,
SlashCommandDescription,
} from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { selectDefaultModel } from "../slices/configSlice";
import { abortStream, streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
export const streamSlashCommand = createAsyncThunk<
void,
{
messages: ChatMessage[];
slashCommand: SlashCommandDescription;
input: string;
historyIndex: number;
selectedCode: RangeInFile[];
contextItems: ContextItemWithId[];
},
ThunkApiType
>(
"chat/streamSlashCommand",
async (
{ messages, selectedCode, slashCommand, input, historyIndex, contextItems },
{ dispatch, getState, extra },
) => {
const state = getState();
const defaultModel = selectDefaultModel(state);
const isStreaming = state.session.isStreaming;
const streamAborter = state.session.streamAborter;
const toolSettings = state.ui.toolSettings;
if (!defaultModel) {
throw new Error("Default model not defined");
}
const useTools = state.ui.useTools;
const includeTools =
useTools &&
modelSupportsTools(defaultModel) &&
state.session.mode === "chat";
const modelTitle = defaultModel.title;
const checkActiveInterval = setInterval(() => {
if (!isStreaming) {
dispatch(abortStream());
clearInterval(checkActiveInterval);
}
}, 100);
for await (const update of extra.ideMessenger.streamRequest(
"command/run",
{
input,
history: messages,
modelTitle,
slashCommandName: slashCommand.name,
contextItems,
params: slashCommand.params,
historyIndex,
selectedCode,
completionOptions: includeTools
? {
// Temporarily commented out until slash commands are hooked up to the tool use feedback loop
// tools: state.config.config.tools.filter(
// (tool) => toolSettings[tool.function.name] !== "disabled",
// ),
}
: {},
},
streamAborter.signal,
)) {
if (!getState().session.isStreaming) {
dispatch(abortStream());
break;
}
for (const item of update) {
if (typeof item === "string") {
dispatch(
streamUpdate([
{
role: "assistant",
content: item,
},
]),
);
}
}
}
clearInterval(checkActiveInterval);
},
);