Elffuss BraidHub

kikocis/continue public

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