🚧 attempting proxy

This commit is contained in:
Nate Sesti 2023-12-10 00:11:30 -08:00
parent 24660df6db
commit d267676728
11 changed files with 1296 additions and 520 deletions

View file

@ -17,10 +17,12 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
};
const TOKEN_BUFFER_FOR_SAFETY = 350;
const PROXY_URL = "http://localhost:65433";
export {
DEFAULT_MAX_TOKENS,
DEFAULT_ARGS,
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_MAX_TOKENS,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -1,6 +1,6 @@
import { LLM, LLMOptions } from "..";
import { ModelProvider } from "../../config";
import { ChatMessage, CompletionOptions } from "../types";
import { CompletionOptions } from "../types";
class Ollama extends LLM {
static providerName: ModelProvider = "ollama";

File diff suppressed because it is too large Load diff

View file

@ -323,6 +323,8 @@
"devDependencies": {
"@nestjs/common": "^8.4.7",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/glob": "^8.0.0",
"@types/mocha": "^10.0.1",
"@types/node": "16.x",
@ -349,10 +351,14 @@
"@reduxjs/toolkit": "^1.9.3",
"axios": "^1.2.5",
"core": "file:../../core",
"cors": "^2.8.5",
"downshift": "^7.6.0",
"express": "^4.18.2",
"fkill": "^8.1.0",
"highlight.js": "^11.7.0",
"highlightable": "^1.3.0-beta.0",
"http-proxy": "^1.18.1",
"http-proxy-middleware": "^2.0.6",
"ncp": "^2.0.0",
"node-machine-id": "^1.1.12",
"posthog-node": "^3.1.2",

View file

@ -1,21 +1,14 @@
import * as vscode from "vscode";
import IdeProtocolClient from "../continueIdeClient";
import { getContinueServerUrl } from "../bridge";
import {
ContinueGUIWebviewViewProvider,
getSidebarContent,
} from "../debugPanel";
import {
getExtensionVersion,
startContinuePythonServer,
} from "./environmentSetup";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { registerAllCommands } from "../commands";
import registerQuickFixProvider from "../lang-server/codeActions";
import { getExtensionUri } from "../util/vscode";
import path from "path";
import { setupInlineTips } from "./inlineTips";
import { v4 } from "uuid";
import * as vscode from "vscode";
import { registerAllCommands } from "../commands";
import IdeProtocolClient from "../continueIdeClient";
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
import registerQuickFixProvider from "../lang-server/codeActions";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { getExtensionUri } from "../util/vscode";
import { setupInlineTips } from "./inlineTips";
import { startProxy } from "./proxy";
export let extensionContext: vscode.ExtensionContext | undefined = undefined;
export let ideProtocolClient: IdeProtocolClient;
@ -106,8 +99,6 @@ function showRefactorMigrationMessage() {
export async function activateExtension(context: vscode.ExtensionContext) {
extensionContext = context;
console.log("Using Continue version: ", getExtensionVersion());
try {
console.log(
"In workspace: ",
@ -127,15 +118,7 @@ export async function activateExtension(context: vscode.ExtensionContext) {
setupInlineTips(context);
showRefactorMigrationMessage();
(async () => {
// Start the server
await startContinuePythonServer();
console.log("Continue server started");
// Initialize IDE Protocol Client
const serverUrl = getContinueServerUrl();
ideProtocolClient = new IdeProtocolClient(serverUrl, context);
})();
ideProtocolClient = new IdeProtocolClient(context);
// Register Continue GUI as sidebar webview, and beginning a new session
const provider = new ContinueGUIWebviewViewProvider();
@ -149,4 +132,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
}
)
);
startProxy();
}

View file

@ -1,49 +1,7 @@
import { exec as execCb, spawn } from "child_process";
import fkill from "fkill";
import * as fs from "fs";
import fetch from "node-fetch";
import * as os from "os";
import * as path from "path";
import { finished } from "stream/promises";
import { promisify } from "util";
import * as vscode from "vscode";
import { getContinueServerUrl } from "../bridge";
import { capture } from "../extension";
import { getExtensionUri, getUniqueId } from "../util/vscode";
import request = require("request");
const exec = promisify(execCb);
async function runCommand(cmd: string): Promise<[string, string | undefined]> {
var stdout = "";
var stderr = "";
try {
var { stdout, stderr } = await exec(cmd, {
shell: process.platform === "win32" ? "powershell.exe" : undefined,
});
} catch (e: any) {
stderr = e.stderr;
stdout = e.stdout;
}
const stderrOrUndefined = stderr === "" ? undefined : stderr;
return [stdout, stderrOrUndefined];
}
async function checkServerRunning(serverUrl: string): Promise<boolean> {
// Check if already running by calling /health
try {
const response = await fetch(`${serverUrl}/health`);
if (response.status === 200) {
console.log("Continue python server already running");
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
export function getContinueGlobalPath(): string {
// This is ~/.continue on mac/linux
@ -75,14 +33,6 @@ export function getConfigJsonPath(): string {
return path.join(getContinueGlobalPath(), "config.json");
}
function serverPath(): string {
const sPath = path.join(getContinueGlobalPath(), "server");
if (!fs.existsSync(sPath)) {
fs.mkdirSync(sPath);
}
return sPath;
}
export function devDataPath(): string {
const sPath = path.join(getContinueGlobalPath(), "dev_data");
if (!fs.existsSync(sPath)) {
@ -91,401 +41,7 @@ export function devDataPath(): string {
return sPath;
}
function serverVersionPath(): string {
return path.join(serverPath(), "server_version.txt");
}
function serverBinaryPath(): string {
let binaryPath = path.join(
serverPath(),
"exe",
`continue_server${os.platform() === "win32" ? ".exe" : ""}`
);
// If it's a directory, this is a directory mode pyinstaller binary
if (fs.existsSync(binaryPath) && fs.lstatSync(binaryPath).isDirectory()) {
binaryPath = path.join(binaryPath, "continue_server");
}
return binaryPath;
}
export function getExtensionVersion() {
const extension = vscode.extensions.getExtension("continue.continue");
return extension?.packageJSON.version || "";
}
// Returns whether a server of the current version is already running
async function checkOrKillRunningServer(
serverUrl: string,
deleteBinary: boolean
): Promise<boolean> {
const serverRunning = await checkServerRunning(serverUrl);
let shouldKillAndReplace = true;
if (fs.existsSync(serverVersionPath())) {
const serverVersion = fs.readFileSync(serverVersionPath(), "utf8");
if (serverVersion === getExtensionVersion() && serverRunning) {
// The current version is already up and running, no need to continue
console.log("Continue server of correct version already running");
shouldKillAndReplace = false;
}
}
// Kill the server if it is running an old version
if (shouldKillAndReplace) {
console.log("Killing server from old version of Continue");
try {
await fkill(":65432", { force: true });
} catch (e: any) {
if (!e.message.includes("Process doesn't exist")) {
console.log("Failed to kill old server:", e);
// Try again, on Windows. This time with taskkill
if (os.platform() === "win32") {
try {
await runCommand(`taskkill /F /IM continue_server.exe`);
} catch (e: any) {
console.log(
"Failed to kill old server second time on windows with taskkill:",
e
);
}
}
}
}
if (fs.existsSync(serverVersionPath())) {
fs.unlinkSync(serverVersionPath());
}
if (deleteBinary) {
// Optionally, delete the server binary
const serverBinary = serverBinaryPath();
if (fs.existsSync(serverBinary)) {
fs.unlinkSync(serverBinary);
}
}
}
return serverRunning && !shouldKillAndReplace;
}
function ensureDirectoryExistence(filePath: string) {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
function isPreviewExtension() {
// If the extension minor version is odd, it is a preview version
const extensionVersion = getExtensionVersion();
if (!extensionVersion || extensionVersion === "") {
return false;
}
const extensionVersionSplit = extensionVersion.split(".");
const extensionMinorVersion = extensionVersionSplit[1];
return parseInt(extensionMinorVersion) % 2 === 1;
}
export async function downloadFromS3(
bucket: string,
fileName: string,
destination: string,
region: string,
useBackupUrl: boolean = false
) {
ensureDirectoryExistence(destination);
const file = fs.createWriteStream(destination);
const download = request({
url: useBackupUrl
? `https://s3.continue.dev/${fileName}`
: `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`,
});
return new Promise(async (resolve, reject) => {
const handleErr = () => {
if (fs.existsSync(destination)) {
fs.unlink(destination, () => {});
}
};
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
handleErr();
reject(new Error("No body returned when downloading from S3 bucket"));
}
});
download.on("error", (err: any) => {
handleErr();
reject(err);
});
download.pipe(file);
await finished(download);
resolve(null);
});
}
function includedBinaryPath(): string {
const extensionPath = getExtensionUri().fsPath;
let binaryPath = path.join(
extensionPath,
"exe",
`continue_server${os.platform() === "win32" ? ".exe" : ""}`
);
if (fs.existsSync(binaryPath) && fs.lstatSync(binaryPath).isDirectory()) {
binaryPath = path.join(binaryPath, "continue_server");
}
return binaryPath;
}
function runExecutable(path: string) {
console.log("---- Starting Continue server ----");
let attempts = 0;
let maxAttempts = 5;
let delay = 1000; // Delay between each attempt in milliseconds
const spawnChild = () => {
const retry = (e: any) => {
attempts++;
console.log(`Error caught: ${e}.\n\nRetrying attempt ${attempts}...`);
setTimeout(spawnChild, delay);
};
try {
// NodeJS bug requires not using detached on Windows, otherwise windowsHide is ineffective
// Otherwise, detach is preferable
const windowsSettings = {
windowsHide: true,
};
const macLinuxSettings = {
detached: true,
stdio: "ignore",
};
const settings: any =
os.platform() === "win32" ? windowsSettings : macLinuxSettings;
// Spawn the server
const child = spawn(path, settings);
// Either unref to avoid zombie process, or listen to events because you can
if (os.platform() === "win32") {
child.stdout.on("data", (data: any) => {
console.log(`stdout: ${data}`);
});
child.stderr.on("data", (data: any) => {
console.log(`stderr: ${data}`);
});
child.on("error", (err: any) => {
if (attempts < maxAttempts) {
retry(err);
} else {
console.error("Failed to start subprocess.", err);
}
});
child.on("exit", (code: any, signal: any) => {
console.log("Subprocess exited with code", code, signal);
});
child.on("close", (code: any, signal: any) => {
console.log("Subprocess closed with code", code, signal);
});
} else {
child.unref();
}
} catch (e: any) {
if (attempts < maxAttempts) {
retry(e);
} else {
throw e;
}
}
};
spawnChild();
// Write the current version of vscode extension to a file called server_version.txt
fs.writeFileSync(serverVersionPath(), getExtensionVersion());
}
async function setupWithS3Download(redownload: boolean, serverUrl: string) {
// Check if server is already running
if (redownload && (await checkOrKillRunningServer(serverUrl, true))) {
console.log("Continue server already running");
return;
}
// Download the server executable
const bucket = "continue-server-binaries";
const fileName =
os.platform() === "win32"
? "windows/continue_server.exe"
: os.platform() === "darwin"
? os.arch() === "arm64"
? "apple-silicon/continue_server"
: "mac/continue_server"
: "linux/continue_server";
const destination = serverBinaryPath();
// First, check if the server is already downloaded
let shouldDownload = true;
if (fs.existsSync(destination) && redownload) {
// Check if the server is the correct version
if (fs.existsSync(serverVersionPath())) {
const serverVersion = fs.readFileSync(serverVersionPath(), "utf8");
if (serverVersion === getExtensionVersion()) {
// The current version is already up and running, no need to continue
console.log("Continue server already downloaded");
shouldDownload = false;
} else {
console.log("Old version of the server downloaded");
if (fs.existsSync(destination)) {
fs.unlinkSync(destination);
}
}
} else {
console.log("Old version of the server downloaded");
if (fs.existsSync(destination)) {
fs.unlinkSync(destination);
}
}
}
if (shouldDownload && redownload) {
let timeout = setTimeout(() => {
vscode.window.showErrorMessage(
`It looks like the Continue server is taking a while to download. If this persists, you can manually download the binary or run it from source: https://continue.dev/docs/troubleshooting#run-the-server-manually.`
);
}, 35_000);
let download = vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Installing Continue server...",
cancellable: false,
},
async () => {
try {
await downloadFromS3(
bucket,
`${isPreviewExtension() ? "preview/" : ""}${fileName}`,
destination,
"us-west-1",
false
);
} catch (e: any) {
console.log("Failed to download from primary url, trying backup url");
capture({
distinctId: getUniqueId(),
event: "first_binary_download_failed",
properties: {
extensionVersion: getExtensionVersion(),
os: os.platform(),
arch: os.arch(),
error_msg: e.message,
},
});
try {
await downloadFromS3(
bucket,
`${isPreviewExtension() ? "preview/" : ""}${fileName}`,
destination,
"us-west-1",
true
);
} catch (e: any) {
capture({
distinctId: getUniqueId(),
event: "second_binary_download_failed",
properties: {
extensionVersion: getExtensionVersion(),
os: os.platform(),
arch: os.arch(),
error_msg: e.message,
},
});
throw e;
}
}
}
);
try {
await download;
console.log("Downloaded server executable at ", destination);
clearTimeout(timeout);
} catch (e: any) {
const errText = `Failed to download Continue server from S3: ${e}`;
vscode.window.showErrorMessage(errText);
}
}
// Get name of the corresponding executable for platform
if (os.platform() === "darwin") {
// Add necessary permissions
fs.chmodSync(destination, 0o7_5_5);
await runCommand(`xattr -dr com.apple.quarantine ${destination}`);
} else if (os.platform() === "linux") {
// Add necessary permissions
fs.chmodSync(destination, 0o7_5_5);
}
// Validate that the file exists
console.log("Looking for file at ", destination);
if (!fs.existsSync(destination)) {
// List the contents of the folder
const files = fs.readdirSync(
path.join(getExtensionUri().fsPath, "server", "exe")
);
console.log("Files in server folder: ", files);
const errText = `- Failed to install Continue server.`;
vscode.window.showErrorMessage(errText);
console.log("6: throwing error message: ", errText);
throw new Error(errText);
}
// Run the executable
runExecutable(destination);
}
export async function startContinuePythonServer(redownload: boolean = true) {
// Check vscode settings for whether server is being run manually
const manuallyRunningServer =
vscode.workspace
.getConfiguration("continue")
.get<boolean>("manuallyRunningServer") || false;
const serverUrl = getContinueServerUrl();
if (
(serverUrl !== "http://localhost:65432" &&
serverUrl !== "http://127.0.0.1:65432") ||
manuallyRunningServer
) {
console.log("Continue server is being run manually, skipping start");
return;
}
// If on Apple Silicon, download binary from S3
// const isAppleSilicon = os.platform() === "darwin" && os.arch() === "arm64";
// if (isAppleSilicon) {
// await setupWithS3Download(redownload, serverUrl);
// return;
// }
// Check if current server version is already running
if (redownload && (await checkOrKillRunningServer(serverUrl, false))) {
console.log("Continue server already running");
return;
}
// Otherwise, use the binary installed with the extension
if (!fs.existsSync(includedBinaryPath())) {
throw new Error(
`Continue server binary not found at ${includedBinaryPath()}`
);
}
runExecutable(includedBinaryPath());
}

View file

@ -0,0 +1,34 @@
import cors from "cors";
import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
const PROXY_PORT = 65433;
const app = express();
app.use(cors());
app.use("/", (req, res, next) => {
// Extract the target from the request URL
// const { protocol, host } = url.parse(req.url);
// const target = `${protocol}//${host}`;
const target = "http://localhost:11434";
// Create a new proxy middleware for this request
const proxy = createProxyMiddleware({
target,
changeOrigin: true,
ws: true,
pathRewrite: {
"^/": "/api/generate",
},
});
// Call the middleware
proxy(req, res, next);
});
export function startProxy() {
console.log("Starting proxy");
app.listen(PROXY_PORT, () => {
console.log(`Proxy server is running on port ${PROXY_PORT}`);
});
}

View file

@ -24,7 +24,7 @@ const continueVirtualDocumentScheme = "continue";
class IdeProtocolClient {
private readonly context: vscode.ExtensionContext;
constructor(serverUrl: string, context: vscode.ExtensionContext) {
constructor(context: vscode.ExtensionContext) {
this.context = context;
const windowInfo = {
window_id: windowId,
@ -34,7 +34,6 @@ class IdeProtocolClient {
name: "vscode",
version: vscode.version,
remote_name: vscode.env.remoteName,
server_url: serverUrl,
},
};

View file

@ -48,6 +48,12 @@ export function getSidebarContent(
enableScripts: true,
localResourceRoots: [vscode.Uri.joinPath(extensionUri, "gui")],
enableCommandUris: true,
portMapping: [
{
webviewPort: 65433,
extensionHostPort: 65433,
},
],
};
const nonce = getNonce();

View file

@ -1,26 +0,0 @@
import { test, describe } from "mocha";
import * as assert from "assert";
import { getContinueServerUrl } from "../bridge";
import { startContinuePythonServer } from "../activation/environmentSetup";
import fetch from "node-fetch";
describe("Can start python server", () => {
test("Can start python server in under 80 seconds", async function () {
const allowedTime = 80_000;
this.timeout(allowedTime + 10_000);
console.log("Starting server in test...");
await startContinuePythonServer(false);
console.log("Server started.");
// If successful, the server is started by the extension while we wait
await new Promise((resolve) => setTimeout(resolve, allowedTime));
// Check if server is running
const serverUrl = getContinueServerUrl();
console.log("Server URL: ", serverUrl);
const response = await fetch(`${serverUrl}/health`);
assert.equal(response.status, 200);
});
});

View file

@ -18,7 +18,6 @@ function useHistory() {
}
async function saveSession() {
console.log("HIStory", state);
if (state.history.length === 0) return;
const sessionInfo: PersistedSessionInfo = {
history: state.history,