Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 14.2 KiBRawPermalink
1import { exec } from "child_process";
2import { promisify } from "util";
3
4import chalk from "chalk";
5import type { ChatHistoryItem } from "core/index.js";
6import express, { Request, Response } from "express";
7
8import { getAssistantSlug } from "../auth/workos.js";
9import { processCommandFlags } from "../flags/flagProcessor.js";
10import { toolPermissionManager } from "../permissions/permissionManager.js";
11import {
12 getService,
13 initializeServices,
14 SERVICE_NAMES,
15 services,
16} from "../services/index.js";
17import {
18 AuthServiceState,
19 ConfigServiceState,
20 ModelServiceState,
21} from "../services/types.js";
22import { createSession } from "../session.js";
23import { constructSystemMessage } from "../systemMessage.js";
24import { telemetryService } from "../telemetry/telemetryService.js";
25import { gracefulExit } from "../util/exit.js";
26import { formatError } from "../util/formatError.js";
27import { logger } from "../util/logger.js";
28import { readStdinSync } from "../util/stdin.js";
29
30import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
31import {
32 streamChatResponseWithInterruption,
33 type ServerState,
34} from "./serve.helpers.js";
35
36const execAsync = promisify(exec);
37
38interface ServeOptions extends ExtendedCommandOptions {
39 timeout?: string;
40 port?: string;
41}
42
43// eslint-disable-next-line max-statements
44export async function serve(prompt?: string, options: ServeOptions = {}) {
45 // Check if prompt should come from stdin instead of parameter
46 let actualPrompt = prompt;
47 if (!prompt) {
48 // Try to read from stdin (for piped input like: cat file | cn serve)
49 const stdinInput = readStdinSync();
50 if (stdinInput) {
51 actualPrompt = stdinInput;
52 }
53 }
54
55 const timeoutSeconds = parseInt(options.timeout || "300", 10);
56 const timeoutMs = timeoutSeconds * 1000;
57 const port = parseInt(options.port || "8000", 10);
58
59 // Initialize services with tool permission overrides
60 const { permissionOverrides } = processCommandFlags(options);
61
62 await initializeServices({
63 options,
64 toolPermissionOverrides: permissionOverrides,
65 headless: true, // Skip onboarding in serve mode
66 });
67
68 // Get initialized services from the service container
69 const [configState, modelState] = await Promise.all([
70 getService<ConfigServiceState>(SERVICE_NAMES.CONFIG),
71 getService<ModelServiceState>(SERVICE_NAMES.MODEL),
72 ]);
73
74 if (!configState.config || !modelState.llmApi || !modelState.model) {
75 throw new Error("Failed to initialize required services");
76 }
77
78 const { config, llmApi, model } = {
79 config: configState.config,
80 llmApi: modelState.llmApi,
81 model: modelState.model,
82 };
83
84 // Organization selection is already handled in initializeServices
85 const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH);
86 if (authState.organizationId) {
87 telemetryService.updateOrganization(authState.organizationId);
88 }
89
90 // Log configuration information
91 const organizationId = authState.organizationId || "personal";
92 const assistantName = config.name;
93 const assistantSlug = getAssistantSlug(authState.authConfig);
94 const modelProvider = model.provider;
95 const modelName = model.model;
96
97 console.log(chalk.blue(`\nConfiguration:`));
98 console.log(chalk.dim(` Organization: ${organizationId}`));
99 console.log(
100 chalk.dim(
101 ` Assistant: ${assistantName}${
102 assistantSlug ? ` (${assistantSlug})` : ""
103 }`,
104 ),
105 );
106 console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
107 if (options.config) {
108 console.log(chalk.dim(` Config file: ${options.config}`));
109 }
110
111 // Initialize session with system message
112 const systemMessage = await constructSystemMessage(
113 options.rule,
114 undefined,
115 true,
116 );
117
118 const initialHistory: ChatHistoryItem[] = [];
119 if (systemMessage) {
120 initialHistory.push({
121 message: { role: "system" as const, content: systemMessage },
122 contextItems: [],
123 });
124 }
125
126 const session = createSession(initialHistory);
127
128 // Align ChatHistoryService with server session and enable remote mode
129 try {
130 await services.chatHistory.initialize(session, false);
131 } catch {
132 // Fallback: continue even if service init fails; stream will still work with arrays
133 }
134
135 // Initialize server state
136 const state: ServerState = {
137 session,
138 config,
139 model,
140 isProcessing: false,
141 lastActivity: Date.now(),
142 messageQueue: [],
143 currentAbortController: null,
144 shouldInterrupt: false,
145 serverRunning: true,
146 pendingPermission: null,
147 };
148
149 // Record session start
150 telemetryService.recordSessionStart();
151 telemetryService.startActiveTime();
152
153 const app = express();
154 app.use(express.json());
155
156 // GET /state - Return the current state
157 app.get("/state", (_req: Request, res: Response) => {
158 state.lastActivity = Date.now();
159 // Ensure session history reflects ChatHistoryService state
160 try {
161 state.session.history = services.chatHistory.getHistory();
162 } catch (e) {
163 logger.debug(
164 `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
165 );
166 }
167 res.json({
168 session: state.session, // Return session directly instead of converting
169 isProcessing: state.isProcessing,
170 messageQueueLength: state.messageQueue.length,
171 pendingPermission: state.pendingPermission,
172 });
173 });
174
175 // POST /message - Queue a message and potentially interrupt
176 app.post("/message", async (req: Request, res: Response) => {
177 state.lastActivity = Date.now();
178
179 const { message } = req.body;
180 if (!message) {
181 return res.status(400).json({ error: "Message field is required" });
182 }
183
184 // Queue the message
185 state.messageQueue.push(message);
186
187 // If currently processing, set interrupt flag
188 if (state.isProcessing && state.currentAbortController) {
189 state.shouldInterrupt = true;
190 }
191
192 res.json({
193 queued: true,
194 position: state.messageQueue.length,
195 willInterrupt: state.shouldInterrupt,
196 });
197
198 // Process messages if not already processing
199 if (!state.isProcessing) {
200 processMessages(state, llmApi);
201 }
202 });
203
204 // POST /permission - Approve or reject pending tool permission
205 app.post("/permission", async (req: Request, res: Response) => {
206 state.lastActivity = Date.now();
207
208 const { requestId, approved } = req.body;
209
210 if (!state.pendingPermission) {
211 return res.status(400).json({ error: "No pending permission request" });
212 }
213
214 if (state.pendingPermission.requestId !== requestId) {
215 return res.status(400).json({ error: "Invalid request ID" });
216 }
217
218 // Remove the permission request message if it exists
219 // Permission requests are handled separately in unified format
220
221 // Send the permission response to the toolPermissionManager
222 if (approved) {
223 toolPermissionManager.approveRequest(requestId);
224 } else {
225 toolPermissionManager.rejectRequest(requestId);
226 }
227
228 // Clear pending permission state
229 state.pendingPermission = null;
230
231 res.json({
232 success: true,
233 approved,
234 });
235 });
236
237 // GET /diff - Return git diff against main branch
238 app.get("/diff", async (_req: Request, res: Response) => {
239 state.lastActivity = Date.now();
240
241 try {
242 // First check if we're in a git repository
243 await execAsync("git rev-parse --git-dir");
244
245 // Get the diff against main branch
246 const { stdout } = await execAsync("git diff main");
247
248 res.json({
249 diff: stdout,
250 });
251 } catch (error: any) {
252 // Git diff returns exit code 1 when there are differences, which is normal
253 if (error.code === 1 && error.stdout) {
254 res.json({
255 diff: error.stdout,
256 });
257 } else if (error.code === 128) {
258 // Handle case where we're not in a git repo or main branch doesn't exist
259 res.status(404).json({
260 error: "Not in a git repository or main branch doesn't exist",
261 diff: "",
262 });
263 } else {
264 logger.error(`Git diff error: ${formatError(error)}`);
265 res.status(500).json({
266 error: `Failed to get git diff: ${formatError(error)}`,
267 diff: "",
268 });
269 }
270 }
271 });
272
273 // Track intervals for cleanup
274 let inactivityChecker: NodeJS.Timeout | null = null;
275
276 // POST /exit - Gracefully shut down the server
277 app.post("/exit", async (_req: Request, res: Response) => {
278 console.log(
279 chalk.yellow("\nReceived exit request, shutting down server..."),
280 );
281
282 // Respond immediately before shutting down
283 res.json({
284 message: "Server shutting down",
285 success: true,
286 });
287
288 // Set server running flag to false to stop processing
289 state.serverRunning = false;
290
291 // Abort any current processing
292 if (state.currentAbortController) {
293 state.currentAbortController.abort();
294 }
295
296 // Clear the message queue
297 state.messageQueue = [];
298
299 // Clean up intervals
300 if (inactivityChecker) {
301 clearInterval(inactivityChecker);
302 inactivityChecker = null;
303 }
304
305 // Give a moment for the response to be sent
306 const handleExitResponse = () => {
307 server.close(() => {
308 telemetryService.stopActiveTime();
309 gracefulExit(0).catch((err) => {
310 logger.error(`Graceful exit failed: ${formatError(err)}`);
311 process.exit(1);
312 });
313 });
314 };
315 setTimeout(handleExitResponse, 100);
316 });
317
318 const server = app.listen(port, () => {
319 console.log(chalk.green(`Server started on http://localhost:${port}`));
320 console.log(chalk.dim("Endpoints:"));
321 console.log(chalk.dim(" GET /state - Get current agent state"));
322 console.log(
323 chalk.dim(
324 " POST /message - Send a message (body: { message: string })",
325 ),
326 );
327 console.log(
328 chalk.dim(
329 " POST /permission - Approve/reject tool (body: { requestId, approved })",
330 ),
331 );
332 console.log(
333 chalk.dim(" GET /diff - Get git diff against main branch"),
334 );
335 console.log(
336 chalk.dim(" POST /exit - Gracefully shut down the server"),
337 );
338 console.log(
339 chalk.dim(
340 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
341 ),
342 );
343
344 // If initial prompt provided, queue it for processing
345 if (actualPrompt) {
346 console.log(chalk.dim("\nProcessing initial prompt..."));
347 state.messageQueue.push(actualPrompt);
348 processMessages(state, llmApi);
349 }
350 });
351
352 // Process messages from the queue
353 function removePartialAssistantMessage(state: ServerState) {
354 try {
355 const svcHistory = services.chatHistory.getHistory();
356 const last = svcHistory[svcHistory.length - 1];
357 if (last && last.message.role === "assistant" && !last.message.content) {
358 const trimmed = svcHistory.slice(0, -1);
359 services.chatHistory.setHistory(trimmed);
360 }
361 } catch {
362 const lastMessage =
363 state.session.history[state.session.history.length - 1];
364 if (
365 lastMessage &&
366 lastMessage.message.role === "assistant" &&
367 !lastMessage.message.content
368 ) {
369 state.session.history.pop();
370 }
371 }
372 }
373
374 async function processMessages(state: ServerState, llmApi: any) {
375 while (state.messageQueue.length > 0 && state.serverRunning) {
376 const userMessage = state.messageQueue.shift()!;
377 state.isProcessing = true;
378 state.shouldInterrupt = false;
379 state.lastActivity = Date.now();
380
381 // Add user message via ChatHistoryService (single source of truth)
382 try {
383 services.chatHistory.addUserMessage(userMessage);
384 } catch {
385 // Fallback to local array if service unavailable
386 state.session.history.push({
387 message: { role: "user", content: userMessage },
388 contextItems: [],
389 });
390 }
391
392 try {
393 // Create new abort controller for this response
394 state.currentAbortController = new AbortController();
395
396 // Stream the response with interruption support
397 await streamChatResponseWithInterruption(
398 state,
399 llmApi,
400 state.currentAbortController,
401 () => state.shouldInterrupt,
402 );
403
404 // No direct persistence here; ChatHistoryService handles persistence when appropriate
405
406 state.lastActivity = Date.now();
407 } catch (e: any) {
408 if (e.name === "AbortError") {
409 logger.debug("Response interrupted");
410 // Remove any partial assistant message
411 removePartialAssistantMessage(state);
412 } else {
413 logger.error(`Error: ${formatError(e)}`);
414 // Add error message via ChatHistoryService
415 const errorMessage = `Error: ${formatError(e)}`;
416 try {
417 services.chatHistory.addAssistantMessage(errorMessage);
418 } catch {
419 state.session.history.push({
420 message: { role: "assistant", content: errorMessage },
421 contextItems: [],
422 });
423 }
424 }
425 } finally {
426 state.currentAbortController = null;
427 state.isProcessing = false;
428 }
429 }
430 }
431
432 // Check for inactivity and shutdown
433 inactivityChecker = setInterval(() => {
434 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
435 console.log(
436 chalk.yellow(
437 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
438 ),
439 );
440 state.serverRunning = false;
441 server.close(() => {
442 telemetryService.stopActiveTime();
443 gracefulExit(0).catch((err) => {
444 logger.error(`Graceful exit failed: ${formatError(err)}`);
445 process.exit(1);
446 });
447 });
448 if (inactivityChecker) {
449 clearInterval(inactivityChecker);
450 inactivityChecker = null;
451 }
452 }
453 }, 1000);
454
455 // Handle graceful shutdown
456 process.on("SIGINT", () => {
457 console.log(chalk.yellow("\nShutting down server..."));
458 state.serverRunning = false;
459 if (inactivityChecker) {
460 clearInterval(inactivityChecker);
461 inactivityChecker = null;
462 }
463 server.close(() => {
464 telemetryService.stopActiveTime();
465 gracefulExit(0).catch((err) => {
466 logger.error(`Graceful exit failed: ${formatError(err)}`);
467 process.exit(1);
468 });
469 });
470 });
471}
472
473// Function moved to serve.helpers.ts - remove implementation
474// async function streamChatResponseWithInterruption - moved to helpers {
475// Implementation moved to serve.helpers.ts