feat: add session management with --resume flag and cn alias
This commit is contained in:
parent
bf1680d364
commit
0096fbcc49
8 changed files with 218 additions and 17 deletions
38
README.md
38
README.md
|
|
@ -19,3 +19,41 @@ cn
|
||||||
```bash
|
```bash
|
||||||
cn --headless "Generate a conventional commit name for the current git changes."
|
cn --headless "Generate a conventional commit name for the current git changes."
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Session Management
|
||||||
|
|
||||||
|
The CLI automatically saves your chat history for each terminal session. You can resume where you left off:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Resume the last session in this terminal
|
||||||
|
cn --resume
|
||||||
|
```
|
||||||
|
|
||||||
|
Each terminal window maintains its own separate session, so you can have multiple concurrent conversations without them interfering with each other.
|
||||||
|
|
||||||
|
### Advanced Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Resume session with specific assistant
|
||||||
|
cn --resume --config my-assistant
|
||||||
|
|
||||||
|
# Resume session in headless mode
|
||||||
|
cn --resume --headless
|
||||||
|
```
|
||||||
|
|
||||||
|
## Command Line Options
|
||||||
|
|
||||||
|
- `--headless`: Run in headless mode (no TUI)
|
||||||
|
- `--config <path>`: Specify assistant configuration path
|
||||||
|
- `--resume`: Resume the last session for this terminal
|
||||||
|
- `<prompt>`: Optional prompt to start with
|
||||||
|
|
||||||
|
## Session Storage
|
||||||
|
|
||||||
|
Sessions are stored in `~/.continue-cli/sessions/` and are automatically managed per terminal window using environment variables like:
|
||||||
|
- `TERM_SESSION_ID`
|
||||||
|
- `SSH_TTY`
|
||||||
|
- `TMUX`
|
||||||
|
- `STY`
|
||||||
|
|
||||||
|
If none of these are available, the process ID is used as a fallback.
|
||||||
|
|
|
||||||
8
package-lock.json
generated
8
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "@continuedev/cli",
|
"name": "@continuedev/cli",
|
||||||
"version": "1.1.0",
|
"version": "1.2.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@continuedev/cli",
|
"name": "@continuedev/cli",
|
||||||
"version": "1.1.0",
|
"version": "1.2.0",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@continuedev/openai-adapters": "^1.0.18",
|
"@continuedev/openai-adapters": "^1.0.18",
|
||||||
|
|
@ -24,9 +24,11 @@
|
||||||
"open": "^10.1.0",
|
"open": "^10.1.0",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"readline-sync": "^1.4.10",
|
"readline-sync": "^1.4.10",
|
||||||
|
"typescript": "^5.8.3",
|
||||||
"uuid": "^9.0.1"
|
"uuid": "^9.0.1"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
|
"cn": "dist/index.js",
|
||||||
"continue-cli": "dist/index.js"
|
"continue-cli": "dist/index.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
@ -13580,9 +13582,7 @@
|
||||||
"version": "5.8.3",
|
"version": "5.8.3",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
|
||||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@
|
||||||
"open": "^10.1.0",
|
"open": "^10.1.0",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"readline-sync": "^1.4.10",
|
"readline-sync": "^1.4.10",
|
||||||
|
"typescript": "^5.8.3",
|
||||||
"uuid": "^9.0.1"
|
"uuid": "^9.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ export interface CommandLineArgs {
|
||||||
isHeadless: boolean;
|
isHeadless: boolean;
|
||||||
configPath: string;
|
configPath: string;
|
||||||
prompt?: string; // Optional prompt argument
|
prompt?: string; // Optional prompt argument
|
||||||
|
resume?: boolean; // Resume from last session
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -22,6 +23,10 @@ export function parseArgs(): CommandLineArgs {
|
||||||
result.isHeadless = true;
|
result.isHeadless = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (args.includes("--resume")) {
|
||||||
|
result.resume = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Get config path from --config flag
|
// Get config path from --config flag
|
||||||
const configIndex = args.indexOf("--config");
|
const configIndex = args.indexOf("--config");
|
||||||
if (configIndex !== -1 && configIndex + 1 < args.length) {
|
if (configIndex !== -1 && configIndex + 1 < args.length) {
|
||||||
|
|
|
||||||
30
src/index.ts
30
src/index.ts
|
|
@ -15,6 +15,7 @@ import { handleSlashCommands } from "./slashCommands.js";
|
||||||
import { streamChatResponse } from "./streamChatResponse.js";
|
import { streamChatResponse } from "./streamChatResponse.js";
|
||||||
import { constructSystemMessage } from "./systemMessage.js";
|
import { constructSystemMessage } from "./systemMessage.js";
|
||||||
import { startTUIChat } from "./ui/index.js";
|
import { startTUIChat } from "./ui/index.js";
|
||||||
|
import { loadSession, saveSession, hasSession } from "./session.js";
|
||||||
|
|
||||||
// Parse command line arguments
|
// Parse command line arguments
|
||||||
const args = parseArgs();
|
const args = parseArgs();
|
||||||
|
|
@ -84,7 +85,7 @@ async function chat() {
|
||||||
|
|
||||||
// If not in headless mode, start the TUI chat (default)
|
// If not in headless mode, start the TUI chat (default)
|
||||||
if (!args.isHeadless) {
|
if (!args.isHeadless) {
|
||||||
await startTUIChat(assistant, client, mcpService, args.prompt);
|
await startTUIChat(assistant, client, mcpService, args.prompt, args.resume);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -92,11 +93,26 @@ async function chat() {
|
||||||
introMessage(assistant, mcpService);
|
introMessage(assistant, mcpService);
|
||||||
|
|
||||||
// Rules
|
// Rules
|
||||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
let chatHistory: ChatCompletionMessageParam[] = [];
|
||||||
const rulesSystemMessage = assistant.systemMessage;
|
|
||||||
const systemMessage = constructSystemMessage(rulesSystemMessage);
|
// Load previous session if --resume flag is used
|
||||||
if (systemMessage) {
|
if (args.resume) {
|
||||||
chatHistory.push({ role: "system", content: systemMessage });
|
const savedHistory = loadSession();
|
||||||
|
if (savedHistory) {
|
||||||
|
chatHistory = savedHistory;
|
||||||
|
console.log(chalk.yellow("Resuming previous session..."));
|
||||||
|
} else {
|
||||||
|
console.log(chalk.yellow("No previous session found, starting fresh..."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no session loaded or not resuming, initialize with system message
|
||||||
|
if (chatHistory.length === 0) {
|
||||||
|
const rulesSystemMessage = assistant.systemMessage;
|
||||||
|
const systemMessage = constructSystemMessage(rulesSystemMessage);
|
||||||
|
if (systemMessage) {
|
||||||
|
chatHistory.push({ role: "system", content: systemMessage });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let isFirstMessage = true;
|
let isFirstMessage = true;
|
||||||
|
|
@ -141,6 +157,8 @@ async function chat() {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await streamChatResponse(chatHistory, assistant, client);
|
await streamChatResponse(chatHistory, assistant, client);
|
||||||
|
// Save session after each successful response
|
||||||
|
saveSession(chatHistory);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
||||||
console.info(
|
console.info(
|
||||||
|
|
|
||||||
104
src/session.ts
Normal file
104
src/session.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
import os from "os";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a unique session identifier for the current terminal session
|
||||||
|
* Uses environment variables to ensure each terminal window has its own session
|
||||||
|
*/
|
||||||
|
function getSessionId(): string {
|
||||||
|
// Use a combination of terminal session ID and process ID to ensure uniqueness
|
||||||
|
const terminalSession = process.env.TERM_SESSION_ID ||
|
||||||
|
process.env.SSH_TTY ||
|
||||||
|
process.env.TMUX ||
|
||||||
|
process.env.STY ||
|
||||||
|
process.pid.toString();
|
||||||
|
|
||||||
|
// Clean up the session ID to be filesystem-safe
|
||||||
|
const cleanSessionId = terminalSession.replace(/[^a-zA-Z0-9-_]/g, '-');
|
||||||
|
|
||||||
|
return `continue-cli-${cleanSessionId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the session storage directory
|
||||||
|
*/
|
||||||
|
function getSessionDir(): string {
|
||||||
|
const homeDir = os.homedir();
|
||||||
|
const sessionDir = path.join(homeDir, '.continue-cli', 'sessions');
|
||||||
|
|
||||||
|
// Create directory if it doesn't exist
|
||||||
|
if (!fs.existsSync(sessionDir)) {
|
||||||
|
fs.mkdirSync(sessionDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return sessionDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the session file path for the current session
|
||||||
|
*/
|
||||||
|
function getSessionFilePath(): string {
|
||||||
|
const sessionId = getSessionId();
|
||||||
|
const sessionDir = getSessionDir();
|
||||||
|
return path.join(sessionDir, `${sessionId}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save chat history to session file
|
||||||
|
*/
|
||||||
|
export function saveSession(chatHistory: ChatCompletionMessageParam[]): void {
|
||||||
|
try {
|
||||||
|
const sessionFilePath = getSessionFilePath();
|
||||||
|
const sessionData = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
chatHistory
|
||||||
|
};
|
||||||
|
|
||||||
|
fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving session:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load chat history from session file
|
||||||
|
*/
|
||||||
|
export function loadSession(): ChatCompletionMessageParam[] | null {
|
||||||
|
try {
|
||||||
|
const sessionFilePath = getSessionFilePath();
|
||||||
|
|
||||||
|
if (!fs.existsSync(sessionFilePath)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, 'utf8'));
|
||||||
|
return sessionData.chatHistory || null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading session:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the current session
|
||||||
|
*/
|
||||||
|
export function clearSession(): void {
|
||||||
|
try {
|
||||||
|
const sessionFilePath = getSessionFilePath();
|
||||||
|
if (fs.existsSync(sessionFilePath)) {
|
||||||
|
fs.unlinkSync(sessionFilePath);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error clearing session:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a session exists for the current terminal
|
||||||
|
*/
|
||||||
|
export function hasSession(): boolean {
|
||||||
|
const sessionFilePath = getSessionFilePath();
|
||||||
|
return fs.existsSync(sessionFilePath);
|
||||||
|
}
|
||||||
|
|
@ -7,6 +7,7 @@ import { handleSlashCommands } from "../slashCommands.js";
|
||||||
import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js";
|
import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js";
|
||||||
import { constructSystemMessage } from "../systemMessage.js";
|
import { constructSystemMessage } from "../systemMessage.js";
|
||||||
import { getToolDisplayName } from "../tools.js";
|
import { getToolDisplayName } from "../tools.js";
|
||||||
|
import { loadSession, saveSession, hasSession } from "../session.js";
|
||||||
import LoadingAnimation from "./LoadingAnimation.js";
|
import LoadingAnimation from "./LoadingAnimation.js";
|
||||||
import ToolResultSummary from "./ToolResultSummary.js";
|
import ToolResultSummary from "./ToolResultSummary.js";
|
||||||
import UserInput from "./UserInput.js";
|
import UserInput from "./UserInput.js";
|
||||||
|
|
@ -15,6 +16,7 @@ interface TUIChatProps {
|
||||||
assistant: ContinueClient["assistant"];
|
assistant: ContinueClient["assistant"];
|
||||||
client: ContinueClient["client"];
|
client: ContinueClient["client"];
|
||||||
initialPrompt?: string;
|
initialPrompt?: string;
|
||||||
|
resume?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DisplayMessage {
|
interface DisplayMessage {
|
||||||
|
|
@ -30,21 +32,49 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
||||||
assistant,
|
assistant,
|
||||||
client,
|
client,
|
||||||
initialPrompt,
|
initialPrompt,
|
||||||
|
resume,
|
||||||
}) => {
|
}) => {
|
||||||
const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
|
const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
|
||||||
() => {
|
() => {
|
||||||
const history: ChatCompletionMessageParam[] = [];
|
let history: ChatCompletionMessageParam[] = [];
|
||||||
const rulesSystemMessage = assistant.systemMessage;
|
|
||||||
const systemMessage = constructSystemMessage(rulesSystemMessage);
|
// Load previous session if --resume flag is used
|
||||||
if (systemMessage) {
|
if (resume) {
|
||||||
history.push({ role: "system", content: systemMessage });
|
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;
|
return history;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
|
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
|
||||||
const [messages, setMessages] = useState<DisplayMessage[]>([]);
|
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 [inputMode, setInputMode] = useState(true);
|
const [inputMode, setInputMode] = useState(true);
|
||||||
const [abortController, setAbortController] =
|
const [abortController, setAbortController] =
|
||||||
useState<AbortController | null>(null);
|
useState<AbortController | null>(null);
|
||||||
|
|
@ -230,6 +260,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
||||||
{ role: "assistant", content: messageContent, isStreaming: false }
|
{ role: "assistant", content: messageContent, isStreaming: false }
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Save session after successful response
|
||||||
|
saveSession(newHistory);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
const errorMessage = `Error: ${error.message}`;
|
const errorMessage = `Error: ${error.message}`;
|
||||||
setMessages((prev) => [
|
setMessages((prev) => [
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,8 @@ export async function startTUIChat(
|
||||||
assistant: ContinueClient["assistant"],
|
assistant: ContinueClient["assistant"],
|
||||||
client: ContinueClient["client"],
|
client: ContinueClient["client"],
|
||||||
mcpService: MCPService,
|
mcpService: MCPService,
|
||||||
initialPrompt?: string
|
initialPrompt?: string,
|
||||||
|
resume?: boolean
|
||||||
) {
|
) {
|
||||||
// Show intro message before starting TUI
|
// Show intro message before starting TUI
|
||||||
introMessage(assistant, mcpService);
|
introMessage(assistant, mcpService);
|
||||||
|
|
@ -20,6 +21,7 @@ export async function startTUIChat(
|
||||||
assistant,
|
assistant,
|
||||||
client,
|
client,
|
||||||
initialPrompt,
|
initialPrompt,
|
||||||
|
resume,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue