From 02fcd4668b2052b0473c487b0a8a6be6c69bc800 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 10:32:53 -0700 Subject: [PATCH 1/7] use continue sdk --- package-lock.json | 26 +++++++++++----- package.json | 2 +- src/args.ts | 3 +- src/auth/workos.ts | 9 ++++-- src/env.ts | 2 +- src/index.ts | 74 ++++++++++++++++++++++++++++++++++++---------- src/intro.ts | 27 +++++++++-------- src/ui/TUIChat.tsx | 12 ++++---- src/ui/index.ts | 8 ++--- 9 files changed, 109 insertions(+), 54 deletions(-) diff --git a/package-lock.json b/package-lock.json index 863704155..c2767957a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 7f8c41e92..737fb3b39 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/args.ts b/src/args.ts index ff2f242c9..0560d068b 100644 --- a/src/args.ts +++ b/src/args.ts @@ -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 diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 1e38c597c..8c0ef649e 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -132,9 +132,12 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string { */ async function refreshToken(refreshToken: string): Promise { 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; diff --git a/src/env.ts b/src/env.ts index d0b567ca0..6c79148f5 100644 --- a/src/env.ts +++ b/src/env.ts @@ -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", }; diff --git a/src/index.ts b/src/index.ts index 5448d1730..e38c010f5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { - const continueSdk = await initializeContinueSDK(accessToken, configPath); + config: string | undefined, + organizationId: string | undefined +): Promise { + 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; diff --git a/src/intro.ts b/src/intro.ts index dec4c2a12..97a8df934 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -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)}`); }); } diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 116337aac..fc0b058be 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -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 = ({ - assistant, + config: assistant, model, llmApi, initialPrompt, @@ -52,7 +52,7 @@ const TUIChat: React.FC = ({ // 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 = ({ 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 = ({ isWaitingForResponse={isWaitingForResponse} inputMode={inputMode} onInterrupt={handleInterrupt} - assistant={assistant.config} + assistant={assistant} onFileAttached={handleFileAttached} /> diff --git a/src/ui/index.ts b/src/ui/index.ts index 221ca9719..03c20f6e4 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -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, From 50d8b463b8e4750ee7a1dc1266ae7feca63b5310 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 10:38:35 -0700 Subject: [PATCH 2/7] refactor --- src/assistant.ts | 126 +++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 115 ++---------------------------------------- 2 files changed, 131 insertions(+), 110 deletions(-) create mode 100644 src/assistant.ts diff --git a/src/assistant.ts b/src/assistant.ts new file mode 100644 index 000000000..20fb9c1e1 --- /dev/null +++ b/src/assistant.ts @@ -0,0 +1,126 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { + BaseLlmApi, + constructLlmApi, + LLMConfig, +} from "@continuedev/openai-adapters"; +import { + Configuration, + DefaultApi, +} from "@continuedev/sdk/dist/api/dist/index.js"; +import { AuthConfig } from "./auth/workos.js"; +import { MCPService } from "./mcp.js"; + +export function getLlmApi( + assistant: AssistantUnrolled, + authConfig: AuthConfig +): [BaseLlmApi, string] { + const model = assistant.models?.find((model) => + model?.roles?.includes("chat") + ); + + if (!model) { + throw new Error( + "No models with the chat role found in the configured assistant" + ); + } + + const config: LLMConfig = + model.provider === "continue-proxy" + ? { + provider: model.provider, + requestOptions: model.requestOptions, + apiBase: model.apiBase, + apiKey: authConfig.accessToken, + env: { + apiKeyLocation: (model as any).apiKeyLocation, + // envSecretLocations: model.env, + orgScopeId: null, // TODO + proxyUrl: undefined, // TODO + }, + } + : { + provider: model.provider as any, + apiKey: model.apiKey, + apiBase: model.apiBase, + requestOptions: model.requestOptions, + env: model.env, + }; + + const llmApi = constructLlmApi(config); + + if (!llmApi) { + throw new Error( + "Failed to initialized LLM. Please check your configuration." + ); + } + + return [llmApi, model.model]; +} + +export async function loadAssistant( + accessToken: string | undefined, + config: string | undefined, + organizationId: string | undefined +): Promise { + const apiClient = new DefaultApi( + new Configuration({ + accessToken, + }) + ); + + 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; + } +} + +export async function initializeAssistant( + authConfig: AuthConfig, + configPath: string | undefined +): Promise<{ + config: AssistantUnrolled; + llmApi: BaseLlmApi; + model: string; + mcpService: MCPService; +}> { + const config = await loadAssistant( + authConfig.accessToken, + configPath, + undefined + ); + const [llmApi, model] = getLlmApi(config, authConfig); + const mcpService = await MCPService.create(config); + + return { config, llmApi, model, mcpService }; +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index e38c010f5..ef3c78664 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,24 +1,14 @@ #!/usr/bin/env node -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { - BaseLlmApi, - constructLlmApi, - LLMConfig, -} from "@continuedev/openai-adapters"; -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 { initializeAssistant } from "./assistant.js"; +import { loadAuthConfig } from "./auth/workos.js"; import { introMessage } from "./intro.js"; import { configureLogger } from "./logger.js"; -import { MCPService } from "./mcp.js"; import { loadSession, saveSession } from "./session.js"; import { handleSlashCommands } from "./slashCommands.js"; import { streamChatResponse } from "./streamChatResponse.js"; @@ -31,99 +21,7 @@ const args = parseArgs(); // Configure logger based on headless mode configureLogger(args.isHeadless); -function getLlmApi( - assistant: AssistantUnrolled, - authConfig: AuthConfig -): [BaseLlmApi, string] { - const model = assistant.models?.find((model) => - model?.roles?.includes("chat") - ); - if (!model) { - throw new Error( - "No models with the chat role found in the configured assistant" - ); - } - - const config: LLMConfig = - model.provider === "continue-proxy" - ? { - provider: model.provider, - requestOptions: model.requestOptions, - apiBase: model.apiBase, - apiKey: authConfig.accessToken, - env: { - apiKeyLocation: (model as any).apiKeyLocation, - // envSecretLocations: model.env, - orgScopeId: null, // TODO - proxyUrl: undefined, // TODO - }, - } - : { - provider: model.provider as any, - apiKey: model.apiKey, - apiBase: model.apiBase, - requestOptions: model.requestOptions, - env: model.env, - }; - - const llmApi = constructLlmApi(config); - - if (!llmApi) { - throw new Error( - "Failed to initialized LLM. Please check your configuration." - ); - } - - return [llmApi, model.model]; -} - -async function loadAssistant( - accessToken: string | undefined, - config: string | undefined, - organizationId: string | undefined -): Promise { - const apiClient = new DefaultApi( - new Configuration({ - accessToken, - }) - ); - - 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() { const isAuthenticated = await ensureAuthenticated(true); @@ -164,13 +62,10 @@ async function chat() { // } // Initialize ContinueSDK and MCPService once - const config = await loadAssistant( - authConfig.accessToken, - args.configPath, - undefined + const { config, llmApi, model, mcpService } = await initializeAssistant( + authConfig, + args.configPath ); - 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) { From 5e73c07ba9b81048c23d418634f59fe33ee50ed4 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 10:51:53 -0700 Subject: [PATCH 3/7] org selection --- src/assistant.ts | 6 +- src/auth/workos.ts | 145 +++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 37 ++---------- src/intro.ts | 6 +- 4 files changed, 156 insertions(+), 38 deletions(-) diff --git a/src/assistant.ts b/src/assistant.ts index 20fb9c1e1..225431300 100644 --- a/src/assistant.ts +++ b/src/assistant.ts @@ -35,7 +35,7 @@ export function getLlmApi( env: { apiKeyLocation: (model as any).apiKeyLocation, // envSecretLocations: model.env, - orgScopeId: null, // TODO + orgScopeId: authConfig.organizationId ?? null, proxyUrl: undefined, // TODO }, } @@ -117,10 +117,10 @@ export async function initializeAssistant( const config = await loadAssistant( authConfig.accessToken, configPath, - undefined + authConfig.organizationId ?? undefined ); const [llmApi, model] = getLlmApi(config, authConfig); const mcpService = await MCPService.create(config); return { config, llmApi, model, mcpService }; -} \ No newline at end of file +} diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 8c0ef649e..c60b610c1 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -1,3 +1,7 @@ +import { + Configuration, + DefaultApi, +} from "@continuedev/sdk/dist/api/dist/index.js"; import axios from "axios"; import chalk from "chalk"; import * as fs from "fs"; @@ -17,6 +21,7 @@ export interface AuthConfig { accessToken?: string; refreshToken?: string; expiresAt?: number; + organizationId?: string | null; } /** @@ -211,6 +216,146 @@ export async function login( } } +/** + * Ensures the user has selected an organization, prompting if necessary + */ +export async function ensureOrganization( + authConfig: AuthConfig, + isHeadless: boolean = false +): Promise { + // If using CONTINUE_API_KEY environment variable, don't require organization selection + if (process.env.CONTINUE_API_KEY) { + return authConfig; + } + + // If already have organization ID (including null for personal), return as-is + if (authConfig.organizationId !== undefined) { + return authConfig; + } + + // In headless mode, default to personal organization if none saved + if (isHeadless) { + const updatedConfig = { + ...authConfig, + organizationId: null, // Default to personal organization + }; + saveAuthConfig(updatedConfig); + return updatedConfig; + } + + // Need to select organization + const apiClient = new DefaultApi( + new Configuration({ + accessToken: authConfig.accessToken, + }) + ); + + try { + const resp = await apiClient.listOrganizations(); + const organizations = resp.organizations; + + if (organizations.length === 0) { + console.info( + chalk.green("No organizations found. Using personal organization.") + ); + const updatedConfig = { + ...authConfig, + organizationId: null, + }; + saveAuthConfig(updatedConfig); + return updatedConfig; + } + + if (organizations.length === 1) { + // Show choice between personal and the one organization + const org = organizations[0]; + console.info(chalk.cyan("\nSelect an organization:")); + console.info(chalk.white(`1. Personal (default)`)); + console.info(chalk.white(`2. ${org.name}`)); + + const selection = await prompt( + chalk.yellow("Enter your choice (number): ") + ); + const selectedIndex = parseInt(selection) - 1; + + if (selectedIndex < 0 || selectedIndex > 1) { + console.error(chalk.red("Invalid selection. Please try again.")); + return await ensureOrganization(authConfig, isHeadless); + } + + let selectedOrgId: string | null; + let selectedOrgName: string; + + if (selectedIndex === 0) { + // Personal organization selected + selectedOrgId = null; + selectedOrgName = "Personal"; + } else { + // The one organization selected + selectedOrgId = org.id; + selectedOrgName = org.name; + } + + console.info(chalk.green(`Selected organization: ${selectedOrgName}`)); + + const updatedConfig = { + ...authConfig, + organizationId: selectedOrgId, + }; + + saveAuthConfig(updatedConfig); + return updatedConfig; + } + + // Multiple organizations - show selection including personal + console.info(chalk.cyan("\nSelect an organization:")); + console.info(chalk.white(`1. Personal (default)`)); + organizations.forEach((org, index) => { + console.info(chalk.white(`${index + 2}. ${org.name}`)); + }); + + const selection = await prompt( + chalk.yellow("Enter your choice (number): ") + ); + const selectedIndex = parseInt(selection) - 1; + + if (selectedIndex < 0 || selectedIndex > organizations.length) { + console.error(chalk.red("Invalid selection. Please try again.")); + return await ensureOrganization(authConfig, isHeadless); + } + + let selectedOrgId: string | null; + let selectedOrgName: string; + + if (selectedIndex === 0) { + // Personal organization selected + selectedOrgId = null; + selectedOrgName = "Personal"; + } else { + // Regular organization selected + const selectedOrg = organizations[selectedIndex - 1]; + selectedOrgId = selectedOrg.id; + selectedOrgName = selectedOrg.name; + } + console.info(chalk.green(`Selected organization: ${selectedOrgName}`)); + + const updatedConfig = { + ...authConfig, + organizationId: selectedOrgId, + }; + + saveAuthConfig(updatedConfig); + return updatedConfig; + } catch (error: any) { + console.error( + chalk.red("Error fetching organizations:"), + error.response?.data?.message || error.message || error + ); + console.info(chalk.yellow("Continuing without organization selection.")); + return authConfig; + } +} + /** * Logs the user out by clearing saved credentials */ diff --git a/src/index.ts b/src/index.ts index ef3c78664..8366b3b34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,9 +4,9 @@ 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 { initializeAssistant } from "./assistant.js"; -import { loadAuthConfig } from "./auth/workos.js"; +import { ensureAuthenticated } from "./auth/ensureAuth.js"; +import { loadAuthConfig, ensureOrganization } from "./auth/workos.js"; import { introMessage } from "./intro.js"; import { configureLogger } from "./logger.js"; import { loadSession, saveSession } from "./session.js"; @@ -21,8 +21,6 @@ const args = parseArgs(); // Configure logger based on headless mode configureLogger(args.isHeadless); - - async function chat() { const isAuthenticated = await ensureAuthenticated(true); @@ -33,37 +31,12 @@ async function chat() { const authConfig = loadAuthConfig(); - // This was the previous default behavior, but currently the SDK - // only supports slugs, so we've disabled reading local assistant files - - // if (fs.existsSync(args.assistantPath)) { - // // If it's a file, load it directly - // console.info( - // chalk.yellow(`Loading assistant from file: ${args.assistantPath}`) - // ); - // // We need to extract the assistant slug from the yaml to use with the SDK - // // For now, let's just use a placeholder slug and use the file content for assistant config - // // In a real implementation, we'd need to parse the YAML and extract the slug - // const assistantSlug = "default/assistant"; - // try { - // sdkClient = await initializeContinueSDK( - // authConfig.accessToken, - // assistantSlug - // ); - // // Since we're using a file, we need to manually set the assistant config - // assistant = JSON.parse(JSON.stringify(sdkClient.assistant.config)); - // } catch (error) { - // console.error( - // chalk.red("Error initializing SDK with local file:"), - // error - // ); - // throw error; - // } - // } + // Ensure organization is selected + const authConfigWithOrg = await ensureOrganization(authConfig, args.isHeadless); // Initialize ContinueSDK and MCPService once const { config, llmApi, model, mcpService } = await initializeAssistant( - authConfig, + authConfigWithOrg, args.configPath ); diff --git a/src/intro.ts b/src/intro.ts index 97a8df934..e733e4585 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -55,9 +55,9 @@ export function introMessage( } console.info(""); - if (config.rules?.length) { - console.info(chalk.yellow("\nAssistant rules: " + config.rules.length)); - } + // if (config.rules?.length) { + // console.info(chalk.yellow("\nRules: " + config.rules.length)); + // } if (config.mcpServers?.length) { console.info(chalk.yellow("\nMCP Servers:")); From d19262590187ebf87c5255c718004231fd8a1537 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 13:24:07 -0700 Subject: [PATCH 4/7] org switcher --- src/auth/workos.ts | 40 ++++++++ src/index.ts | 35 +++---- src/slashCommands.ts | 6 +- src/ui/OrganizationSelector.tsx | 156 ++++++++++++++++++++++++++++++++ src/ui/SlashCommandUI.tsx | 14 ++- src/ui/TUIChat.tsx | 115 ++++++++++++++++++++++- src/ui/UserInput.tsx | 24 ++++- src/ui/index.ts | 5 +- 8 files changed, 364 insertions(+), 31 deletions(-) create mode 100644 src/ui/OrganizationSelector.tsx diff --git a/src/auth/workos.ts b/src/auth/workos.ts index c60b610c1..b87e2e039 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -356,6 +356,46 @@ export async function ensureOrganization( } } +/** + * Gets the list of available organizations for the user + */ +export async function listUserOrganizations(): Promise< + { id: string; name: string }[] | null +> { + // If using CONTINUE_API_KEY environment variable, organization switching is not supported + if (process.env.CONTINUE_API_KEY) { + return null; + } + + const authConfig = loadAuthConfig(); + + if (!authConfig.accessToken) { + return null; + } + + const apiClient = new DefaultApi( + new Configuration({ + accessToken: authConfig.accessToken, + }) + ); + + try { + const resp = await apiClient.listOrganizations(); + return resp.organizations || []; + } catch (error) { + return null; + } +} + +/** + * Checks if the user has multiple organizations available + */ +export async function hasMultipleOrganizations(): Promise { + const organizations = await listUserOrganizations(); + // Has multiple organizations if there's at least one organization (plus personal) + return organizations !== null && organizations.length > 0; +} + /** * Logs the user out by clearing saved credentials */ diff --git a/src/index.ts b/src/index.ts index 8366b3b34..b6c3c4060 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,11 +6,10 @@ import * as readlineSync from "readline-sync"; import { parseArgs } from "./args.js"; import { initializeAssistant } from "./assistant.js"; import { ensureAuthenticated } from "./auth/ensureAuth.js"; -import { loadAuthConfig, ensureOrganization } from "./auth/workos.js"; +import { ensureOrganization, loadAuthConfig } from "./auth/workos.js"; import { introMessage } from "./intro.js"; import { configureLogger } from "./logger.js"; import { loadSession, saveSession } from "./session.js"; -import { handleSlashCommands } from "./slashCommands.js"; import { streamChatResponse } from "./streamChatResponse.js"; import { constructSystemMessage } from "./systemMessage.js"; import { startTUIChat } from "./ui/index.js"; @@ -21,7 +20,7 @@ const args = parseArgs(); // Configure logger based on headless mode configureLogger(args.isHeadless); -async function chat() { +async function initializeChat() { const isAuthenticated = await ensureAuthenticated(true); if (!isAuthenticated) { @@ -32,7 +31,10 @@ async function chat() { const authConfig = loadAuthConfig(); // Ensure organization is selected - const authConfigWithOrg = await ensureOrganization(authConfig, args.isHeadless); + const authConfigWithOrg = await ensureOrganization( + authConfig, + args.isHeadless + ); // Initialize ContinueSDK and MCPService once const { config, llmApi, model, mcpService } = await initializeAssistant( @@ -40,6 +42,12 @@ async function chat() { args.configPath ); + return { config, llmApi, model, mcpService }; +} + +async function chat() { + let { config, llmApi, model, mcpService } = await initializeChat(); + // If not in headless mode, start the TUI chat (default) if (!args.isHeadless) { await startTUIChat( @@ -48,7 +56,8 @@ async function chat() { model, mcpService, args.prompt, - args.resume + args.resume, + args.configPath ); return; } @@ -94,22 +103,6 @@ async function chat() { isFirstMessage = false; - // Handle slash commands - const commandResult = handleSlashCommands(userInput, config); - if (commandResult) { - if (commandResult.exit) { - break; - } - - // Note that `console.log` is shown in headless mode, `console.info` is not - console.log(`\n${chalk.italic.gray(commandResult.output ?? "")}`); - - if (commandResult.newInput) { - userInput = commandResult.newInput; - } else { - continue; - } - } // Add user message to history chatHistory.push({ role: "user", content: userInput }); diff --git a/src/slashCommands.ts b/src/slashCommands.ts index c7d011f71..f29de50ea 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -7,15 +7,15 @@ import { } from "./auth/workos.js"; import { type AssistantConfig } from "@continuedev/sdk"; -export function handleSlashCommands( +export async function handleSlashCommands( input: string, assistant: AssistantConfig -): { +): Promise<{ output?: string; exit?: boolean; newInput?: string; clear?: boolean; -} | null { +} | null> { if (input.startsWith("/")) { const [command, ...args] = input.slice(1).split(" "); switch (command) { diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx new file mode 100644 index 000000000..076c9fd4b --- /dev/null +++ b/src/ui/OrganizationSelector.tsx @@ -0,0 +1,156 @@ +import { Box, Text, useInput } from "ink"; +import React, { useEffect, useState } from "react"; +import { loadAuthConfig, listUserOrganizations } from "../auth/workos.js"; + +interface Organization { + id: string; + name: string; +} + +interface OrganizationSelectorProps { + onSelect: (organizationId: string | null, organizationName: string) => void; + onCancel: () => void; +} + +const OrganizationSelector: React.FC = ({ + onSelect, + onCancel, +}) => { + const [organizations, setOrganizations] = useState([]); + const [selectedIndex, setSelectedIndex] = useState(0); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [currentOrgId, setCurrentOrgId] = useState(); + + useEffect(() => { + const loadOrganizations = async () => { + try { + const authConfig = loadAuthConfig(); + setCurrentOrgId(authConfig.organizationId); + + const organizations = await listUserOrganizations(); + if (organizations === null) { + setError("Failed to load organizations"); + setLoading(false); + return; + } + + setOrganizations(organizations); + setLoading(false); + } catch (err: any) { + setError(err.message || "Failed to load organizations"); + setLoading(false); + } + }; + + loadOrganizations(); + }, []); + + useInput((input, key) => { + if (key.escape) { + onCancel(); + return; + } + + if (key.return) { + const totalOptions = organizations.length + 1; // +1 for personal + if (selectedIndex === 0) { + onSelect(null, "Personal"); + } else if (selectedIndex <= organizations.length) { + const selectedOrg = organizations[selectedIndex - 1]; + onSelect(selectedOrg.id, selectedOrg.name); + } + return; + } + + if (key.upArrow) { + setSelectedIndex((prev) => Math.max(0, prev - 1)); + } else if (key.downArrow) { + const totalOptions = organizations.length + 1; // +1 for personal + setSelectedIndex((prev) => Math.min(totalOptions - 1, prev + 1)); + } + }); + + if (loading) { + return ( + + + Organization Selector + + Loading organizations... + + ); + } + + if (error) { + return ( + + + Error + + {error} + + Press Escape to cancel + + + ); + } + + const allOptions = [ + { id: null, name: "Personal", isCurrent: currentOrgId === null }, + ...organizations.map((org) => ({ + ...org, + isCurrent: currentOrgId === org.id, + })), + ]; + + return ( + + + Select Organization + + + {allOptions.map((option, index) => { + const isSelected = index === selectedIndex; + const isCurrent = option.isCurrent; + + return ( + + + {isSelected ? "▶ " : " "} + {option.name} + {isCurrent ? " (current)" : ""} + + + ); + })} + + + + Use ↑/↓ to navigate, Enter to select, Escape to cancel + + + + ); +}; + +export default OrganizationSelector; \ No newline at end of file diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 60d454715..089b28987 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,6 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text } from "ink"; -import React from "react"; +import React, { useEffect, useState } from "react"; +import { hasMultipleOrganizations } from "../auth/workos.js"; interface SlashCommandUIProps { assistant: AssistantConfig; @@ -21,6 +22,12 @@ const SlashCommandUI: React.FC = ({ selectedIndex, onSelect, }) => { + const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); + + useEffect(() => { + hasMultipleOrganizations().then(setHasMultipleOrgs); + }, []); + // Get all available slash commands const getSlashCommands = (): SlashCommand[] => { const systemCommands: SlashCommand[] = [ @@ -42,6 +49,11 @@ const SlashCommandUI: React.FC = ({ description: "Check who you're currently logged in as", category: "system", }, + ...(hasMultipleOrgs ? [{ + name: "org", + description: "Switch organization", + category: "system" as const, + }] : []), ]; const assistantCommands: SlashCommand[] = diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index fc0b058be..e968be15b 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -6,11 +6,16 @@ import path from "path"; import React, { useEffect, useState } from "react"; import { loadSession, saveSession } from "../session.js"; import { handleSlashCommands } from "../slashCommands.js"; +import { saveAuthConfig, loadAuthConfig } from "../auth/workos.js"; +import { initializeAssistant } from "../assistant.js"; +import { MCPService } from "../mcp.js"; +import { introMessage } from "../intro.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { getToolDisplayName } from "../tools.js"; import LoadingAnimation from "./LoadingAnimation.js"; import MarkdownRenderer from "./MarkdownRenderer.js"; +import OrganizationSelector from "./OrganizationSelector.js"; import ToolResultSummary from "./ToolResultSummary.js"; import UserInput from "./UserInput.js"; @@ -18,6 +23,8 @@ interface TUIChatProps { config: AssistantUnrolled; model: string; llmApi: BaseLlmApi; + mcpService: MCPService; + configPath?: string; initialPrompt?: string; resume?: boolean; } @@ -32,12 +39,19 @@ interface DisplayMessage { } const TUIChat: React.FC = ({ - config: assistant, - model, - llmApi, + config: initialAssistant, + model: initialModel, + llmApi: initialLlmApi, + mcpService: initialMcpService, + configPath, initialPrompt, resume, }) => { + // Track current assistant configuration state + const [assistant, setAssistant] = useState(initialAssistant); + const [model, setModel] = useState(initialModel); + const [llmApi, setLlmApi] = useState(initialLlmApi); + const [mcpService, setMcpService] = useState(initialMcpService); const [chatHistory, setChatHistory] = useState( () => { let history: ChatCompletionMessageParam[] = []; @@ -85,6 +99,7 @@ const TUIChat: React.FC = ({ const [attachedFiles, setAttachedFiles] = useState< Array<{ path: string; content: string }> >([]); + const [showOrgSelector, setShowOrgSelector] = useState(false); const { exit } = useApp(); // Handle initial prompt @@ -95,8 +110,14 @@ const TUIChat: React.FC = ({ }, [initialPrompt]); const handleUserMessage = async (message: string) => { + // Special handling for /org command in TUI - show selector instead of prompting + if (message.trim() === "/org") { + setShowOrgSelector(true); + return; + } + // Handle slash commands - const commandResult = handleSlashCommands(message, assistant); + const commandResult = await handleSlashCommands(message, assistant); if (commandResult) { if (commandResult.exit) { exit(); @@ -123,6 +144,7 @@ const TUIChat: React.FC = ({ return; } + // Add command output to messages if (commandResult.output) { setMessages((prev) => [ @@ -392,6 +414,82 @@ const TUIChat: React.FC = ({ ); }; + const handleOrganizationSelect = async (organizationId: string | null, organizationName: string) => { + setShowOrgSelector(false); + + // Update auth config + const authConfig = loadAuthConfig(); + const updatedConfig = { + ...authConfig, + organizationId, + }; + saveAuthConfig(updatedConfig); + + try { + // Show loading message + setMessages([ + { + role: "system", + content: `Switching to organization: ${organizationName}...`, + messageType: "system", + }, + ]); + + // Reinitialize assistant with new organization (full refresh) + const { config, llmApi: newLlmApi, model: newModel, mcpService: newMcpService } = await initializeAssistant( + updatedConfig, + configPath // Pass the original config path to potentially load different assistant + ); + + // Update state with new assistant configuration + setAssistant(config); + setLlmApi(newLlmApi); + setModel(newModel); + setMcpService(newMcpService); + + // Clear chat history and start fresh + const rulesSystemMessage = ""; // TODO: get from assistant.systemMessage if available + const systemMessage = constructSystemMessage(rulesSystemMessage); + const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; + setChatHistory(newHistory); + + // Clear the screen completely + clearScreen(); + + // Show the new intro message for the new assistant + introMessage(config, newModel, newMcpService); + + // Clear messages and show success + setMessages([ + { + role: "system", + content: `Successfully switched to organization: ${organizationName}`, + messageType: "system", + }, + ]); + + } catch (error: any) { + // Show error message + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Failed to switch organization: ${error.message}`, + messageType: "system", + }, + ]); + } + }; + + const handleOrganizationCancel = () => { + setShowOrgSelector(false); + }; + + const clearScreen = () => { + // Clear the terminal screen + process.stdout.write('\x1b[2J\x1b[H'); + }; + return ( {/* Chat history - takes up all available space above input */} @@ -409,6 +507,14 @@ const TUIChat: React.FC = ({ )} + {/* Organization selector - shows above input when active */} + {showOrgSelector && ( + + )} + {/* Input area - always at bottom */} = ({ onInterrupt={handleInterrupt} assistant={assistant} onFileAttached={handleFileAttached} + disabled={showOrgSelector} /> ● Continue CLI diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index b6c30cd73..0283f2ec2 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -1,6 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useState } from "react"; +import React, { useState, useEffect } from "react"; +import { hasMultipleOrganizations } from "../auth/workos.js"; import { InputHistory } from "../util/inputHistory.js"; import FileSearchUI from "./FileSearchUI.js"; import SlashCommandUI from "./SlashCommandUI.js"; @@ -13,6 +14,7 @@ interface UserInputProps { onInterrupt?: () => void; assistant: AssistantConfig; onFileAttached?: (filePath: string, content: string) => void; + disabled?: boolean; } const UserInput: React.FC = ({ @@ -22,6 +24,7 @@ const UserInput: React.FC = ({ onInterrupt, assistant, onFileAttached, + disabled = false, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); @@ -39,6 +42,12 @@ const UserInput: React.FC = ({ const { exit } = useApp(); // Get all available slash commands + const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); + + useEffect(() => { + hasMultipleOrganizations().then(setHasMultipleOrgs); + }, []); + const getSlashCommands = () => { const systemCommands = [ { name: "help", description: "Show help message" }, @@ -49,6 +58,10 @@ const UserInput: React.FC = ({ name: "whoami", description: "Check who you're currently logged in as", }, + ...(hasMultipleOrgs ? [{ + name: "org", + description: "Switch organization", + }] : []), ]; const assistantCommands = @@ -185,6 +198,10 @@ const UserInput: React.FC = ({ }; useInput((input, key) => { + // Don't handle any input when disabled + if (disabled) { + return; + } if (key.ctrl && (input === "c" || input === "d")) { exit(); return; @@ -433,6 +450,11 @@ const UserInput: React.FC = ({ } }; + // Don't render anything when disabled + if (disabled) { + return null; + } + return ( {/* Input box */} diff --git a/src/ui/index.ts b/src/ui/index.ts index 03c20f6e4..12711075d 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -14,7 +14,8 @@ export async function startTUIChat( model: string, mcpService: MCPService, initialPrompt?: string, - resume?: boolean + resume?: boolean, + configPath?: string ) { // Show intro message before starting TUI introMessage(config, model, mcpService); @@ -25,6 +26,8 @@ export async function startTUIChat( config: config, model, llmApi, + mcpService, + configPath, initialPrompt, resume, }) From 304d1ac0a3992ca659fa0acadde88b1637301914 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 14:09:34 -0700 Subject: [PATCH 5/7] refactor into hooks --- src/ui/TUIChat.tsx | 490 ++---------------------- src/ui/hooks/useChat.ts | 348 +++++++++++++++++ src/ui/hooks/useMessageRenderer.tsx | 74 ++++ src/ui/hooks/useOrganizationSelector.ts | 105 +++++ src/ui/types.ts | 8 + 5 files changed, 573 insertions(+), 452 deletions(-) create mode 100644 src/ui/hooks/useChat.ts create mode 100644 src/ui/hooks/useMessageRenderer.tsx create mode 100644 src/ui/hooks/useOrganizationSelector.ts create mode 100644 src/ui/types.ts diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index e968be15b..2f06613e9 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,22 +1,13 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { Box, Text, useApp } from "ink"; -import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import path from "path"; -import React, { useEffect, useState } from "react"; -import { loadSession, saveSession } from "../session.js"; -import { handleSlashCommands } from "../slashCommands.js"; -import { saveAuthConfig, loadAuthConfig } from "../auth/workos.js"; -import { initializeAssistant } from "../assistant.js"; +import { Box, Text } from "ink"; +import React, { useState } from "react"; import { MCPService } from "../mcp.js"; -import { introMessage } from "../intro.js"; -import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; -import { constructSystemMessage } from "../systemMessage.js"; -import { getToolDisplayName } from "../tools.js"; +import { useChat } from "./hooks/useChat.js"; +import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; +import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import LoadingAnimation from "./LoadingAnimation.js"; -import MarkdownRenderer from "./MarkdownRenderer.js"; import OrganizationSelector from "./OrganizationSelector.js"; -import ToolResultSummary from "./ToolResultSummary.js"; import UserInput from "./UserInput.js"; interface TUIChatProps { @@ -29,14 +20,6 @@ interface TUIChatProps { resume?: boolean; } -interface DisplayMessage { - role: string; - content: string; - isStreaming?: boolean; - messageType?: "tool-start" | "tool-result" | "tool-error" | "system"; - toolName?: string; - toolResult?: string; -} const TUIChat: React.FC = ({ config: initialAssistant, @@ -52,443 +35,46 @@ const TUIChat: React.FC = ({ const [model, setModel] = useState(initialModel); const [llmApi, setLlmApi] = useState(initialLlmApi); const [mcpService, setMcpService] = useState(initialMcpService); - const [chatHistory, setChatHistory] = useState( - () => { - let history: ChatCompletionMessageParam[] = []; - // Load previous session if --resume flag is used - if (resume) { - const savedHistory = loadSession(); - if (savedHistory) { - history = savedHistory; - } - } - - // If no session loaded or not resuming, initialize with system message - if (history.length === 0) { - const rulesSystemMessage = ""; // TODO // assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage); - if (systemMessage) { - history.push({ role: "system", content: systemMessage }); - } - } - - return history; - } - ); - - const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); - const [messages, setMessages] = useState(() => { - // Convert loaded chat history to display messages (excluding system messages) - if (resume) { - const savedHistory = loadSession(); - if (savedHistory) { - return savedHistory - .filter((msg) => msg.role !== "system") - .map((msg) => ({ - role: msg.role, - content: msg.content as string, - })); - } - } - return []; + const { + messages, + setMessages, + isWaitingForResponse, + inputMode, + handleUserMessage, + handleInterrupt, + handleFileAttached, + resetChatHistory, + } = useChat({ + assistant, + model, + llmApi, + initialPrompt, + resume, + onShowOrgSelector: () => showOrganizationSelector(), }); - const [inputMode, setInputMode] = useState(true); - const [abortController, setAbortController] = - useState(null); - const [attachedFiles, setAttachedFiles] = useState< - Array<{ path: string; content: string }> - >([]); - const [showOrgSelector, setShowOrgSelector] = useState(false); - const { exit } = useApp(); - // Handle initial prompt - useEffect(() => { - if (initialPrompt) { - handleUserMessage(initialPrompt); - } - }, [initialPrompt]); + const { renderMessage } = useMessageRenderer(); - const handleUserMessage = async (message: string) => { - // Special handling for /org command in TUI - show selector instead of prompting - if (message.trim() === "/org") { - setShowOrgSelector(true); - return; - } - - // Handle slash commands - const commandResult = await handleSlashCommands(message, assistant); - if (commandResult) { - if (commandResult.exit) { - exit(); - return; - } - - if (commandResult.clear) { - // Clear chat history but keep system message - const systemMessage = chatHistory.find((msg) => msg.role === "system"); - const newHistory = systemMessage ? [systemMessage] : []; - setChatHistory(newHistory); - setMessages([]); - - // Add command output to messages - if (commandResult.output) { - setMessages([ - { - role: "system", - content: commandResult.output!, - messageType: "system", - }, - ]); - } - return; - } - - - // Add command output to messages - if (commandResult.output) { - setMessages((prev) => [ - ...prev, - { - role: "system", - content: commandResult.output!, - messageType: "system", - }, - ]); - } - - if (commandResult.newInput) { - message = commandResult.newInput; - } else { - return; - } - } - - // Add user message to history and display - let messageContent = message; - - // Prepend attached files to the message - if (attachedFiles.length > 0) { - const fileContents = attachedFiles - .map( - (file) => `\n\n\n${file.content}\n` - ) - .join(""); - messageContent = `${message}${fileContents}`; - - // Clear attached files after sending - setAttachedFiles([]); - } - - const newUserMessage: ChatCompletionMessageParam = { - role: "user", - content: messageContent, - }; - const newHistory = [...chatHistory, newUserMessage]; - setChatHistory(newHistory); - setMessages((prev) => [...prev, { role: "user", content: message }]); - - // Start streaming response - const controller = new AbortController(); - setAbortController(controller); - setIsWaitingForResponse(true); - setInputMode(false); - - try { - let currentStreamingMessage: DisplayMessage | null = null; - - // Create callbacks to handle streaming updates - const streamCallbacks: StreamCallbacks = { - onContent: (content: string) => { - // Buffer content but don't update UI until complete or tool call - if (!currentStreamingMessage) { - currentStreamingMessage = { - role: "assistant", - content: "", - isStreaming: true, - }; - } - currentStreamingMessage.content += content; - }, - onContentComplete: (content: string) => { - // Display the complete message - if (currentStreamingMessage) { - setMessages((prev) => [ - ...prev, - { role: "assistant", content: content, isStreaming: false }, - ]); - currentStreamingMessage = null; - } - }, - onToolStart: (toolName: string, toolArgs?: any) => { - const formatToolCall = (name: string, args: any) => { - const displayName = getToolDisplayName(name); - if (!args) return displayName; - - // Get the first parameter value for display - const firstValue = Object.values(args)[0]; - - // Convert absolute paths to relative paths from workspace root - const formatPath = (value: any) => { - if (typeof value === "string" && path.isAbsolute(value)) { - const workspaceRoot = process.cwd(); - const relativePath = path.relative(workspaceRoot, value); - return relativePath || value; - } - return value; - }; - - return `${displayName}(${formatPath(firstValue) || ""})`; - }; - - // Display buffered content when tool starts - if (currentStreamingMessage && currentStreamingMessage.content) { - const messageContent = currentStreamingMessage.content; - setMessages((prev) => [ - ...prev, - { - role: "assistant", - content: messageContent, - isStreaming: false, - }, - ]); - currentStreamingMessage = null; - } - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: formatToolCall(toolName, toolArgs), - messageType: "tool-start", - toolName, - }, - ]); - }, - onToolResult: (result: string, toolName: string) => { - setMessages((prev) => { - const newMessages = [...prev]; - // Find the last tool-start message for this tool and replace it - for (let i = newMessages.length - 1; i >= 0; i--) { - if ( - newMessages[i].messageType === "tool-start" && - newMessages[i].toolName === toolName - ) { - newMessages[i] = { - ...newMessages[i], - messageType: "tool-result", - toolResult: result, // Store the actual result separately - }; - break; - } - } - return newMessages; - }); - }, - onToolError: (error: string, toolName?: string) => { - setMessages((prev) => [ - ...prev, - { - role: "system", - content: error, - messageType: "tool-error", - toolName, - }, - ]); - }, - }; - - await streamChatResponse( - newHistory, - model, - llmApi, - controller, - streamCallbacks - ); - - // Finalize any remaining streaming message - if (currentStreamingMessage && (currentStreamingMessage as any).content) { - const messageContent = (currentStreamingMessage as any).content; - setMessages((prev) => [ - ...prev, - { role: "assistant", content: messageContent, isStreaming: false }, - ]); - } - - // Save session after successful response - saveSession(newHistory); - } catch (error: any) { - const errorMessage = `Error: ${error.message}`; - setMessages((prev) => [ - ...prev, - { role: "system", content: errorMessage, messageType: "system" }, - ]); - } finally { - setAbortController(null); - setIsWaitingForResponse(false); - setInputMode(true); - } - }; - - const handleInterrupt = () => { - if (abortController && isWaitingForResponse) { - abortController.abort(); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "[Interrupted by user]", - messageType: "system", - }, - ]); - } - }; - - const handleFileAttached = (filePath: string, content: string) => { - setAttachedFiles((prev) => [...prev, { path: filePath, content }]); - }; - - const renderMessage = (message: DisplayMessage, index: number) => { - const isUser = message.role === "user"; - const isSystem = message.role === "system"; - - if (isSystem) { - // Handle different types of system messages - switch (message.messageType) { - case "tool-start": - return ( - - ○ {message.content} - - ); - - case "tool-result": - return ( - - - ● - {message.content} - - - - - - ); - - case "tool-error": - return ( - - - ✗{" "} - - Tool error: {message.content} - - ); - - default: - // Regular system messages - return ( - - - {message.content} - - - ); - } - } - - return ( - - ● - - {isUser ? ( - {message.content} - ) : ( - - )} - {message.isStreaming && ▋} - - ); - }; - - const handleOrganizationSelect = async (organizationId: string | null, organizationName: string) => { - setShowOrgSelector(false); - - // Update auth config - const authConfig = loadAuthConfig(); - const updatedConfig = { - ...authConfig, - organizationId, - }; - saveAuthConfig(updatedConfig); - - try { - // Show loading message - setMessages([ - { - role: "system", - content: `Switching to organization: ${organizationName}...`, - messageType: "system", - }, - ]); - - // Reinitialize assistant with new organization (full refresh) - const { config, llmApi: newLlmApi, model: newModel, mcpService: newMcpService } = await initializeAssistant( - updatedConfig, - configPath // Pass the original config path to potentially load different assistant - ); - - // Update state with new assistant configuration - setAssistant(config); - setLlmApi(newLlmApi); + const { + showOrgSelector, + handleOrganizationSelect, + handleOrganizationCancel, + showOrganizationSelector, + } = useOrganizationSelector({ + configPath, + onAssistantChange: (newAssistant, newModel, newLlmApi, newMcpService) => { + setAssistant(newAssistant); setModel(newModel); + setLlmApi(newLlmApi); setMcpService(newMcpService); - - // Clear chat history and start fresh - const rulesSystemMessage = ""; // TODO: get from assistant.systemMessage if available - const systemMessage = constructSystemMessage(rulesSystemMessage); - const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; - setChatHistory(newHistory); - - // Clear the screen completely - clearScreen(); - - // Show the new intro message for the new assistant - introMessage(config, newModel, newMcpService); - - // Clear messages and show success - setMessages([ - { - role: "system", - content: `Successfully switched to organization: ${organizationName}`, - messageType: "system", - }, - ]); - - } catch (error: any) { - // Show error message - setMessages((prev) => [ - ...prev, - { - role: "system", - content: `Failed to switch organization: ${error.message}`, - messageType: "system", - }, - ]); - } - }; + }, + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); - const handleOrganizationCancel = () => { - setShowOrgSelector(false); - }; - - const clearScreen = () => { - // Clear the terminal screen - process.stdout.write('\x1b[2J\x1b[H'); - }; return ( diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts new file mode 100644 index 000000000..c40bfb5bc --- /dev/null +++ b/src/ui/hooks/useChat.ts @@ -0,0 +1,348 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { useApp } from "ink"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import path from "path"; +import { useEffect, useState } from "react"; +import { loadSession, saveSession } from "../../session.js"; +import { handleSlashCommands } from "../../slashCommands.js"; +import { + StreamCallbacks, + streamChatResponse, +} from "../../streamChatResponse.js"; +import { constructSystemMessage } from "../../systemMessage.js"; +import { getToolDisplayName } from "../../tools.js"; + +import { DisplayMessage } from "../types.js"; + +interface UseChatProps { + assistant: AssistantUnrolled; + model: string; + llmApi: BaseLlmApi; + initialPrompt?: string; + resume?: boolean; + onShowOrgSelector: () => void; +} + +export function useChat({ + assistant, + model, + llmApi, + initialPrompt, + resume, + onShowOrgSelector, +}: UseChatProps) { + const { exit } = useApp(); + + const [chatHistory, setChatHistory] = useState( + () => { + let history: ChatCompletionMessageParam[] = []; + + if (resume) { + const savedHistory = loadSession(); + if (savedHistory) { + history = savedHistory; + } + } + + if (history.length === 0) { + const rulesSystemMessage = ""; + const systemMessage = constructSystemMessage(rulesSystemMessage); + if (systemMessage) { + history.push({ role: "system", content: systemMessage }); + } + } + + return history; + } + ); + + const [messages, setMessages] = useState(() => { + if (resume) { + const savedHistory = loadSession(); + if (savedHistory) { + return savedHistory + .filter((msg) => msg.role !== "system") + .map((msg) => ({ + role: msg.role, + content: msg.content as string, + })); + } + } + return []; + }); + + const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); + const [inputMode, setInputMode] = useState(true); + const [abortController, setAbortController] = + useState(null); + const [attachedFiles, setAttachedFiles] = useState< + Array<{ path: string; content: string }> + >([]); + + useEffect(() => { + if (initialPrompt) { + handleUserMessage(initialPrompt); + } + }, [initialPrompt]); + + const handleUserMessage = async (message: string) => { + // Special handling for /org command in TUI + if (message.trim() === "/org") { + onShowOrgSelector(); + return; + } + + // Handle slash commands + const commandResult = await handleSlashCommands(message, assistant); + if (commandResult) { + if (commandResult.exit) { + exit(); + return; + } + + if (commandResult.clear) { + const systemMessage = chatHistory.find((msg) => msg.role === "system"); + const newHistory = systemMessage ? [systemMessage] : []; + setChatHistory(newHistory); + setMessages([]); + + if (commandResult.output) { + const output = commandResult.output; + setMessages([ + { + role: "system", + content: output, + messageType: "system" as const, + }, + ]); + } + return; + } + + if (commandResult.output) { + const output = commandResult.output; + setMessages((prev) => [ + ...prev, + { + role: "system", + content: output, + messageType: "system" as const, + }, + ]); + } + + if (commandResult.newInput) { + message = commandResult.newInput; + } else { + return; + } + } + + // Add user message to history and display + let messageContent = message; + + if (attachedFiles.length > 0) { + const fileContents = attachedFiles + .map( + (file) => `\n\n\n${file.content}\n` + ) + .join(""); + messageContent = `${message}${fileContents}`; + setAttachedFiles([]); + } + + const newUserMessage: ChatCompletionMessageParam = { + role: "user", + content: messageContent, + }; + const newHistory = [...chatHistory, newUserMessage]; + setChatHistory(newHistory); + setMessages((prev) => [...prev, { role: "user", content: message }]); + + // Start streaming response + const controller = new AbortController(); + setAbortController(controller); + setIsWaitingForResponse(true); + setInputMode(false); + + try { + let currentStreamingMessage: DisplayMessage | null = null; + + const streamCallbacks: StreamCallbacks = { + onContent: (content: string) => { + if (!currentStreamingMessage) { + currentStreamingMessage = { + role: "assistant", + content: "", + isStreaming: true, + }; + } + currentStreamingMessage.content += content; + }, + onContentComplete: (content: string) => { + if (currentStreamingMessage) { + setMessages((prev) => [ + ...prev, + { + role: "assistant", + content: content, + isStreaming: false, + }, + ]); + currentStreamingMessage = null; + } + }, + onToolStart: (toolName: string, toolArgs?: any) => { + const formatToolCall = (name: string, args: any) => { + const displayName = getToolDisplayName(name); + if (!args) return displayName; + + const firstValue = Object.values(args)[0]; + const formatPath = (value: any) => { + if (typeof value === "string" && path.isAbsolute(value)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, value); + return relativePath || value; + } + return value; + }; + + return `${displayName}(${formatPath(firstValue) || ""})`; + }; + + if (currentStreamingMessage && currentStreamingMessage.content) { + const messageContent = currentStreamingMessage.content; + setMessages((prev) => [ + ...prev, + { + role: "assistant", + content: messageContent, + isStreaming: false, + }, + ]); + currentStreamingMessage = null; + } + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: formatToolCall(toolName, toolArgs), + messageType: "tool-start", + toolName, + }, + ]); + }, + onToolResult: (result: string, toolName: string) => { + setMessages((prev) => { + const newMessages = [...prev]; + for (let i = newMessages.length - 1; i >= 0; i--) { + if ( + newMessages[i].messageType === "tool-start" && + newMessages[i].toolName === toolName + ) { + newMessages[i] = { + ...newMessages[i], + messageType: "tool-result", + toolResult: result, + }; + break; + } + } + return newMessages; + }); + }, + onToolError: (error: string, toolName?: string) => { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: error, + messageType: "tool-error", + toolName, + }, + ]); + }, + }; + + await streamChatResponse( + newHistory, + model, + llmApi, + controller, + streamCallbacks + ); + + if (currentStreamingMessage && (currentStreamingMessage as any).content) { + const messageContent = (currentStreamingMessage as any).content; + setMessages((prev) => [ + ...prev, + { + role: "assistant", + content: messageContent, + isStreaming: false, + }, + ]); + } + + saveSession(newHistory); + } catch (error: any) { + const errorMessage = `Error: ${error.message}`; + setMessages((prev) => [ + ...prev, + { + role: "system", + content: errorMessage, + messageType: "system" as const, + }, + ]); + } finally { + setAbortController(null); + setIsWaitingForResponse(false); + setInputMode(true); + } + }; + + const handleInterrupt = () => { + if (abortController && isWaitingForResponse) { + abortController.abort(); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "[Interrupted by user]", + messageType: "system" as const, + }, + ]); + } + }; + + const handleFileAttached = (filePath: string, content: string) => { + setAttachedFiles((prev) => [...prev, { path: filePath, content }]); + }; + + const resetChatHistory = () => { + const rulesSystemMessage = ""; + const systemMessage = constructSystemMessage(rulesSystemMessage); + const newHistory = systemMessage + ? [{ role: "system" as const, content: systemMessage }] + : []; + setChatHistory(newHistory); + setMessages([]); + }; + + return { + messages, + setMessages, + chatHistory, + setChatHistory, + isWaitingForResponse, + inputMode, + attachedFiles, + handleUserMessage, + handleInterrupt, + handleFileAttached, + resetChatHistory, + }; +} diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx new file mode 100644 index 000000000..00984f87c --- /dev/null +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -0,0 +1,74 @@ +import { Box, Text } from "ink"; +import React from "react"; +import MarkdownRenderer from "../MarkdownRenderer.js"; +import ToolResultSummary from "../ToolResultSummary.js"; + +import { DisplayMessage } from "../types.js"; + +export function useMessageRenderer() { + const renderMessage = (message: DisplayMessage, index: number) => { + const isUser = message.role === "user"; + const isSystem = message.role === "system"; + + if (isSystem) { + switch (message.messageType) { + case "tool-start": + return ( + + ○ {message.content} + + ); + + case "tool-result": + return ( + + + ● + {message.content} + + + + + + ); + + case "tool-error": + return ( + + + ✗{" "} + + Tool error: {message.content} + + ); + + default: + return ( + + + {message.content} + + + ); + } + } + + return ( + + ● + + {isUser ? ( + {message.content} + ) : ( + + )} + {message.isStreaming && ▋} + + ); + }; + + return { renderMessage }; +} diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts new file mode 100644 index 000000000..f04106dee --- /dev/null +++ b/src/ui/hooks/useOrganizationSelector.ts @@ -0,0 +1,105 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { useState } from "react"; +import { initializeAssistant } from "../../assistant.js"; +import { loadAuthConfig, saveAuthConfig } from "../../auth/workos.js"; +import { introMessage } from "../../intro.js"; +import { MCPService } from "../../mcp.js"; + +interface UseOrganizationSelectorProps { + configPath?: string; + onAssistantChange: ( + assistant: AssistantUnrolled, + model: string, + llmApi: BaseLlmApi, + mcpService: MCPService + ) => void; + onMessage: (message: { + role: string; + content: string; + messageType: "system"; + }) => void; + onChatReset: () => void; +} + +export function useOrganizationSelector({ + configPath, + onAssistantChange, + onMessage, + onChatReset, +}: UseOrganizationSelectorProps) { + const [showOrgSelector, setShowOrgSelector] = useState(false); + + const handleOrganizationSelect = async ( + organizationId: string | null, + organizationName: string + ) => { + setShowOrgSelector(false); + + // Update auth config + const authConfig = loadAuthConfig(); + const updatedConfig = { + ...authConfig, + organizationId, + }; + saveAuthConfig(updatedConfig); + + try { + // Show loading message + onMessage({ + role: "system", + content: `Switching to organization: ${organizationName}...`, + messageType: "system" as const, + }); + + // Reinitialize assistant with new organization + const { + config, + llmApi: newLlmApi, + model: newModel, + mcpService: newMcpService, + } = await initializeAssistant(updatedConfig, configPath); + + // Update assistant configuration + onAssistantChange(config, newModel, newLlmApi, newMcpService); + + // Reset chat history + onChatReset(); + + // Clear the screen completely + process.stdout.write("\x1b[2J\x1b[H"); + + // Show the new intro message + introMessage(config, newModel, newMcpService); + + // Show success message + onMessage({ + role: "system", + content: `Successfully switched to organization: ${organizationName}`, + messageType: "system" as const, + }); + } catch (error: any) { + // Show error message + onMessage({ + role: "system", + content: `Failed to switch organization: ${error.message}`, + messageType: "system" as const, + }); + } + }; + + const handleOrganizationCancel = () => { + setShowOrgSelector(false); + }; + + const showOrganizationSelector = () => { + setShowOrgSelector(true); + }; + + return { + showOrgSelector, + handleOrganizationSelect, + handleOrganizationCancel, + showOrganizationSelector, + }; +} diff --git a/src/ui/types.ts b/src/ui/types.ts new file mode 100644 index 000000000..91ec986e5 --- /dev/null +++ b/src/ui/types.ts @@ -0,0 +1,8 @@ +export interface DisplayMessage { + role: string; + content: string; + isStreaming?: boolean; + messageType?: "tool-start" | "tool-result" | "tool-error" | "system"; + toolName?: string; + toolResult?: string; +} From ae77d34d903c3aa04f2a3e1cffdeb463e07333b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 17:56:58 -0700 Subject: [PATCH 6/7] don't overwrite organization --- src/auth/workos.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/auth/workos.ts b/src/auth/workos.ts index b87e2e039..9d2931a43 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -137,6 +137,9 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string { */ async function refreshToken(refreshToken: string): Promise { try { + // Load existing config to preserve organizationId and other fields + const existingConfig = loadAuthConfig(); + const response = await axios.post( new URL("auth/refresh", env.apiBase).toString(), { @@ -150,6 +153,7 @@ async function refreshToken(refreshToken: string): Promise { const tokenExpiresAt = Date.now() + 60 * 60 * 1000; const authConfig: AuthConfig = { + ...existingConfig, // Preserve existing fields like organizationId userId: user.id, userEmail: user.email, accessToken, @@ -415,4 +419,4 @@ export function logout(): void { } else { console.info(chalk.yellow("No active session found")); } -} +} \ No newline at end of file From 56965ab52f9492f00f09c6f15a3427f049d9b5ab Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 18:01:49 -0700 Subject: [PATCH 7/7] bump sdk version --- package-lock.json | 28 ++++++++-------------------- package.json | 3 +-- 2 files changed, 9 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index c2767957a..8ba587817 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@continuedev/config-yaml": "^1.0.96", "@continuedev/openai-adapters": "1.0.46-beta", - "@continuedev/sdk": "file:../continue/packages/continue-sdk/typescript", + "@continuedev/sdk": "^0.0.13", "@modelcontextprotocol/sdk": "^1.9.0", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5", @@ -34,8 +34,7 @@ "uuid": "^9.0.1" }, "bin": { - "cn": "dist/index.js", - "continue-cli": "dist/index.js" + "cn": "dist/index.js" }, "devDependencies": { "@semantic-release/changelog": "^6.0.3", @@ -59,21 +58,6 @@ "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", @@ -1451,8 +1435,12 @@ } }, "node_modules/@continuedev/sdk": { - "resolved": "../continue/packages/continue-sdk/typescript", - "link": true + "version": "0.0.13", + "resolved": "https://registry.npmjs.org/@continuedev/sdk/-/sdk-0.0.13.tgz", + "integrity": "sha512-3OvwfmngMpSYWUHbtgavLKSn9GsXgWoVUAAGT5wP5AJTPr4QSLnOTctY/2IYCbkfyCVa1rJtTqrUV/hez95nQQ==", + "dependencies": { + "openai": "^4.96.2" + } }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", diff --git a/package.json b/package.json index 737fb3b39..0201191be 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,6 @@ "types": "dist/index.d.ts", "type": "module", "bin": { - "continue-cli": "dist/index.js", "cn": "dist/index.js" }, "scripts": { @@ -34,7 +33,7 @@ "dependencies": { "@continuedev/config-yaml": "^1.0.96", "@continuedev/openai-adapters": "1.0.46-beta", - "@continuedev/sdk": "file:../continue/packages/continue-sdk/typescript", + "@continuedev/sdk": "^0.0.13", "@modelcontextprotocol/sdk": "^1.9.0", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5",