use continue sdk

This commit is contained in:
Nate 2025-07-15 10:32:53 -07:00
parent 2d2eda9f10
commit 02fcd4668b
9 changed files with 109 additions and 54 deletions

26
package-lock.json generated
View file

@ -11,7 +11,7 @@
"dependencies": {
"@continuedev/config-yaml": "^1.0.96",
"@continuedev/openai-adapters": "1.0.46-beta",
"@continuedev/sdk": "^0.0.12",
"@continuedev/sdk": "file:../continue/packages/continue-sdk/typescript",
"@modelcontextprotocol/sdk": "^1.9.0",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
@ -59,6 +59,21 @@
"tsx": "^4.20.3"
}
},
"../continue/packages/continue-sdk/typescript": {
"name": "@continuedev/sdk",
"version": "0.0.12",
"license": "Apache-2.0",
"dependencies": {
"openai": "^4.96.2"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"dotenv": "^16.5.0",
"jest": "^29.7.0",
"ts-jest": "^29.1.2",
"typescript": "^5.0.0"
}
},
"node_modules/@alcalzone/ansi-tokenize": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz",
@ -1436,13 +1451,8 @@
}
},
"node_modules/@continuedev/sdk": {
"version": "0.0.12",
"resolved": "https://registry.npmjs.org/@continuedev/sdk/-/sdk-0.0.12.tgz",
"integrity": "sha512-iWir05oFMf599GUDY98sgj9PPnMVXNeHs3OcH1FdmaJVZWuH+rreqLzr8H/NYvw9jPqbsdf+eeCjq+H+4l+eSA==",
"license": "Apache-2.0",
"dependencies": {
"openai": "^4.96.2"
}
"resolved": "../continue/packages/continue-sdk/typescript",
"link": true
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",

View file

@ -34,7 +34,7 @@
"dependencies": {
"@continuedev/config-yaml": "^1.0.96",
"@continuedev/openai-adapters": "1.0.46-beta",
"@continuedev/sdk": "^0.0.12",
"@continuedev/sdk": "file:../continue/packages/continue-sdk/typescript",
"@modelcontextprotocol/sdk": "^1.9.0",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",

View file

@ -1,6 +1,6 @@
export interface CommandLineArgs {
isHeadless: boolean;
configPath: string;
configPath?: string;
prompt?: string; // Optional prompt argument
resume?: boolean; // Resume from last session
}
@ -15,7 +15,6 @@ export function parseArgs(): CommandLineArgs {
// Default values
const result: CommandLineArgs = {
isHeadless: false,
configPath: "nate/default-assistant",
};
// Parse flags

View file

@ -132,9 +132,12 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string {
*/
async function refreshToken(refreshToken: string): Promise<AuthConfig> {
try {
const response = await axios.post(`${env.apiBase}/auth/refresh`, {
refreshToken,
});
const response = await axios.post(
new URL("auth/refresh", env.apiBase).toString(),
{
refreshToken,
}
);
const { accessToken, refreshToken: newRefreshToken, user } = response.data;

View file

@ -3,7 +3,7 @@ import dotenv from "dotenv";
dotenv.config();
export const env = {
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev",
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev/",
workOsClientId: "client_01J0FW6XN8N2XJAECF7NE0Y65J",
appUrl: "https://hub.continue.dev",
};

View file

@ -1,18 +1,21 @@
#!/usr/bin/env node
import { AssistantUnrolled } from "@continuedev/config-yaml";
import {
BaseLlmApi,
constructLlmApi,
LLMConfig,
} from "@continuedev/openai-adapters";
import { Assistant } from "@continuedev/sdk";
import {
Configuration,
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { parseArgs } from "./args.js";
import { ensureAuthenticated } from "./auth/ensureAuth.js";
import { AuthConfig, loadAuthConfig } from "./auth/workos.js";
import { initializeContinueSDK } from "./continueSDK.js";
import { introMessage } from "./intro.js";
import { configureLogger } from "./logger.js";
import { MCPService } from "./mcp.js";
@ -29,10 +32,10 @@ const args = parseArgs();
configureLogger(args.isHeadless);
function getLlmApi(
assistant: Assistant,
assistant: AssistantUnrolled,
authConfig: AuthConfig
): [BaseLlmApi, string] {
const model = assistant.config.models?.find((model) =>
const model = assistant.models?.find((model) =>
model?.roles?.includes("chat")
);
@ -77,11 +80,49 @@ function getLlmApi(
async function loadAssistant(
accessToken: string | undefined,
configPath: string
): Promise<Assistant> {
const continueSdk = await initializeContinueSDK(accessToken, configPath);
config: string | undefined,
organizationId: string | undefined
): Promise<AssistantUnrolled> {
const apiClient = new DefaultApi(
new Configuration({
accessToken,
})
);
return continueSdk.assistant;
if (!config) {
// Fall back to listing assistants and taking the first one
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
organizationId,
});
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
} else if (config.startsWith(".") || config.startsWith("/")) {
// Load from file
throw new Error("Loading from file is not supported yet.");
// return loadAssistantFromFile(config);
} else {
// Load from slug
const [ownerSlug, packageSlug] = config.split("/");
const resp = await apiClient.getAssistant({
ownerSlug,
packageSlug,
alwaysUseProxy: "false",
organizationId,
});
const result = resp.configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
}
async function chat() {
@ -123,17 +164,18 @@ async function chat() {
// }
// Initialize ContinueSDK and MCPService once
const assistant = await loadAssistant(
const config = await loadAssistant(
authConfig.accessToken,
args.configPath
args.configPath,
undefined
);
const [llmApi, model] = getLlmApi(assistant, authConfig);
const mcpService = await MCPService.create(assistant.config);
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = await MCPService.create(config);
// If not in headless mode, start the TUI chat (default)
if (!args.isHeadless) {
await startTUIChat(
assistant,
config,
llmApi,
model,
mcpService,
@ -144,7 +186,7 @@ async function chat() {
}
// Show intro message for headless mode
introMessage(assistant, mcpService);
introMessage(config, model, mcpService);
// Rules
let chatHistory: ChatCompletionMessageParam[] = [];
@ -162,7 +204,7 @@ async function chat() {
// If no session loaded or not resuming, initialize with system message
if (chatHistory.length === 0) {
const rulesSystemMessage = assistant.systemMessage;
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
const systemMessage = constructSystemMessage(rulesSystemMessage);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
@ -185,7 +227,7 @@ async function chat() {
isFirstMessage = false;
// Handle slash commands
const commandResult = handleSlashCommands(userInput, assistant.config);
const commandResult = handleSlashCommands(userInput, config);
if (commandResult) {
if (commandResult.exit) {
break;

View file

@ -1,4 +1,5 @@
import { Assistant, type AssistantConfig } from "@continuedev/sdk";
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import { CONTINUE_ASCII_ART } from "./asciiArt.js";
import { MCPService } from "./mcp.js";
@ -13,16 +14,18 @@ export function loadSystemMessage(
.join("\n");
}
export function introMessage(assistant: Assistant, mcpService: MCPService) {
const assistantConfig = assistant.config;
export function introMessage(
config: AssistantUnrolled,
modelName: string,
mcpService: MCPService
) {
const mcpTools = mcpService.getTools() ?? [];
const mcpPrompts = mcpService.getPrompts() ?? [];
console.info(chalk.cyan(CONTINUE_ASCII_ART));
console.info(`\n${chalk.bold.blue(`Agent: ${assistantConfig.name}\n`)}`);
console.info(`${chalk.yellow("Model:")} ${assistant.getModel()}\n`);
console.info(`\n${chalk.bold.blue(`Agent: ${config.name}\n`)}`);
console.info(`${chalk.yellow("Model:")} ${modelName}\n`);
console.info(chalk.yellow("Tools:"));
getAllTools().forEach((tool) => {
@ -44,7 +47,7 @@ export function introMessage(assistant: Assistant, mcpService: MCPService) {
console.info(
`- ${chalk.green("/whoami")}: Check who you're currently logged in as`
);
for (const prompt of assistantConfig.prompts ?? []) {
for (const prompt of config.prompts ?? []) {
console.info(`- /${prompt?.name}: ${prompt?.description}`);
}
for (const prompt of mcpPrompts) {
@ -52,15 +55,13 @@ export function introMessage(assistant: Assistant, mcpService: MCPService) {
}
console.info("");
if (assistantConfig.rules?.length) {
console.info(
chalk.yellow("\nAssistant rules: " + assistantConfig.rules.length)
);
if (config.rules?.length) {
console.info(chalk.yellow("\nAssistant rules: " + config.rules.length));
}
if (assistantConfig.mcpServers?.length) {
if (config.mcpServers?.length) {
console.info(chalk.yellow("\nMCP Servers:"));
assistantConfig.mcpServers.forEach((server: any) => {
config.mcpServers.forEach((server: any) => {
console.info(`- ${chalk.cyan(server?.name)}`);
});
}

View file

@ -1,5 +1,5 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ContinueClient } from "@continuedev/sdk";
import { Box, Text, useApp } from "ink";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import path from "path";
@ -15,7 +15,7 @@ import ToolResultSummary from "./ToolResultSummary.js";
import UserInput from "./UserInput.js";
interface TUIChatProps {
assistant: ContinueClient["assistant"];
config: AssistantUnrolled;
model: string;
llmApi: BaseLlmApi;
initialPrompt?: string;
@ -32,7 +32,7 @@ interface DisplayMessage {
}
const TUIChat: React.FC<TUIChatProps> = ({
assistant,
config: assistant,
model,
llmApi,
initialPrompt,
@ -52,7 +52,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
// If no session loaded or not resuming, initialize with system message
if (history.length === 0) {
const rulesSystemMessage = assistant.systemMessage;
const rulesSystemMessage = ""; // TODO // assistant.systemMessage;
const systemMessage = constructSystemMessage(rulesSystemMessage);
if (systemMessage) {
history.push({ role: "system", content: systemMessage });
@ -96,7 +96,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
const handleUserMessage = async (message: string) => {
// Handle slash commands
const commandResult = handleSlashCommands(message, assistant.config);
const commandResult = handleSlashCommands(message, assistant);
if (commandResult) {
if (commandResult.exit) {
exit();
@ -415,7 +415,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant.config}
assistant={assistant}
onFileAttached={handleFileAttached}
/>
<Box marginRight={2} justifyContent="flex-end">

View file

@ -1,5 +1,5 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ContinueClient } from "@continuedev/sdk";
import { render } from "ink";
import React from "react";
import { introMessage } from "../intro.js";
@ -9,7 +9,7 @@ import TUIChat from "./TUIChat.js";
export { default as MarkdownRenderer } from "./MarkdownRenderer.js";
export async function startTUIChat(
assistant: ContinueClient["assistant"],
config: AssistantUnrolled,
llmApi: BaseLlmApi,
model: string,
mcpService: MCPService,
@ -17,12 +17,12 @@ export async function startTUIChat(
resume?: boolean
) {
// Show intro message before starting TUI
introMessage(assistant, mcpService);
introMessage(config, model, mcpService);
// Start the TUI
const { unmount } = render(
React.createElement(TUIChat, {
assistant,
config: config,
model,
llmApi,
initialPrompt,