Elffuss BraidHub

kikocis/continue public

dd35e28818ae · 13.7 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 { formatError } from "../util/formatError.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
35const execAsync = promisify(exec);
36
37interface ServeOptions extends ExtendedCommandOptions {
38 timeout?: string;
39 port?: 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
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 // Record session start
149 telemetryService.recordSessionStart();
150 telemetryService.startActiveTime();
151
152 const app = express();
153 app.use(express.json());
154
155 // GET /state - Return the current state
156 app.get("/state", (_req: Request, res: Response) => {
157 state.lastActivity = Date.now();
158 // Ensure session history reflects ChatHistoryService state
159 try {
160 state.session.history = services.chatHistory.getHistory();
161 } catch (e) {
162 logger.debug(
163 `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
164 );
165 }
166 res.json({
167 session: state.session, // Return session directly instead of converting
168 isProcessing: state.isProcessing,
169 messageQueueLength: state.messageQueue.length,
170 pendingPermission: state.pendingPermission,
171 });
172 });
173
174 // POST /message - Queue a message and potentially interrupt
175 app.post("/message", async (req: Request, res: Response) => {
176 state.lastActivity = Date.now();
177
178 const { message } = req.body;
179 if (!message) {
180 return res.status(400).json({ error: "Message field is required" });
181 }
182
183 // Queue the message
184 state.messageQueue.push(message);
185
186 // If currently processing, set interrupt flag
187 if (state.isProcessing && state.currentAbortController) {
188 state.shouldInterrupt = true;
189 }
190
191 res.json({
192 queued: true,
193 position: state.messageQueue.length,
194 willInterrupt: state.shouldInterrupt,
195 });
196
197 // Process messages if not already processing
198 if (!state.isProcessing) {
199 processMessages(state, llmApi);
200 }
201 });
202
203 // POST /permission - Approve or reject pending tool permission
204 app.post("/permission", async (req: Request, res: Response) => {
205 state.lastActivity = Date.now();
206
207 const { requestId, approved } = req.body;
208
209 if (!state.pendingPermission) {
210 return res.status(400).json({ error: "No pending permission request" });
211 }
212
213 if (state.pendingPermission.requestId !== requestId) {
214 return res.status(400).json({ error: "Invalid request ID" });
215 }
216
217 // Remove the permission request message if it exists
218 // Permission requests are handled separately in unified format
219
220 // Send the permission response to the toolPermissionManager
221 if (approved) {
222 toolPermissionManager.approveRequest(requestId);
223 } else {
224 toolPermissionManager.rejectRequest(requestId);
225 }
226
227 // Clear pending permission state
228 state.pendingPermission = null;
229
230 res.json({
231 success: true,
232 approved,
233 });
234 });
235
236 // GET /diff - Return git diff against main branch
237 app.get("/diff", async (_req: Request, res: Response) => {
238 state.lastActivity = Date.now();
239
240 try {
241 // First check if we're in a git repository
242 await execAsync("git rev-parse --git-dir");
243
244 // Get the diff against main branch
245 const { stdout } = await execAsync("git diff main");
246
247 res.json({
248 diff: stdout,
249 });
250 } catch (error: any) {
251 // Git diff returns exit code 1 when there are differences, which is normal
252 if (error.code === 1 && error.stdout) {
253 res.json({
254 diff: error.stdout,
255 });
256 } else if (error.code === 128) {
257 // Handle case where we're not in a git repo or main branch doesn't exist
258 res.status(404).json({
259 error: "Not in a git repository or main branch doesn't exist",
260 diff: "",
261 });
262 } else {
263 logger.error(`Git diff error: ${formatError(error)}`);
264 res.status(500).json({
265 error: `Failed to get git diff: ${formatError(error)}`,
266 diff: "",
267 });
268 }
269 }
270 });
271
272 // Track intervals for cleanup
273 let inactivityChecker: NodeJS.Timeout | null = null;
274
275 // POST /exit - Gracefully shut down the server
276 app.post("/exit", async (_req: Request, res: Response) => {
277 console.log(
278 chalk.yellow("\nReceived exit request, shutting down server..."),
279 );
280
281 // Respond immediately before shutting down
282 res.json({
283 message: "Server shutting down",
284 success: true,
285 });
286
287 // Set server running flag to false to stop processing
288 state.serverRunning = false;
289
290 // Abort any current processing
291 if (state.currentAbortController) {
292 state.currentAbortController.abort();
293 }
294
295 // Clear the message queue
296 state.messageQueue = [];
297
298 // Clean up intervals
299 if (inactivityChecker) {
300 clearInterval(inactivityChecker);
301 inactivityChecker = null;
302 }
303
304 // Give a moment for the response to be sent
305 setTimeout(() => {
306 server.close(() => {
307 telemetryService.stopActiveTime();
308 process.exit(0);
309 });
310 }, 100);
311 });
312
313 const server = app.listen(port, () => {
314 console.log(chalk.green(`Server started on http://localhost:${port}`));
315 console.log(chalk.dim("Endpoints:"));
316 console.log(chalk.dim(" GET /state - Get current agent state"));
317 console.log(
318 chalk.dim(
319 " POST /message - Send a message (body: { message: string })",
320 ),
321 );
322 console.log(
323 chalk.dim(
324 " POST /permission - Approve/reject tool (body: { requestId, approved })",
325 ),
326 );
327 console.log(
328 chalk.dim(" GET /diff - Get git diff against main branch"),
329 );
330 console.log(
331 chalk.dim(" POST /exit - Gracefully shut down the server"),
332 );
333 console.log(
334 chalk.dim(
335 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
336 ),
337 );
338
339 // If initial prompt provided, queue it for processing
340 if (actualPrompt) {
341 console.log(chalk.dim("\nProcessing initial prompt..."));
342 state.messageQueue.push(actualPrompt);
343 processMessages(state, llmApi);
344 }
345 });
346
347 // Process messages from the queue
348 function removePartialAssistantMessage(state: ServerState) {
349 try {
350 const svcHistory = services.chatHistory.getHistory();
351 const last = svcHistory[svcHistory.length - 1];
352 if (last && last.message.role === "assistant" && !last.message.content) {
353 const trimmed = svcHistory.slice(0, -1);
354 services.chatHistory.setHistory(trimmed);
355 }
356 } catch {
357 const lastMessage =
358 state.session.history[state.session.history.length - 1];
359 if (
360 lastMessage &&
361 lastMessage.message.role === "assistant" &&
362 !lastMessage.message.content
363 ) {
364 state.session.history.pop();
365 }
366 }
367 }
368
369 async function processMessages(state: ServerState, llmApi: any) {
370 while (state.messageQueue.length > 0 && state.serverRunning) {
371 const userMessage = state.messageQueue.shift()!;
372 state.isProcessing = true;
373 state.shouldInterrupt = false;
374 state.lastActivity = Date.now();
375
376 // Add user message via ChatHistoryService (single source of truth)
377 try {
378 services.chatHistory.addUserMessage(userMessage);
379 } catch {
380 // Fallback to local array if service unavailable
381 state.session.history.push({
382 message: { role: "user", content: userMessage },
383 contextItems: [],
384 });
385 }
386
387 try {
388 // Create new abort controller for this response
389 state.currentAbortController = new AbortController();
390
391 // Stream the response with interruption support
392 await streamChatResponseWithInterruption(
393 state,
394 llmApi,
395 state.currentAbortController,
396 () => state.shouldInterrupt,
397 );
398
399 // No direct persistence here; ChatHistoryService handles persistence when appropriate
400
401 state.lastActivity = Date.now();
402 } catch (e: any) {
403 if (e.name === "AbortError") {
404 logger.debug("Response interrupted");
405 // Remove any partial assistant message
406 removePartialAssistantMessage(state);
407 } else {
408 logger.error(`Error: ${formatError(e)}`);
409 // Add error message via ChatHistoryService
410 const errorMessage = `Error: ${formatError(e)}`;
411 try {
412 services.chatHistory.addAssistantMessage(errorMessage);
413 } catch {
414 state.session.history.push({
415 message: { role: "assistant", content: errorMessage },
416 contextItems: [],
417 });
418 }
419 }
420 } finally {
421 state.currentAbortController = null;
422 state.isProcessing = false;
423 }
424 }
425 }
426
427 // Check for inactivity and shutdown
428 inactivityChecker = setInterval(() => {
429 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
430 console.log(
431 chalk.yellow(
432 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
433 ),
434 );
435 state.serverRunning = false;
436 server.close(() => {
437 telemetryService.stopActiveTime();
438 process.exit(0);
439 });
440 if (inactivityChecker) {
441 clearInterval(inactivityChecker);
442 inactivityChecker = null;
443 }
444 }
445 }, 1000);
446
447 // Handle graceful shutdown
448 process.on("SIGINT", () => {
449 console.log(chalk.yellow("\nShutting down server..."));
450 state.serverRunning = false;
451 if (inactivityChecker) {
452 clearInterval(inactivityChecker);
453 inactivityChecker = null;
454 }
455 server.close(() => {
456 telemetryService.stopActiveTime();
457 process.exit(0);
458 });
459 });
460}
461
462// Function moved to serve.helpers.ts - remove implementation
463// async function streamChatResponseWithInterruption - moved to helpers {
464// Implementation moved to serve.helpers.ts