Merge pull request #30 from continuedev/nate/continue-sdk

use continue sdk
This commit is contained in:
Nate Sesti 2025-07-15 18:11:10 -07:00 • committed by GitHub
commit a91a5712a1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 1170 additions and 531 deletions

12
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": "^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",
@ -1436,10 +1435,9 @@
}
},
"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",
"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"
}

View file

@ -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": "^0.0.12",
"@continuedev/sdk": "^0.0.13",
"@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

126
src/assistant.ts Normal file
View file

@ -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: authConfig.organizationId ?? null,
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<AssistantUnrolled> {
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,
authConfig.organizationId ?? undefined
);
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = await MCPService.create(config);
return { config, llmApi, model, mcpService };
}

View file

@ -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;
}
/**
@ -132,9 +137,15 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string {
*/
async function refreshToken(refreshToken: string): Promise<AuthConfig> {
try {
const response = await axios.post(`${env.apiBase}/auth/refresh`, {
refreshToken,
});
// Load existing config to preserve organizationId and other fields
const existingConfig = loadAuthConfig();
const response = await axios.post(
new URL("auth/refresh", env.apiBase).toString(),
{
refreshToken,
}
);
const { accessToken, refreshToken: newRefreshToken, user } = response.data;
@ -142,6 +153,7 @@ async function refreshToken(refreshToken: string): Promise<AuthConfig> {
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
const authConfig: AuthConfig = {
...existingConfig, // Preserve existing fields like organizationId
userId: user.id,
userEmail: user.email,
accessToken,
@ -208,6 +220,186 @@ export async function login(
}
}
/**
* Ensures the user has selected an organization, prompting if necessary
*/
export async function ensureOrganization(
authConfig: AuthConfig,
isHeadless: boolean = false
): Promise<AuthConfig> {
// 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;
}
}
/**
* 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<boolean> {
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
*/
@ -227,4 +419,4 @@ export function logout(): void {
} else {
console.info(chalk.yellow("No active session found"));
}
}
}

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,23 +1,15 @@
#!/usr/bin/env node
import {
BaseLlmApi,
constructLlmApi,
LLMConfig,
} from "@continuedev/openai-adapters";
import { Assistant } from "@continuedev/sdk";
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { parseArgs } from "./args.js";
import { initializeAssistant } from "./assistant.js";
import { ensureAuthenticated } from "./auth/ensureAuth.js";
import { AuthConfig, loadAuthConfig } from "./auth/workos.js";
import { initializeContinueSDK } from "./continueSDK.js";
import { ensureOrganization, 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";
import { constructSystemMessage } from "./systemMessage.js";
import { startTUIChat } from "./ui/index.js";
@ -28,63 +20,7 @@ const args = parseArgs();
// Configure logger based on headless mode
configureLogger(args.isHeadless);
function getLlmApi(
assistant: Assistant,
authConfig: AuthConfig
): [BaseLlmApi, string] {
const model = assistant.config.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,
configPath: string
): Promise<Assistant> {
const continueSdk = await initializeContinueSDK(accessToken, configPath);
return continueSdk.assistant;
}
async function chat() {
async function initializeChat() {
const isAuthenticated = await ensureAuthenticated(true);
if (!isAuthenticated) {
@ -94,57 +30,40 @@ 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 assistant = await loadAssistant(
authConfig.accessToken,
const { config, llmApi, model, mcpService } = await initializeAssistant(
authConfigWithOrg,
args.configPath
);
const [llmApi, model] = getLlmApi(assistant, authConfig);
const mcpService = await MCPService.create(assistant.config);
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(
assistant,
config,
llmApi,
model,
mcpService,
args.prompt,
args.resume
args.resume,
args.configPath
);
return;
}
// Show intro message for headless mode
introMessage(assistant, mcpService);
introMessage(config, model, mcpService);
// Rules
let chatHistory: ChatCompletionMessageParam[] = [];
@ -162,7 +81,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 });
@ -184,22 +103,6 @@ async function chat() {
isFirstMessage = false;
// Handle slash commands
const commandResult = handleSlashCommands(userInput, assistant.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 });

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("\nRules: " + 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

@ -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) {

View file

@ -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<OrganizationSelectorProps> = ({
onSelect,
onCancel,
}) => {
const [organizations, setOrganizations] = useState<Organization[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [currentOrgId, setCurrentOrgId] = useState<string | null | undefined>();
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 (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text color="blue" bold>
Organization Selector
</Text>
<Text color="gray">Loading organizations...</Text>
</Box>
);
}
if (error) {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="red"
>
<Text color="red" bold>
Error
</Text>
<Text color="red">{error}</Text>
<Text color="gray" dimColor>
Press Escape to cancel
</Text>
</Box>
);
}
const allOptions = [
{ id: null, name: "Personal", isCurrent: currentOrgId === null },
...organizations.map((org) => ({
...org,
isCurrent: currentOrgId === org.id,
})),
];
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text color="blue" bold>
Select Organization
</Text>
<Box flexDirection="column" marginTop={1}>
{allOptions.map((option, index) => {
const isSelected = index === selectedIndex;
const isCurrent = option.isCurrent;
return (
<Box key={option.id || "personal"}>
<Text
color={isSelected ? "blue" : "white"}
bold={isSelected}
inverse={isSelected}
>
{isSelected ? "▶ " : " "}
{option.name}
{isCurrent ? " (current)" : ""}
</Text>
</Box>
);
})}
</Box>
<Box marginTop={1}>
<Text color="gray" dimColor>
Use ↑/↓ to navigate, Enter to select, Escape to cancel
</Text>
</Box>
</Box>
);
};
export default OrganizationSelector;

View file

@ -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<SlashCommandUIProps> = ({
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<SlashCommandUIProps> = ({
description: "Check who you're currently logged in as",
category: "system",
},
...(hasMultipleOrgs ? [{
name: "org",
description: "Switch organization",
category: "system" as const,
}] : []),
];
const assistantCommands: SlashCommand[] =

View file

@ -1,396 +1,80 @@
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";
import React, { 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 { Box, Text } from "ink";
import React, { useState } from "react";
import { MCPService } from "../mcp.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 ToolResultSummary from "./ToolResultSummary.js";
import OrganizationSelector from "./OrganizationSelector.js";
import UserInput from "./UserInput.js";
interface TUIChatProps {
assistant: ContinueClient["assistant"];
config: AssistantUnrolled;
model: string;
llmApi: BaseLlmApi;
mcpService: MCPService;
configPath?: string;
initialPrompt?: string;
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<TUIChatProps> = ({
assistant,
model,
llmApi,
config: initialAssistant,
model: initialModel,
llmApi: initialLlmApi,
mcpService: initialMcpService,
configPath,
initialPrompt,
resume,
}) => {
const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
() => {
let history: ChatCompletionMessageParam[] = [];
// 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);
// 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 = 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<DisplayMessage[]>(() => {
// 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<AbortController | null>(null);
const [attachedFiles, setAttachedFiles] = useState<
Array<{ path: string; content: string }>
>([]);
const { exit } = useApp();
// Handle initial prompt
useEffect(() => {
if (initialPrompt) {
handleUserMessage(initialPrompt);
}
}, [initialPrompt]);
const { renderMessage } = useMessageRenderer();
const handleUserMessage = async (message: string) => {
// Handle slash commands
const commandResult = handleSlashCommands(message, assistant.config);
if (commandResult) {
if (commandResult.exit) {
exit();
return;
}
const {
showOrgSelector,
handleOrganizationSelect,
handleOrganizationCancel,
showOrganizationSelector,
} = useOrganizationSelector({
configPath,
onAssistantChange: (newAssistant, newModel, newLlmApi, newMcpService) => {
setAssistant(newAssistant);
setModel(newModel);
setLlmApi(newLlmApi);
setMcpService(newMcpService);
},
onMessage: (message) => {
setMessages((prev) => [...prev, message]);
},
onChatReset: resetChatHistory,
});
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<file path="${file.path}">\n${file.content}\n</file>`
)
.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 (
<Box key={index} marginBottom={1}>
<Text color="white">○ {message.content}</Text>
</Box>
);
case "tool-result":
return (
<Box key={index} marginBottom={1} flexDirection="column">
<Box>
<Text color="green">●</Text>
<Text> {message.content}</Text>
</Box>
<Box marginLeft={2}>
<ToolResultSummary
toolName={message.toolName}
content={message.toolResult || ""}
/>
</Box>
</Box>
);
case "tool-error":
return (
<Box key={index} marginBottom={1}>
<Text color="red" bold>
✗{" "}
</Text>
<Text color="red">Tool error: {message.content}</Text>
</Box>
);
default:
// Regular system messages
return (
<Box key={index} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
}
}
return (
<Box key={index} marginBottom={1}>
<Text color={isUser ? "green" : "blue"}>●</Text>
<Text> </Text>
{isUser ? (
<Text>{message.content}</Text>
) : (
<MarkdownRenderer content={message.content} />
)}
{message.isStreaming && <Text color="gray">▋</Text>}
</Box>
);
};
return (
<Box flexDirection="column" height="100%">
@ -409,14 +93,23 @@ const TUIChat: React.FC<TUIChatProps> = ({
</Box>
)}
{/* Organization selector - shows above input when active */}
{showOrgSelector && (
<OrganizationSelector
onSelect={handleOrganizationSelect}
onCancel={handleOrganizationCancel}
/>
)}
{/* Input area - always at bottom */}
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant.config}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={showOrgSelector}
/>
<Box marginRight={2} justifyContent="flex-end">
<Text color="gray">● Continue CLI</Text>

View file

@ -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<UserInputProps> = ({
@ -22,6 +24,7 @@ const UserInput: React.FC<UserInputProps> = ({
onInterrupt,
assistant,
onFileAttached,
disabled = false,
}) => {
const [textBuffer] = useState(() => new TextBuffer());
const [inputHistory] = useState(() => new InputHistory());
@ -39,6 +42,12 @@ const UserInput: React.FC<UserInputProps> = ({
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<UserInputProps> = ({
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<UserInputProps> = ({
};
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<UserInputProps> = ({
}
};
// Don't render anything when disabled
if (disabled) {
return null;
}
return (
<Box flexDirection="column">
{/* Input box */}

348
src/ui/hooks/useChat.ts Normal file
View file

@ -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<ChatCompletionMessageParam[]>(
() => {
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<DisplayMessage[]>(() => {
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<AbortController | null>(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<file path="${file.path}">\n${file.content}\n</file>`
)
.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,
};
}

View file

@ -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 (
<Box key={index} marginBottom={1}>
<Text color="white">○ {message.content}</Text>
</Box>
);
case "tool-result":
return (
<Box key={index} marginBottom={1} flexDirection="column">
<Box>
<Text color="green">●</Text>
<Text> {message.content}</Text>
</Box>
<Box marginLeft={2}>
<ToolResultSummary
toolName={message.toolName}
content={message.toolResult || ""}
/>
</Box>
</Box>
);
case "tool-error":
return (
<Box key={index} marginBottom={1}>
<Text color="red" bold>
✗{" "}
</Text>
<Text color="red">Tool error: {message.content}</Text>
</Box>
);
default:
return (
<Box key={index} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
}
}
return (
<Box key={index} marginBottom={1}>
<Text color={isUser ? "green" : "blue"}>●</Text>
<Text> </Text>
{isUser ? (
<Text>{message.content}</Text>
) : (
<MarkdownRenderer content={message.content} />
)}
{message.isStreaming && <Text color="gray">▋</Text>}
</Box>
);
};
return { renderMessage };
}

View file

@ -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,
};
}

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,22 +9,25 @@ 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,
initialPrompt?: string,
resume?: boolean
resume?: boolean,
configPath?: string
) {
// 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,
mcpService,
configPath,
initialPrompt,
resume,
})

8
src/ui/types.ts Normal file
View file

@ -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;
}