Elffuss BraidHub

kikocis/continue public

3a1e5cc69df2 · 14.5 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, getCompleteStateSnapshot } from "../session.js";
20import { messageQueue } from "../stream/messageQueue.js";
21import { constructSystemMessage } from "../systemMessage.js";
22import { telemetryService } from "../telemetry/telemetryService.js";
23import { gracefulExit } from "../util/exit.js";
24import { formatError } from "../util/formatError.js";
25import { getGitDiffSnapshot } from "../util/git.js";
26import { logger } from "../util/logger.js";
27import { readStdinSync } from "../util/stdin.js";
28
29import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
30import {
31 streamChatResponseWithInterruption,
32 type ServerState,
33} from "./serve.helpers.js";
34
35interface ServeOptions extends ExtendedCommandOptions {
36 timeout?: string;
37 port?: string;
38 /** Storage identifier for remote sync */
39 id?: string;
40}
41
42// eslint-disable-next-line max-statements
43export async function serve(prompt?: string, options: ServeOptions = {}) {
44 // Check if prompt should come from stdin instead of parameter
45 let actualPrompt = prompt;
46 if (!prompt) {
47 // Try to read from stdin (for piped input like: cat file | cn serve)
48 const stdinInput = readStdinSync();
49 if (stdinInput) {
50 actualPrompt = stdinInput;
51 }
52 }
53
54 const timeoutSeconds = parseInt(options.timeout || "300", 10);
55 const timeoutMs = timeoutSeconds * 1000;
56 const port = parseInt(options.port || "8000", 10);
57
58 // Initialize services with tool permission overrides
59 const { permissionOverrides } = processCommandFlags(options);
60
61 await initializeServices({
62 options,
63 toolPermissionOverrides: permissionOverrides,
64 headless: true, // Skip onboarding in serve mode
65 });
66
67 // Get initialized services from the service container
68 const [configState, modelState] = await Promise.all([
69 getService<ConfigServiceState>(SERVICE_NAMES.CONFIG),
70 getService<ModelServiceState>(SERVICE_NAMES.MODEL),
71 ]);
72
73 if (!configState.config || !modelState.llmApi || !modelState.model) {
74 throw new Error("Failed to initialize required services");
75 }
76
77 const { config, llmApi, model } = {
78 config: configState.config,
79 llmApi: modelState.llmApi,
80 model: modelState.model,
81 };
82
83 // Organization selection is already handled in initializeServices
84 const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH);
85 if (authState.organizationId) {
86 telemetryService.updateOrganization(authState.organizationId);
87 }
88 const accessToken = getAccessToken(authState.authConfig);
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 currentAbortController: null,
143 serverRunning: true,
144 pendingPermission: null,
145 };
146
147 const syncSessionHistory = () => {
148 try {
149 state.session.history = services.chatHistory.getHistory();
150 } catch (e) {
151 logger.debug(
152 `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
153 );
154 }
155 };
156
157 const storageSyncService = services.storageSync;
158 let storageSyncActive = await storageSyncService.startFromOptions({
159 storageOption: options.id,
160 accessToken,
161 syncSessionHistory,
162 getCompleteStateSnapshot: () =>
163 getCompleteStateSnapshot(
164 state.session,
165 state.isProcessing,
166 messageQueue.getQueueLength(),
167 state.pendingPermission,
168 ),
169 isActive: () => state.serverRunning,
170 });
171
172 const stopStorageSync = () => {
173 if (storageSyncActive) {
174 storageSyncService.stop();
175 storageSyncActive = false;
176 }
177 };
178
179 // Record session start
180 telemetryService.recordSessionStart();
181 telemetryService.startActiveTime();
182
183 const app = express();
184 app.use(express.json());
185
186 // GET /state - Return the current state
187 app.get("/state", (_req: Request, res: Response) => {
188 state.lastActivity = Date.now();
189 syncSessionHistory();
190 const stateSnapshot = getCompleteStateSnapshot(
191 state.session,
192 state.isProcessing,
193 messageQueue.getQueueLength(),
194 state.pendingPermission,
195 );
196 res.json(stateSnapshot);
197 });
198
199 // POST /message - Queue a message and potentially interrupt
200 app.post("/message", async (req: Request, res: Response) => {
201 state.lastActivity = Date.now();
202
203 const { message } = req.body;
204 if (!message) {
205 return res.status(400).json({ error: "Message field is required" });
206 }
207
208 // Queue the message
209 await messageQueue.enqueueMessage(message);
210
211 res.json({
212 queued: true,
213 position: messageQueue.getQueueLength(),
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 // Clean up intervals
307 if (inactivityChecker) {
308 clearInterval(inactivityChecker);
309 inactivityChecker = null;
310 }
311
312 // Give a moment for the response to be sent
313 const handleExitResponse = () => {
314 server.close(() => {
315 telemetryService.stopActiveTime();
316 gracefulExit(0).catch((err) => {
317 logger.error(`Graceful exit failed: ${formatError(err)}`);
318 process.exit(1);
319 });
320 });
321 };
322 setTimeout(handleExitResponse, 100);
323 });
324
325 const server = app.listen(port, async () => {
326 console.log(chalk.green(`Server started on http://localhost:${port}`));
327 console.log(chalk.dim("Endpoints:"));
328 console.log(chalk.dim(" GET /state - Get current agent state"));
329 console.log(
330 chalk.dim(
331 " POST /message - Send a message (body: { message: string })",
332 ),
333 );
334 console.log(
335 chalk.dim(
336 " POST /permission - Approve/reject tool (body: { requestId, approved })",
337 ),
338 );
339 console.log(
340 chalk.dim(" GET /diff - Get git diff against main branch"),
341 );
342 console.log(
343 chalk.dim(" POST /exit - Gracefully shut down the server"),
344 );
345 console.log(
346 chalk.dim(
347 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
348 ),
349 );
350
351 // If initial prompt provided, queue it for processing
352 if (actualPrompt) {
353 console.log(chalk.dim("\nProcessing initial prompt..."));
354 await messageQueue.enqueueMessage(actualPrompt);
355 processMessages(state, llmApi);
356 }
357 });
358
359 // Process messages from the queue
360 function removePartialAssistantMessage(state: ServerState) {
361 try {
362 const svcHistory = services.chatHistory.getHistory();
363 const last = svcHistory[svcHistory.length - 1];
364 if (last && last.message.role === "assistant" && !last.message.content) {
365 const trimmed = svcHistory.slice(0, -1);
366 services.chatHistory.setHistory(trimmed);
367 }
368 } catch {
369 const lastMessage =
370 state.session.history[state.session.history.length - 1];
371 if (
372 lastMessage &&
373 lastMessage.message.role === "assistant" &&
374 !lastMessage.message.content
375 ) {
376 state.session.history.pop();
377 }
378 }
379 }
380
381 async function processMessages(state: ServerState, llmApi: any) {
382 let processedMessage = false;
383 while (state.serverRunning) {
384 const queuedMessage = messageQueue.getNextMessage();
385 if (!queuedMessage) {
386 break;
387 }
388
389 const userMessage = queuedMessage.message;
390 state.isProcessing = true;
391 state.lastActivity = Date.now();
392 processedMessage = true;
393
394 // Add user message via ChatHistoryService (single source of truth)
395 try {
396 services.chatHistory.addUserMessage(userMessage);
397 } catch {
398 // Fallback to local array if service unavailable
399 state.session.history.push({
400 message: { role: "user", content: userMessage },
401 contextItems: [],
402 });
403 }
404
405 try {
406 // Create new abort controller for this response
407 state.currentAbortController = new AbortController();
408
409 // Stream the response with interruption support
410 await streamChatResponseWithInterruption(
411 state,
412 llmApi,
413 state.currentAbortController,
414 () => false,
415 );
416
417 // No direct persistence here; ChatHistoryService handles persistence when appropriate
418
419 state.lastActivity = Date.now();
420 } catch (e: any) {
421 if (e.name === "AbortError") {
422 logger.debug("Response interrupted");
423 // Remove any partial assistant message
424 removePartialAssistantMessage(state);
425 } else {
426 logger.error(`Error: ${formatError(e)}`);
427 // Add error message via ChatHistoryService
428 const errorMessage = `Error: ${formatError(e)}`;
429 try {
430 services.chatHistory.addAssistantMessage(errorMessage);
431 } catch {
432 state.session.history.push({
433 message: { role: "assistant", content: errorMessage },
434 contextItems: [],
435 });
436 }
437 }
438 } finally {
439 state.currentAbortController = null;
440 state.isProcessing = false;
441 }
442 }
443
444 if (
445 processedMessage &&
446 state.serverRunning &&
447 messageQueue.getQueueLength() === 0
448 ) {
449 await storageSyncService.markAgentStatusUnread();
450 }
451 }
452
453 // Check for inactivity and shutdown
454 inactivityChecker = setInterval(() => {
455 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
456 console.log(
457 chalk.yellow(
458 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
459 ),
460 );
461 state.serverRunning = false;
462 stopStorageSync();
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 if (inactivityChecker) {
471 clearInterval(inactivityChecker);
472 inactivityChecker = null;
473 }
474 }
475 }, 1000);
476
477 // Handle graceful shutdown
478 process.on("SIGINT", () => {
479 console.log(chalk.yellow("\nShutting down server..."));
480 state.serverRunning = false;
481 stopStorageSync();
482 if (inactivityChecker) {
483 clearInterval(inactivityChecker);
484 inactivityChecker = null;
485 }
486 server.close(() => {
487 telemetryService.stopActiveTime();
488 gracefulExit(0).catch((err) => {
489 logger.error(`Graceful exit failed: ${formatError(err)}`);
490 process.exit(1);
491 });
492 });
493 });
494}
495
496// Function moved to serve.helpers.ts - remove implementation
497// async function streamChatResponseWithInterruption - moved to helpers {
498// Implementation moved to serve.helpers.ts