Elffuss BraidHub

kikocis/continue public

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