Elffuss BraidHub

kikocis/continue public

e0b45db6ff5d · 9.4 KiBRawPermalink
1import { execSync } from "child_process";
2import fs from "fs";
3import os from "os";
4import path from "path";
5
6import { ChatCompletionMessageParam } from "openai/resources.mjs";
7
8import { logger } from "./util/logger.js";
9
10// List of known terminal process names
11const TERMINAL_PROCESSES = [
12 "Terminal",
13 "iTerm",
14 "tmux",
15 "screen",
16 "bash",
17 "zsh",
18 "fish",
19 "kitty",
20 "alacritty",
21 "wt", // Windows Terminal
22 "cmd", // Windows Command Prompt
23 "powershell",
24];
25
26// Check if a process name looks like a terminal
27function isTerminalProcess(comm: string): boolean {
28 if (!comm) return false;
29 return TERMINAL_PROCESSES.some((term) => comm.includes(term));
30}
31
32/**
33 * Get the terminal process ID by walking up the process tree
34 */
35function getTerminalProcessId(): string | null {
36 try {
37 // Skip on Windows - ps command doesn't exist
38 if (os.platform() === "win32") {
39 return null;
40 }
41
42 // Get parent process info by walking up the tree
43 let currentPid = process.ppid;
44
45 for (let i = 0; i < 10 && currentPid; i++) {
46 try {
47 const psOutput = execSync(`ps -o pid,ppid,comm -p ${currentPid}`, {
48 encoding: "utf8",
49 timeout: 1000,
50 stdio: ["ignore", "pipe", "ignore"], // Suppress stderr
51 }).trim();
52
53 const lines = psOutput.split("\n");
54 if (lines.length < 2) break;
55
56 const processInfo = lines[1].trim().split(/\s+/);
57 const [pid, ppid, comm] = processInfo;
58
59 // Check if this looks like a terminal process
60 if (isTerminalProcess(comm)) {
61 return pid;
62 }
63
64 const nextPid = parseInt(ppid);
65 if (isNaN(nextPid) || nextPid <= 1) break;
66 currentPid = nextPid;
67 } catch {
68 // Continue to next iteration if this process lookup fails
69 break;
70 }
71 }
72 } catch {
73 // Silently fail - this is a fallback mechanism
74 }
75
76 return null;
77}
78
79/**
80 * Get the TTY device path for unique terminal identification
81 */
82function getTtyPath(): string | null {
83 try {
84 // Skip on Windows - tty command doesn't exist
85 if (os.platform() === "win32") {
86 return null;
87 }
88
89 if (process.stdin.isTTY) {
90 // Get the TTY device path
91 const ttyPath = execSync("tty", {
92 encoding: "utf8",
93 timeout: 1000,
94 stdio: ["ignore", "pipe", "ignore"], // Suppress stderr
95 }).trim();
96
97 if (
98 ttyPath &&
99 ttyPath !== "not a tty" &&
100 !ttyPath.includes("not found")
101 ) {
102 // Convert /dev/ttys002 to ttys002 for cleaner ID
103 return ttyPath.replace("/dev/", "");
104 }
105 }
106 } catch {
107 // Silently fail - this is a fallback mechanism
108 }
109
110 return null;
111}
112
113/**
114 * Get a unique session identifier for the current terminal session
115 * Uses environment variables to ensure each terminal window has its own session
116 */
117function getSessionId(): string {
118 // For tests, use a specific session ID if provided
119 if (process.env.CONTINUE_CLI_TEST_SESSION_ID) {
120 return `continue-cli-${process.env.CONTINUE_CLI_TEST_SESSION_ID}`;
121 }
122
123 // Try environment variables first (most reliable)
124 const envSession =
125 process.env.TMUX_PANE ||
126 process.env.TERM_SESSION_ID ||
127 process.env.SSH_TTY ||
128 process.env.TMUX ||
129 process.env.STY;
130
131 if (envSession) {
132 const cleanSessionId = envSession.replace(/[^a-zA-Z0-9-_]/g, "-");
133 return `continue-cli-${cleanSessionId}`;
134 }
135
136 // Fallback 1: Try to get TTY device path (unique per terminal window)
137 const ttyPath = getTtyPath();
138 if (ttyPath) {
139 const cleanTtyId = ttyPath.replace(/[^a-zA-Z0-9-_]/g, "-");
140 return `continue-cli-tty-${cleanTtyId}`;
141 }
142
143 // Fallback 2: Try to get terminal process ID (unique per terminal process)
144 const terminalPid = getTerminalProcessId();
145 if (terminalPid) {
146 return `continue-cli-term-${terminalPid}`;
147 }
148
149 // Final fallback: Use process PID (least reliable but always available)
150 return `continue-cli-pid-${process.pid}`;
151}
152
153/**
154 * Get the session storage directory
155 */
156function getSessionDir(): string {
157 // For tests, use the test directory if we're in test mode
158 if (process.env.CONTINUE_CLI_TEST && process.env.HOME) {
159 const sessionDir = path.join(process.env.HOME, ".continue", "cli-sessions");
160
161 // Create directory if it doesn't exist
162 if (!fs.existsSync(sessionDir)) {
163 fs.mkdirSync(sessionDir, { recursive: true });
164 }
165
166 return sessionDir;
167 }
168
169 const homeDir = os.homedir();
170 const sessionDir = path.join(homeDir, ".continue", "cli-sessions");
171
172 // Create directory if it doesn't exist
173 if (!fs.existsSync(sessionDir)) {
174 fs.mkdirSync(sessionDir, { recursive: true });
175 }
176
177 return sessionDir;
178}
179
180/**
181 * Get the session file path for the current session
182 */
183function getSessionFilePath(): string {
184 const sessionId = getSessionId();
185 const sessionDir = getSessionDir();
186 return path.join(sessionDir, `${sessionId}.json`);
187}
188
189/**
190 * Save chat history to session file
191 */
192export function saveSession(chatHistory: ChatCompletionMessageParam[]): void {
193 try {
194 const sessionFilePath = getSessionFilePath();
195 const sessionData = {
196 timestamp: new Date().toISOString(),
197 chatHistory,
198 };
199
200 fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2));
201 } catch (error) {
202 logger.error("Error saving session:", error);
203 }
204}
205
206/**
207 * Load chat history from session file
208 */
209export function loadSession(): ChatCompletionMessageParam[] | null {
210 try {
211 const sessionFilePath = getSessionFilePath();
212
213 if (!fs.existsSync(sessionFilePath)) {
214 return null;
215 }
216
217 const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
218 return sessionData.chatHistory || null;
219 } catch (error) {
220 logger.error("Error loading session:", error);
221 return null;
222 }
223}
224
225/**
226 * Clear the current session
227 */
228export function clearSession(): void {
229 try {
230 const sessionFilePath = getSessionFilePath();
231 if (fs.existsSync(sessionFilePath)) {
232 fs.unlinkSync(sessionFilePath);
233 }
234 } catch (error) {
235 logger.error("Error clearing session:", error);
236 }
237}
238
239/**
240 * Check if a session exists for the current terminal
241 */
242export function hasSession(): boolean {
243 const sessionFilePath = getSessionFilePath();
244 return fs.existsSync(sessionFilePath);
245}
246
247/**
248 * Session metadata for listing sessions
249 */
250export interface SessionMetadata {
251 id: string; // Session ID from filename
252 path: string; // Full file path
253 timestamp: Date; // Last modified or session timestamp
254 messageCount: number; // Total messages in session
255 firstUserMessage?: string; // Preview of first user input
256}
257
258/**
259 * Get metadata from a session file
260 */
261function getSessionMetadata(filePath: string): SessionMetadata | null {
262 try {
263 const fileName = path.basename(filePath, ".json");
264 const stats = fs.statSync(filePath);
265 const sessionData = JSON.parse(fs.readFileSync(filePath, "utf8"));
266
267 const chatHistory = sessionData.chatHistory || [];
268 const messageCount = chatHistory.length;
269
270 // Find the first user message
271 let firstUserMessage: string | undefined;
272 for (let i = 0; i < chatHistory.length; i++) {
273 if (chatHistory[i].role === "user") {
274 const content = chatHistory[i].content;
275 // Handle both string and array content types
276 if (typeof content === "string") {
277 firstUserMessage = content;
278 } else if (Array.isArray(content)) {
279 // For array content, find the first text part
280 const textPart = content.find((part) => part.type === "text");
281 firstUserMessage = textPart?.text || "(multimodal message)";
282 } else {
283 firstUserMessage = "(unknown content type)";
284 }
285 break;
286 }
287 }
288
289 // Use session timestamp if available, otherwise file modification time
290 const timestamp = sessionData.timestamp
291 ? new Date(sessionData.timestamp)
292 : stats.mtime;
293
294 return {
295 id: fileName,
296 path: filePath,
297 timestamp,
298 messageCount,
299 firstUserMessage,
300 };
301 } catch (error) {
302 logger.error(`Error reading session file ${filePath}:`, error);
303 return null;
304 }
305}
306
307/**
308 * List all available sessions with metadata
309 */
310export function listSessions(limit: number = 10): SessionMetadata[] {
311 try {
312 const sessionDir = getSessionDir();
313
314 if (!fs.existsSync(sessionDir)) {
315 return [];
316 }
317
318 const files = fs
319 .readdirSync(sessionDir)
320 .filter((file) => file.endsWith(".json"))
321 .map((file) => path.join(sessionDir, file));
322
323 const sessions: SessionMetadata[] = [];
324
325 for (const filePath of files) {
326 const metadata = getSessionMetadata(filePath);
327 if (metadata) {
328 sessions.push(metadata);
329 }
330 }
331
332 // Sort by timestamp (most recent first) and limit results
333 return sessions
334 .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
335 .slice(0, limit);
336 } catch (error) {
337 logger.error("Error listing sessions:", error);
338 return [];
339 }
340}
341
342/**
343 * Load chat history from a specific session file
344 */
345export function loadSessionById(
346 sessionId: string,
347): ChatCompletionMessageParam[] | null {
348 try {
349 const sessionDir = getSessionDir();
350 const sessionFilePath = path.join(sessionDir, `${sessionId}.json`);
351
352 if (!fs.existsSync(sessionFilePath)) {
353 return null;
354 }
355
356 const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
357 return sessionData.chatHistory || null;
358 } catch (error) {
359 logger.error("Error loading session by ID:", error);
360 return null;
361 }
362}