API tokens set through global Vsc settings

This commit is contained in:
Nate Sesti 2023-06-03 11:33:05 -04:00
parent 917ba983d6
commit b2fbe075b5
8 changed files with 64 additions and 45 deletions

View file

@ -11,7 +11,6 @@ from .observation import Observation
from ..server.ide_protocol import AbstractIdeProtocolServer
from .main import History, Step
from ..steps.core.core import *
from .env import get_env_var, make_sure_env_exists
class Autopilot:
@ -105,24 +104,7 @@ class ContinueSDK:
return await self.run_step(FileSystemEditStep(edit=DeleteDirectory(path=path)))
async def get_user_secret(self, env_var: str, prompt: str) -> str:
make_sure_env_exists()
val = None
while val is None:
try:
val = get_env_var(env_var)
if val is not None:
return val
except:
pass
server_dir = os.getcwd()
env_path = os.path.join(server_dir, ".env")
await self.ide.setFileOpen(env_path)
await self.append_to_file(env_path, f'\n{env_var}="<ENTER SECRET HERE>"')
await self.run_step(WaitForUserConfirmationStep(prompt=prompt))
val = get_env_var(env_var)
return val
return await self.ide.getUserSecret(env_var)
async def get_config(self) -> ContinueConfig:
dir = await self.ide.getWorkspaceDirectory()

View file

@ -40,46 +40,42 @@ Server.handle_exit = AppStatus.handle_exit
class FileEditsUpdate(BaseModel):
messageType: str = "fileEdits"
fileEdits: List[FileEditWithFullContents]
class OpenFilesResponse(BaseModel):
messageType: str = "openFiles"
openFiles: List[str]
class HighlightedCodeResponse(BaseModel):
messageType: str = "highlightedCode"
highlightedCode: List[RangeInFile]
class ShowSuggestionRequest(BaseModel):
messageType: str = "showSuggestion"
suggestion: FileEdit
class ShowSuggestionResponse(BaseModel):
messageType: str = "showSuggestion"
suggestion: FileEdit
accepted: bool
class ReadFileResponse(BaseModel):
messageType: str = "readFile"
contents: str
class EditFileResponse(BaseModel):
messageType: str = "editFile"
fileEdit: FileEditWithFullContents
class WorkspaceDirectoryResponse(BaseModel):
messageType: str = "workspaceDirectory"
workspaceDirectory: str
class GetUserSecretResponse(BaseModel):
value: str
T = TypeVar("T", bound=BaseModel)
@ -114,7 +110,7 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
fileEdits = list(
map(lambda d: FileEditWithFullContents.parse_obj(d), data["fileEdits"]))
self.onFileEdits(fileEdits)
elif message_type in ["highlightedCode", "openFiles", "readFile", "editFile", "workspaceDirectory"]:
elif message_type in ["highlightedCode", "openFiles", "readFile", "editFile", "workspaceDirectory", "getUserSecret"]:
self.sub_queue.post(message_type, data)
else:
raise ValueError("Unknown message type", message_type)
@ -183,31 +179,31 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
# Request information. Session doesn't matter.
async def getOpenFiles(self) -> List[str]:
resp = await self._send_and_receive_json({
"messageType": "openFiles"
}, OpenFilesResponse, "openFiles")
resp = await self._send_and_receive_json({}, OpenFilesResponse, "openFiles")
return resp.openFiles
async def getWorkspaceDirectory(self) -> str:
resp = await self._send_and_receive_json({
"messageType": "workspaceDirectory"
}, WorkspaceDirectoryResponse, "workspaceDirectory")
resp = await self._send_and_receive_json({}, WorkspaceDirectoryResponse, "workspaceDirectory")
return resp.workspaceDirectory
async def getHighlightedCode(self) -> List[RangeInFile]:
resp = await self._send_and_receive_json({
"messageType": "highlightedCode"
}, HighlightedCodeResponse, "highlightedCode")
resp = await self._send_and_receive_json({}, HighlightedCodeResponse, "highlightedCode")
return resp.highlightedCode
async def readFile(self, filepath: str) -> str:
"""Read a file"""
resp = await self._send_and_receive_json({
"messageType": "readFile",
"filepath": filepath
}, ReadFileResponse, "readFile")
return resp.contents
async def getUserSecret(self, key: str) -> str:
"""Get a user secret"""
resp = await self._send_and_receive_json({
"key": key
}, GetUserSecretResponse, "getUserSecret")
return resp.value
async def saveFile(self, filepath: str):
"""Save a file"""
await self._send_json("saveFile", {
@ -222,7 +218,6 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
async def editFile(self, edit: FileEdit) -> FileEditWithFullContents:
"""Edit a file"""
resp = await self._send_and_receive_json({
"messageType": "editFile",
"edit": edit.dict()
}, EditFileResponse, "editFile")
return resp.fileEdit

View file

@ -78,3 +78,7 @@ class AbstractIdeProtocolServer(ABC):
@abstractmethod
async def saveFile(self, filepath: str):
"""Save a file"""
@abstractmethod
async def getUserSecret(self, key: str):
"""Get a user secret"""

View file

@ -205,4 +205,5 @@ class WaitForUserConfirmationStep(Step):
async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:
self._description = self.prompt
resp = await sdk.wait_for_user_input()
self.hide = True
return TextObservation(text=resp)

View file

@ -190,7 +190,7 @@ class FasterEditHighlightedCodeStep(Step):
class StarCoderEditHighlightedCodeStep(Step):
user_input: str
name: str = "Editing code"
name: str = "Editing Code"
hide = False
_prompt: str = "<commit_before>{code}<commit_msg>{user_request}<commit_after>"

View file

@ -39,6 +39,16 @@
"type": "string",
"default": "http://localhost:8000",
"description": "The URL of the Continue server to use."
},
"continue.OPENAI_API_KEY": {
"type": "string",
"default": "",
"description": "The OpenAI API key to use for code generation."
},
"continue.HUGGING_FACE_TOKEN": {
"type": "string",
"default": "",
"description": "The Hugging Face API token to use for code generation."
}
}
},

View file

@ -114,12 +114,12 @@ function StepContainer(props: StepContainerProps) {
hidden={props.historyNode.step.hide as any}
>
<GradientBorder
className="m-2 overflow-hidden cursor-pointer"
onClick={() => setOpen((prev) => !prev)}
className="m-2 overflow-hidden"
// onClick={() => setOpen((prev) => !prev)}
>
<StepContainerDiv open={open}>
<HeaderDiv>
<h4 className="m-2 cursor-pointer">
<h4 className="m-2">
{open ? (
<ChevronDown size="1.4em" />
) : (
@ -127,14 +127,14 @@ function StepContainer(props: StepContainerProps) {
)}
{props.historyNode.step.name as any}:
</h4>
<HeaderButton
{/* <HeaderButton
onClick={(e) => {
e.stopPropagation();
props.onReverse();
}}
>
<Backward size="1.6em" onClick={props.onReverse}></Backward>
</HeaderButton>
</HeaderButton> */}
</HeaderDiv>
<ReactMarkdown key={1} className="overflow-scroll">

View file

@ -74,6 +74,12 @@ class IdeProtocolClient {
this.messenger?.send("workspaceDirectory", {
workspaceDirectory: this.getWorkspaceDirectory(),
});
break;
case "getUserSecret":
this.messenger?.send("getUserSecret", {
value: await this.getUserSecret(data.key),
});
break;
case "openFiles":
this.messenger?.send("openFiles", {
openFiles: this.getOpenFiles(),
@ -130,6 +136,27 @@ class IdeProtocolClient {
openEditorAndRevealRange(filepath, undefined, vscode.ViewColumn.One);
}
async getUserSecret(key: string) {
// Check if secret already exists in VS Code settings (global)
let secret = vscode.workspace.getConfiguration("continue").get(key);
if (secret && secret !== "") return secret;
// If not, ask user for secret
while (typeof secret === "undefined" || secret === "") {
secret = await vscode.window.showInputBox({
prompt: `Enter secret for ${key}`,
password: true,
});
}
// Add secret to VS Code settings
vscode.workspace
.getConfiguration("continue")
.update(key, secret, vscode.ConfigurationTarget.Global);
return secret;
}
// ------------------------------------ //
// Initiate Request