Elffuss BraidHub

kikocis/continue public

c5e6566b8882 · 13.9 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(async () => {
307 telemetryService.stopActiveTime();
308 const { gracefulExit } = await import("../util/exit.js");
309 await gracefulExit(0);
310 });
311 }, 100);
312 });
313
314 const server = app.listen(port, () => {
315 console.log(chalk.green(`Server started on http://localhost:${port}`));
316 console.log(chalk.dim("Endpoints:"));
317 console.log(chalk.dim(" GET /state - Get current agent state"));
318 console.log(
319 chalk.dim(
320 " POST /message - Send a message (body: { message: string })",
321 ),
322 );
323 console.log(
324 chalk.dim(
325 " POST /permission - Approve/reject tool (body: { requestId, approved })",
326 ),
327 );
328 console.log(
329 chalk.dim(" GET /diff - Get git diff against main branch"),
330 );
331 console.log(
332 chalk.dim(" POST /exit - Gracefully shut down the server"),
333 );
334 console.log(
335 chalk.dim(
336 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
337 ),
338 );
339
340 // If initial prompt provided, queue it for processing
341 if (actualPrompt) {
342 console.log(chalk.dim("\nProcessing initial prompt..."));
343 state.messageQueue.push(actualPrompt);
344 processMessages(state, llmApi);
345 }
346 });
347
348 // Process messages from the queue
349 function removePartialAssistantMessage(state: ServerState) {
350 try {
351 const svcHistory = services.chatHistory.getHistory();
352 const last = svcHistory[svcHistory.length - 1];
353 if (last && last.message.role === "assistant" && !last.message.content) {
354 const trimmed = svcHistory.slice(0, -1);
355 services.chatHistory.setHistory(trimmed);
356 }
357 } catch {
358 const lastMessage =
359 state.session.history[state.session.history.length - 1];
360 if (
361 lastMessage &&
362 lastMessage.message.role === "assistant" &&
363 !lastMessage.message.content
364 ) {
365 state.session.history.pop();
366 }
367 }
368 }
369
370 async function processMessages(state: ServerState, llmApi: any) {
371 while (state.messageQueue.length > 0 && state.serverRunning) {
372 const userMessage = state.messageQueue.shift()!;
373 state.isProcessing = true;
374 state.shouldInterrupt = false;
375 state.lastActivity = Date.now();
376
377 // Add user message via ChatHistoryService (single source of truth)
378 try {
379 services.chatHistory.addUserMessage(userMessage);
380 } catch {
381 // Fallback to local array if service unavailable
382 state.session.history.push({
383 message: { role: "user", content: userMessage },
384 contextItems: [],
385 });
386 }
387
388 try {
389 // Create new abort controller for this response
390 state.currentAbortController = new AbortController();
391
392 // Stream the response with interruption support
393 await streamChatResponseWithInterruption(
394 state,
395 llmApi,
396 state.currentAbortController,
397 () => state.shouldInterrupt,
398 );
399
400 // No direct persistence here; ChatHistoryService handles persistence when appropriate
401
402 state.lastActivity = Date.now();
403 } catch (e: any) {
404 if (e.name === "AbortError") {
405 logger.debug("Response interrupted");
406 // Remove any partial assistant message
407 removePartialAssistantMessage(state);
408 } else {
409 logger.error(`Error: ${formatError(e)}`);
410 // Add error message via ChatHistoryService
411 const errorMessage = `Error: ${formatError(e)}`;
412 try {
413 services.chatHistory.addAssistantMessage(errorMessage);
414 } catch {
415 state.session.history.push({
416 message: { role: "assistant", content: errorMessage },
417 contextItems: [],
418 });
419 }
420 }
421 } finally {
422 state.currentAbortController = null;
423 state.isProcessing = false;
424 }
425 }
426 }
427
428 // Check for inactivity and shutdown
429 inactivityChecker = setInterval(() => {
430 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
431 console.log(
432 chalk.yellow(
433 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
434 ),
435 );
436 state.serverRunning = false;
437 server.close(async () => {
438 telemetryService.stopActiveTime();
439 const { gracefulExit } = await import("../util/exit.js");
440 await gracefulExit(0);
441 });
442 if (inactivityChecker) {
443 clearInterval(inactivityChecker);
444 inactivityChecker = null;
445 }
446 }
447 }, 1000);
448
449 // Handle graceful shutdown
450 process.on("SIGINT", () => {
451 console.log(chalk.yellow("\nShutting down server..."));
452 state.serverRunning = false;
453 if (inactivityChecker) {
454 clearInterval(inactivityChecker);
455 inactivityChecker = null;
456 }
457 server.close(async () => {
458 telemetryService.stopActiveTime();
459 const { gracefulExit } = await import("../util/exit.js");
460 await gracefulExit(0);
461 });
462 });
463}
464
465// Function moved to serve.helpers.ts - remove implementation
466// async function streamChatResponseWithInterruption - moved to helpers {
467// Implementation moved to serve.helpers.ts