Elffuss BraidHub

kikocis/continue public

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