Elffuss BraidHub

kikocis/continue public

fc89067dc2f1 · 18.3 KiBRawPermalink
1import { exec } from "child_process";
2import path from "path";
3import { promisify } from "util";
4
5import chalk from "chalk";
6import express, { Request, Response } from "express";
7import type { ChatCompletionMessageParam } from "openai/resources.mjs";
8
9import { getAssistantSlug } from "../auth/workos.js";
10import { processCommandFlags } from "../flags/flagProcessor.js";
11import { toolPermissionManager } from "../permissions/permissionManager.js";
12import {
13 getService,
14 initializeServices,
15 SERVICE_NAMES,
16} from "../services/index.js";
17import {
18 AuthServiceState,
19 ConfigServiceState,
20 ModelServiceState,
21} from "../services/types.js";
22import { saveSession } from "../session.js";
23import { streamChatResponse } from "../streamChatResponse.js";
24import { StreamCallbacks } from "../streamChatResponse.types.js";
25import { constructSystemMessage } from "../systemMessage.js";
26import { telemetryService } from "../telemetry/telemetryService.js";
27import { getToolDisplayName } from "../tools/index.js";
28import { DisplayMessage } from "../ui/types.js";
29import { formatError } from "../util/formatError.js";
30import { logger } from "../util/logger.js";
31import { readStdinSync } from "../util/stdin.js";
32
33import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
34
35const execAsync = promisify(exec);
36
37interface ServeOptions extends ExtendedCommandOptions {
38 timeout?: string;
39 port?: string;
40}
41
42interface PendingPermission {
43 toolName: string;
44 toolArgs: any;
45 requestId: string;
46 timestamp: number;
47}
48
49interface ServerState {
50 chatHistory: ChatCompletionMessageParam[];
51 displayMessages: DisplayMessage[]; // Messages formatted for display with tool info
52 config: any;
53 model: any;
54 isProcessing: boolean;
55 lastActivity: number;
56 messageQueue: string[];
57 currentAbortController: AbortController | null;
58 shouldInterrupt: boolean;
59 serverRunning: boolean;
60 pendingPermission: PendingPermission | null;
61}
62
63export async function serve(prompt?: string, options: ServeOptions = {}) {
64 // Check if prompt should come from stdin instead of parameter
65 let actualPrompt = prompt;
66 if (!prompt) {
67 // Try to read from stdin (for piped input like: cat file | cn serve)
68 const stdinInput = readStdinSync();
69 if (stdinInput) {
70 actualPrompt = stdinInput;
71 }
72 }
73
74 const timeoutSeconds = parseInt(options.timeout || "300", 10);
75 const timeoutMs = timeoutSeconds * 1000;
76 const port = parseInt(options.port || "8000", 10);
77
78 // Initialize services with tool permission overrides
79 const { permissionOverrides } = processCommandFlags(options);
80
81 await initializeServices({
82 options,
83 toolPermissionOverrides: permissionOverrides,
84 headless: true, // Skip onboarding in serve mode
85 });
86
87 // Get initialized services from the service container
88 const [configState, modelState] = await Promise.all([
89 getService<ConfigServiceState>(SERVICE_NAMES.CONFIG),
90 getService<ModelServiceState>(SERVICE_NAMES.MODEL),
91 ]);
92
93 if (!configState.config || !modelState.llmApi || !modelState.model) {
94 throw new Error("Failed to initialize required services");
95 }
96
97 const { config, llmApi, model } = {
98 config: configState.config,
99 llmApi: modelState.llmApi,
100 model: modelState.model,
101 };
102
103 // Organization selection is already handled in initializeServices
104 const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH);
105 if (authState.organizationId) {
106 telemetryService.updateOrganization(authState.organizationId);
107 }
108
109 // Log configuration information
110 const organizationId = authState.organizationId || "personal";
111 const assistantName = config.name;
112 const assistantSlug = getAssistantSlug(authState.authConfig);
113 const modelProvider = model.provider;
114 const modelName = model.model;
115
116 console.log(chalk.blue(`\nConfiguration:`));
117 console.log(chalk.dim(` Organization: ${organizationId}`));
118 console.log(
119 chalk.dim(
120 ` Assistant: ${assistantName}${
121 assistantSlug ? ` (${assistantSlug})` : ""
122 }`,
123 ),
124 );
125 console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
126 if (options.config) {
127 console.log(chalk.dim(` Config file: ${options.config}`));
128 }
129
130 // Initialize chat history
131 const chatHistory: ChatCompletionMessageParam[] = [];
132 const systemMessage = await constructSystemMessage(
133 options.rule,
134 undefined,
135 true,
136 );
137 if (systemMessage) {
138 chatHistory.push({ role: "system", content: systemMessage });
139 }
140
141 // Initialize server state
142 const state: ServerState = {
143 chatHistory,
144 displayMessages: [], // Initialize empty display messages
145 config,
146 model,
147 isProcessing: false,
148 lastActivity: Date.now(),
149 messageQueue: [],
150 currentAbortController: null,
151 shouldInterrupt: false,
152 serverRunning: true,
153 pendingPermission: null,
154 };
155
156 // Record session start
157 telemetryService.recordSessionStart();
158 telemetryService.startActiveTime();
159
160 const app = express();
161 app.use(express.json());
162
163 // GET /state - Return the current state
164 app.get("/state", (_req: Request, res: Response) => {
165 state.lastActivity = Date.now();
166 res.json({
167 chatHistory: state.displayMessages, // Send display messages with proper formatting
168 isProcessing: state.isProcessing,
169 messageQueueLength: state.messageQueue.length,
170 pendingPermission: state.pendingPermission,
171 });
172 });
173
174 // POST /message - Queue a message and potentially interrupt
175 app.post("/message", async (req: Request, res: Response) => {
176 state.lastActivity = Date.now();
177
178 const { message } = req.body;
179 if (!message) {
180 return res.status(400).json({ error: "Message field is required" });
181 }
182
183 // Queue the message
184 state.messageQueue.push(message);
185
186 // If currently processing, set interrupt flag
187 if (state.isProcessing && state.currentAbortController) {
188 state.shouldInterrupt = true;
189 }
190
191 res.json({
192 queued: true,
193 position: state.messageQueue.length,
194 willInterrupt: state.shouldInterrupt,
195 });
196
197 // Process messages if not already processing
198 if (!state.isProcessing) {
199 processMessages(state, llmApi);
200 }
201 });
202
203 // POST /permission - Approve or reject pending tool permission
204 app.post("/permission", async (req: Request, res: Response) => {
205 state.lastActivity = Date.now();
206
207 const { requestId, approved } = req.body;
208
209 if (!state.pendingPermission) {
210 return res.status(400).json({ error: "No pending permission request" });
211 }
212
213 if (state.pendingPermission.requestId !== requestId) {
214 return res.status(400).json({ error: "Invalid request ID" });
215 }
216
217 // Remove the permission request message
218 const lastMsg = state.displayMessages[state.displayMessages.length - 1];
219 if (lastMsg && lastMsg.messageType === "tool-permission-request") {
220 state.displayMessages.pop();
221 }
222
223 // Send the permission response to the toolPermissionManager
224 if (approved) {
225 toolPermissionManager.approveRequest(requestId);
226 } else {
227 toolPermissionManager.rejectRequest(requestId);
228 }
229
230 // Clear pending permission state
231 state.pendingPermission = null;
232
233 res.json({
234 success: true,
235 approved,
236 });
237 });
238
239 // GET /diff - Return git diff against main branch
240 app.get("/diff", async (_req: Request, res: Response) => {
241 state.lastActivity = Date.now();
242
243 try {
244 // First check if we're in a git repository
245 await execAsync("git rev-parse --git-dir");
246
247 // Get the diff against main branch
248 const { stdout } = await execAsync("git diff main");
249
250 res.json({
251 diff: stdout,
252 });
253 } catch (error: any) {
254 // Git diff returns exit code 1 when there are differences, which is normal
255 if (error.code === 1 && error.stdout) {
256 res.json({
257 diff: error.stdout,
258 });
259 } else if (error.code === 128) {
260 // Handle case where we're not in a git repo or main branch doesn't exist
261 res.status(404).json({
262 error: "Not in a git repository or main branch doesn't exist",
263 diff: "",
264 });
265 } else {
266 logger.error(`Git diff error: ${formatError(error)}`);
267 res.status(500).json({
268 error: `Failed to get git diff: ${formatError(error)}`,
269 diff: "",
270 });
271 }
272 }
273 });
274
275 // Track intervals for cleanup
276 let inactivityChecker: NodeJS.Timeout | null = null;
277
278 // POST /exit - Gracefully shut down the server
279 app.post("/exit", async (_req: Request, res: Response) => {
280 console.log(
281 chalk.yellow("\nReceived exit request, shutting down server..."),
282 );
283
284 // Respond immediately before shutting down
285 res.json({
286 message: "Server shutting down",
287 success: true,
288 });
289
290 // Set server running flag to false to stop processing
291 state.serverRunning = false;
292
293 // Abort any current processing
294 if (state.currentAbortController) {
295 state.currentAbortController.abort();
296 }
297
298 // Clear the message queue
299 state.messageQueue = [];
300
301 // Clean up intervals
302 if (inactivityChecker) {
303 clearInterval(inactivityChecker);
304 inactivityChecker = null;
305 }
306
307 // Give a moment for the response to be sent
308 setTimeout(() => {
309 server.close(() => {
310 telemetryService.stopActiveTime();
311 process.exit(0);
312 });
313 }, 100);
314 });
315
316 const server = app.listen(port, () => {
317 console.log(chalk.green(`Server started on http://localhost:${port}`));
318 console.log(chalk.dim("Endpoints:"));
319 console.log(chalk.dim(" GET /state - Get current agent state"));
320 console.log(
321 chalk.dim(
322 " POST /message - Send a message (body: { message: string })",
323 ),
324 );
325 console.log(
326 chalk.dim(
327 " POST /permission - Approve/reject tool (body: { requestId, approved })",
328 ),
329 );
330 console.log(
331 chalk.dim(" GET /diff - Get git diff against main branch"),
332 );
333 console.log(
334 chalk.dim(" POST /exit - Gracefully shut down the server"),
335 );
336 console.log(
337 chalk.dim(
338 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
339 ),
340 );
341
342 // If initial prompt provided, queue it for processing
343 if (actualPrompt) {
344 console.log(chalk.dim("\nProcessing initial prompt..."));
345 state.messageQueue.push(actualPrompt);
346 processMessages(state, llmApi);
347 }
348 });
349
350 // Process messages from the queue
351 async function processMessages(state: ServerState, llmApi: any) {
352 while (state.messageQueue.length > 0 && state.serverRunning) {
353 const userMessage = state.messageQueue.shift()!;
354 state.isProcessing = true;
355 state.shouldInterrupt = false;
356 state.lastActivity = Date.now();
357
358 // Add user message to history
359 state.chatHistory.push({ role: "user", content: userMessage });
360 state.displayMessages.push({ role: "user", content: userMessage });
361
362 try {
363 // Create new abort controller for this response
364 state.currentAbortController = new AbortController();
365
366 // Stream the response with interruption support
367 await streamChatResponseWithInterruption(
368 state,
369 llmApi,
370 state.currentAbortController,
371 () => state.shouldInterrupt,
372 );
373
374 // Save session after successful response
375 saveSession(state.chatHistory);
376
377 state.lastActivity = Date.now();
378 } catch (e: any) {
379 if (e.name === "AbortError") {
380 logger.debug("Response interrupted");
381 // Remove the partial assistant message if it exists
382 const lastMessage = state.chatHistory[state.chatHistory.length - 1];
383 if (lastMessage.role === "assistant" && !lastMessage.content) {
384 state.chatHistory.pop();
385 }
386 // Also remove partial display messages
387 const lastDisplayMessage =
388 state.displayMessages[state.displayMessages.length - 1];
389 if (
390 lastDisplayMessage &&
391 lastDisplayMessage.role === "assistant" &&
392 lastDisplayMessage.isStreaming
393 ) {
394 state.displayMessages.pop();
395 }
396 } else {
397 logger.error(`Error: ${formatError(e)}`);
398 // Add error message to chat history and display messages
399 const errorMessage = `Error: ${formatError(e)}`;
400 state.chatHistory.push({
401 role: "assistant",
402 content: errorMessage,
403 });
404 state.displayMessages.push({
405 role: "assistant",
406 content: errorMessage,
407 });
408 }
409 } finally {
410 state.currentAbortController = null;
411 state.isProcessing = false;
412 }
413 }
414 }
415
416 // Check for inactivity and shutdown
417 inactivityChecker = setInterval(() => {
418 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
419 console.log(
420 chalk.yellow(
421 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
422 ),
423 );
424 state.serverRunning = false;
425 server.close(() => {
426 telemetryService.stopActiveTime();
427 process.exit(0);
428 });
429 if (inactivityChecker) {
430 clearInterval(inactivityChecker);
431 inactivityChecker = null;
432 }
433 }
434 }, 1000);
435
436 // Handle graceful shutdown
437 process.on("SIGINT", () => {
438 console.log(chalk.yellow("\nShutting down server..."));
439 state.serverRunning = false;
440 if (inactivityChecker) {
441 clearInterval(inactivityChecker);
442 inactivityChecker = null;
443 }
444 server.close(() => {
445 telemetryService.stopActiveTime();
446 process.exit(0);
447 });
448 });
449}
450
451// Modified version of streamChatResponse that supports interruption
452async function streamChatResponseWithInterruption(
453 state: ServerState,
454 llmApi: any,
455 abortController: AbortController,
456 shouldInterrupt: () => boolean,
457): Promise<string> {
458 // Import the original streamChatResponse logic but add interruption checks
459 // Create a wrapper that checks for interruption
460 const originalSignal = abortController.signal;
461 const checkInterruption = () => {
462 if (shouldInterrupt() && !originalSignal.aborted) {
463 abortController.abort();
464 }
465 };
466
467 // Set up periodic interruption checks
468 const interruptionChecker = setInterval(checkInterruption, 100);
469
470 let currentStreamingMessage: DisplayMessage | null = null;
471
472 // Create callbacks to capture tool events
473 const callbacks: StreamCallbacks = {
474 onContent: (content: string) => {
475 if (!currentStreamingMessage) {
476 currentStreamingMessage = {
477 role: "assistant",
478 content: "",
479 isStreaming: true,
480 };
481 state.displayMessages.push(currentStreamingMessage);
482 }
483 currentStreamingMessage.content += content;
484 },
485 onContentComplete: (content: string) => {
486 if (currentStreamingMessage) {
487 currentStreamingMessage.content = content;
488 currentStreamingMessage.isStreaming = false;
489 currentStreamingMessage = null;
490 } else {
491 // Add complete assistant message
492 state.displayMessages.push({
493 role: "assistant",
494 content: content,
495 isStreaming: false,
496 });
497 }
498 },
499 onToolStart: (toolName: string, toolArgs?: any) => {
500 // Format tool call similar to local mode
501 const formatToolCall = (name: string, args: any) => {
502 const displayName = getToolDisplayName(name);
503 if (!args) return displayName;
504
505 const firstValue = Object.values(args)[0];
506 const formatPath = (value: any) => {
507 if (typeof value === "string" && path.isAbsolute(value)) {
508 const workspaceRoot = process.cwd();
509 const relativePath = path.relative(workspaceRoot, value);
510 return relativePath || value;
511 }
512 return value;
513 };
514
515 return `${displayName}(${formatPath(firstValue) || ""})`;
516 };
517
518 // If there was streaming content, finalize it first
519 if (currentStreamingMessage && currentStreamingMessage.content) {
520 currentStreamingMessage.isStreaming = false;
521 currentStreamingMessage = null;
522 }
523
524 state.displayMessages.push({
525 role: "system",
526 content: `○ ${formatToolCall(toolName, toolArgs)}`,
527 messageType: "tool-start",
528 toolName,
529 });
530 },
531 onToolResult: (result: string, toolName: string) => {
532 // Replace the tool-start message with tool-result
533 const displayName = getToolDisplayName(toolName);
534
535 // Find and replace the corresponding tool-start message
536 for (let i = state.displayMessages.length - 1; i >= 0; i--) {
537 if (
538 state.displayMessages[i].messageType === "tool-start" &&
539 state.displayMessages[i].toolName === toolName
540 ) {
541 state.displayMessages[i] = {
542 ...state.displayMessages[i],
543 content: `● ${displayName}`,
544 messageType: "tool-result",
545 toolResult: result,
546 };
547 return;
548 }
549 }
550
551 // If no tool-start found, add as new message (fallback)
552 state.displayMessages.push({
553 role: "system",
554 content: `● ${displayName}`,
555 messageType: "tool-result",
556 toolName,
557 toolResult: result,
558 });
559 },
560 onToolError: (error: string, toolName?: string) => {
561 state.displayMessages.push({
562 role: "system",
563 content: `✗ Tool error: ${error}`,
564 messageType: "tool-error",
565 toolName,
566 });
567 },
568 onToolPermissionRequest: (
569 toolName: string,
570 toolArgs: any,
571 requestId: string,
572 ) => {
573 // Set pending permission state
574 state.pendingPermission = {
575 toolName,
576 toolArgs,
577 requestId,
578 timestamp: Date.now(),
579 };
580
581 // Add a display message indicating permission is needed
582 state.displayMessages.push({
583 role: "system",
584 content: `⚠️ Tool ${toolName} requires permission`,
585 messageType: "tool-permission-request" as any,
586 toolName,
587 });
588
589 // Don't wait here - the streamChatResponse will handle waiting
590 },
591 };
592
593 try {
594 const response = await streamChatResponse(
595 state.chatHistory,
596 state.model,
597 llmApi,
598 abortController,
599 callbacks,
600 );
601 return response || "";
602 } finally {
603 clearInterval(interruptionChecker);
604 // Ensure any streaming message is finalized
605 if (currentStreamingMessage !== null) {
606 // TypeScript is having issues with this line - the message will be finalized anyway
607 // currentStreamingMessage.isStreaming = false;
608 }
609 }
610}