✨ slash commands that run in NodeJs side

This commit is contained in:
Nate Sesti 2023-12-27 19:30:34 -05:00
parent 89e68b4d39
commit 8d2e8414e6
9 changed files with 101 additions and 21 deletions

View file

@ -24,7 +24,7 @@ declare global {
region?: string;
projectId?: string;
_fetch?: (input: any, init?: RequestInit) => Promise<any>;
_fetch?: (input: any, init?: any) => Promise<any>;
complete(prompt: string, options?: LLMFullCompletionOptions): Promise<string>;
@ -148,6 +148,7 @@ declare global {
export interface ChatHistoryItem {
message: ChatMessage;
editorState?: any;
contextItems: ContextItemWithId[];
promptLogs?: [string, string][]; // [prompt, completion]
}
@ -267,6 +268,10 @@ declare global {
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
// If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs
// You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser
runInNodeJs?: boolean;
}
// Config
@ -302,6 +307,7 @@ declare global {
| "anthropic"
| "chatml"
| "none"
| "openchat"
| "deepseek";
type ModelProvider =
@ -319,7 +325,8 @@ declare global {
| "lmstudio"
| "llamafile"
| "gemini"
| "mistral";
| "mistral"
| "bedrock";
export type ModelName =
// OpenAI
@ -362,7 +369,7 @@ declare global {
verifySsl?: boolean;
caBundlePath?: string | string[];
proxy?: string;
headers?: Record<string, string>;
headers?: { [key: string]: string };
}
export interface StepWithParams {
@ -483,6 +490,7 @@ declare global {
userToken?: string;
}
}
export {};

View file

@ -103,5 +103,11 @@ export async function* ideStreamRequest(
await new Promise((resolve) => setTimeout(resolve, 50));
}
if (buffer.length > index) {
const chunk = buffer.slice(index);
index = buffer.length;
yield chunk;
}
clearTimeout(staleTimeout);
}

4
core/index.d.ts vendored
View file

@ -266,6 +266,10 @@ export interface SlashCommand {
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
// If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs
// You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser
runInNodeJs?: boolean;
}
// Config

View file

@ -11,7 +11,7 @@ import { ideProtocolClient, windowId } from "./activation/activate";
import { getContinueServerUrl } from "./bridge";
import historyManager from "./history";
import { VsCodeIde } from "./ideProtocol";
import { llmFromTitle } from "./loadConfig";
import { configHandler, llmFromTitle } from "./loadConfig";
import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
let sockets: { [url: string]: io.Socket | undefined } = {};
@ -436,6 +436,39 @@ export function getSidebarContent(
respond({ content: completion });
break;
}
case "runNodeJsSlashCommand": {
const {
input,
history,
modelTitle,
slashCommandName,
contextItems,
params,
} = data.message;
const config = await configHandler.loadConfig(ide);
const llm = await llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
for await (const update of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: () => {},
})) {
respond({ content: update });
}
respond({ done: true });
break;
}
}
} catch (e) {
vscode.window.showErrorMessage(

View file

@ -32,7 +32,7 @@ async function buildConfigTs(browser: boolean) {
platform: browser ? "browser" : "node",
format: browser ? "esm" : "cjs",
outfile: getConfigJsPath(!browser),
external: ["fetch"],
external: ["fetch", "fs", "path", "os", "child_process"],
});
} catch (e) {
console.log(e);

View file

@ -62,7 +62,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌘ ⇧ M",
windows: "⌃ ⇧ M",
description: "Edit Highlighted Code",
description: "Ask Follow-Up about Highlighted Code",
},
{
mac: "⌘ ⇧ ⏎",

View file

@ -125,6 +125,9 @@ function TipTapEditor(props: TipTapEditorProps) {
const firstResultsRef = useUpdatingRef(firstResults);
const historyLengthRef = useUpdatingRef(historyLength);
const onEnterRef = useUpdatingRef(props.onEnter);
const availableSlashCommandsRef = useUpdatingRef(
props.availableSlashCommands
);
const editor = useEditor({
extensions: [
@ -190,7 +193,7 @@ function TipTapEditor(props: TipTapEditorProps) {
class: "mention",
},
suggestion: getCommandSuggestion(
props.availableSlashCommands,
availableSlashCommandsRef,
onClose,
onOpen
),

View file

@ -157,13 +157,13 @@ export function getMentionSuggestion(
}
export function getCommandSuggestion(
availableSlashCommands: ComboBoxItem[],
availableSlashCommandsRef: MutableRefObject<ComboBoxItem[]>,
onClose: () => void,
onOpen: () => void
) {
const items = ({ query }) => {
return (
availableSlashCommands?.filter((slashCommand) => {
availableSlashCommandsRef.current?.filter((slashCommand) => {
const sc = slashCommand.title.substring(1).toLowerCase();
const iv = query.toLowerCase();
return sc.startsWith(iv);

View file

@ -3,6 +3,7 @@ import { Dispatch } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/react";
import { ChatHistory, ChatHistoryItem, ChatMessage, SlashCommand } from "core";
import { ExtensionIde } from "core/ide";
import { ideStreamRequest } from "core/ide/messaging";
import { constructMessages } from "core/llm/constructMessages";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef } from "react";
@ -70,26 +71,51 @@ function useChatHandler(dispatch: Dispatch) {
return [slashCommand, input];
};
async function* _streamSlashCommandFromVsCode(
messages: ChatMessage[],
slashCommand: SlashCommand,
input: string
): AsyncGenerator<string> {
const modelTitle = defaultModel.title;
for await (const update of ideStreamRequest("runNodeJsSlashCommand", {
input,
history: messages,
modelTitle,
slashCommandName: slashCommand.name,
contextItems,
params: slashCommand.params,
})) {
yield update;
}
}
async function _streamSlashCommand(
messages: ChatMessage[],
slashCommand: SlashCommand,
input: string
) {
const sdk = {
input,
history: messages,
ide: new ExtensionIde(),
llm: defaultModel,
addContextItem: (item) => {
dispatch(addContextItems([item]));
},
contextItems,
params: slashCommand.params,
};
let generator: AsyncGenerator<string>;
if (slashCommand.runInNodeJs) {
generator = _streamSlashCommandFromVsCode(messages, slashCommand, input);
} else {
const sdk = {
input,
history: messages,
ide: new ExtensionIde(),
llm: defaultModel,
addContextItem: (item) => {
dispatch(addContextItems([item]));
},
contextItems,
params: slashCommand.params,
};
generator = slashCommand.run(sdk);
}
// TODO: if the model returned fast enough it would immediately break
// Ideally you aren't trusting that results of dispatch show up before the first yield
for await (const update of slashCommand.run(sdk)) {
for await (const update of generator) {
if (!activeRef.current) {
break;
}