Elffuss BraidHub

kikocis/continue public

4e7d29ea58e1 · 12.6 KiBRawPermalink
1import { exec } from "child_process";
2import { promisify } from "util";
3
4import chalk from "chalk";
5import type { ChatHistoryItem } from "core/index.js";
6import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
7import express, { Request, Response } from "express";
8
9import { getAssistantSlug } from "../auth/workos.js";
10import { processCommandFlags } from "../flags/flagProcessor.js";
11import { toolPermissionManager } from "../permissions/permissionManager.js";
12import {
13 getService,
14 initializeServices,
15 SERVICE_NAMES,
16} from "../services/index.js";
17import {
18 AuthServiceState,
19 ConfigServiceState,
20 ModelServiceState,
21} from "../services/types.js";
22import { createSession, updateSessionHistory } 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
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
88 // Log configuration information
89 const organizationId = authState.organizationId || "personal";
90 const assistantName = config.name;
91 const assistantSlug = getAssistantSlug(authState.authConfig);
92 const modelProvider = model.provider;
93 const modelName = model.model;
94
95 console.log(chalk.blue(`\nConfiguration:`));
96 console.log(chalk.dim(` Organization: ${organizationId}`));
97 console.log(
98 chalk.dim(
99 ` Assistant: ${assistantName}${
100 assistantSlug ? ` (${assistantSlug})` : ""
101 }`,
102 ),
103 );
104 console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
105 if (options.config) {
106 console.log(chalk.dim(` Config file: ${options.config}`));
107 }
108
109 // Initialize session with system message
110 const systemMessage = await constructSystemMessage(
111 options.rule,
112 undefined,
113 true,
114 );
115
116 const initialHistory: ChatHistoryItem[] = [];
117 if (systemMessage) {
118 initialHistory.push({
119 message: { role: "system" as const, content: systemMessage },
120 contextItems: [],
121 });
122 }
123
124 const session = createSession(initialHistory);
125
126 // Initialize server state
127 const state: ServerState = {
128 session,
129 config,
130 model,
131 isProcessing: false,
132 lastActivity: Date.now(),
133 messageQueue: [],
134 currentAbortController: null,
135 shouldInterrupt: false,
136 serverRunning: true,
137 pendingPermission: null,
138 };
139
140 // Record session start
141 telemetryService.recordSessionStart();
142 telemetryService.startActiveTime();
143
144 const app = express();
145 app.use(express.json());
146
147 // GET /state - Return the current state
148 app.get("/state", (_req: Request, res: Response) => {
149 state.lastActivity = Date.now();
150 res.json({
151 chatHistory: convertFromUnifiedHistory(state.session.history), // Convert back to legacy format for API
152 isProcessing: state.isProcessing,
153 messageQueueLength: state.messageQueue.length,
154 pendingPermission: state.pendingPermission,
155 });
156 });
157
158 // POST /message - Queue a message and potentially interrupt
159 app.post("/message", async (req: Request, res: Response) => {
160 state.lastActivity = Date.now();
161
162 const { message } = req.body;
163 if (!message) {
164 return res.status(400).json({ error: "Message field is required" });
165 }
166
167 // Queue the message
168 state.messageQueue.push(message);
169
170 // If currently processing, set interrupt flag
171 if (state.isProcessing && state.currentAbortController) {
172 state.shouldInterrupt = true;
173 }
174
175 res.json({
176 queued: true,
177 position: state.messageQueue.length,
178 willInterrupt: state.shouldInterrupt,
179 });
180
181 // Process messages if not already processing
182 if (!state.isProcessing) {
183 processMessages(state, llmApi);
184 }
185 });
186
187 // POST /permission - Approve or reject pending tool permission
188 app.post("/permission", async (req: Request, res: Response) => {
189 state.lastActivity = Date.now();
190
191 const { requestId, approved } = req.body;
192
193 if (!state.pendingPermission) {
194 return res.status(400).json({ error: "No pending permission request" });
195 }
196
197 if (state.pendingPermission.requestId !== requestId) {
198 return res.status(400).json({ error: "Invalid request ID" });
199 }
200
201 // Remove the permission request message if it exists
202 // Permission requests are handled separately in unified format
203
204 // Send the permission response to the toolPermissionManager
205 if (approved) {
206 toolPermissionManager.approveRequest(requestId);
207 } else {
208 toolPermissionManager.rejectRequest(requestId);
209 }
210
211 // Clear pending permission state
212 state.pendingPermission = null;
213
214 res.json({
215 success: true,
216 approved,
217 });
218 });
219
220 // GET /diff - Return git diff against main branch
221 app.get("/diff", async (_req: Request, res: Response) => {
222 state.lastActivity = Date.now();
223
224 try {
225 // First check if we're in a git repository
226 await execAsync("git rev-parse --git-dir");
227
228 // Get the diff against main branch
229 const { stdout } = await execAsync("git diff main");
230
231 res.json({
232 diff: stdout,
233 });
234 } catch (error: any) {
235 // Git diff returns exit code 1 when there are differences, which is normal
236 if (error.code === 1 && error.stdout) {
237 res.json({
238 diff: error.stdout,
239 });
240 } else if (error.code === 128) {
241 // Handle case where we're not in a git repo or main branch doesn't exist
242 res.status(404).json({
243 error: "Not in a git repository or main branch doesn't exist",
244 diff: "",
245 });
246 } else {
247 logger.error(`Git diff error: ${formatError(error)}`);
248 res.status(500).json({
249 error: `Failed to get git diff: ${formatError(error)}`,
250 diff: "",
251 });
252 }
253 }
254 });
255
256 // Track intervals for cleanup
257 let inactivityChecker: NodeJS.Timeout | null = null;
258
259 // POST /exit - Gracefully shut down the server
260 app.post("/exit", async (_req: Request, res: Response) => {
261 console.log(
262 chalk.yellow("\nReceived exit request, shutting down server..."),
263 );
264
265 // Respond immediately before shutting down
266 res.json({
267 message: "Server shutting down",
268 success: true,
269 });
270
271 // Set server running flag to false to stop processing
272 state.serverRunning = false;
273
274 // Abort any current processing
275 if (state.currentAbortController) {
276 state.currentAbortController.abort();
277 }
278
279 // Clear the message queue
280 state.messageQueue = [];
281
282 // Clean up intervals
283 if (inactivityChecker) {
284 clearInterval(inactivityChecker);
285 inactivityChecker = null;
286 }
287
288 // Give a moment for the response to be sent
289 setTimeout(() => {
290 server.close(() => {
291 telemetryService.stopActiveTime();
292 process.exit(0);
293 });
294 }, 100);
295 });
296
297 const server = app.listen(port, () => {
298 console.log(chalk.green(`Server started on http://localhost:${port}`));
299 console.log(chalk.dim("Endpoints:"));
300 console.log(chalk.dim(" GET /state - Get current agent state"));
301 console.log(
302 chalk.dim(
303 " POST /message - Send a message (body: { message: string })",
304 ),
305 );
306 console.log(
307 chalk.dim(
308 " POST /permission - Approve/reject tool (body: { requestId, approved })",
309 ),
310 );
311 console.log(
312 chalk.dim(" GET /diff - Get git diff against main branch"),
313 );
314 console.log(
315 chalk.dim(" POST /exit - Gracefully shut down the server"),
316 );
317 console.log(
318 chalk.dim(
319 `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
320 ),
321 );
322
323 // If initial prompt provided, queue it for processing
324 if (actualPrompt) {
325 console.log(chalk.dim("\nProcessing initial prompt..."));
326 state.messageQueue.push(actualPrompt);
327 processMessages(state, llmApi);
328 }
329 });
330
331 // Process messages from the queue
332 async function processMessages(state: ServerState, llmApi: any) {
333 while (state.messageQueue.length > 0 && state.serverRunning) {
334 const userMessage = state.messageQueue.shift()!;
335 state.isProcessing = true;
336 state.shouldInterrupt = false;
337 state.lastActivity = Date.now();
338
339 // Add user message to history
340 state.session.history.push({
341 message: { role: "user", content: userMessage },
342 contextItems: [],
343 });
344
345 try {
346 // Create new abort controller for this response
347 state.currentAbortController = new AbortController();
348
349 // Stream the response with interruption support
350 await streamChatResponseWithInterruption(
351 state,
352 llmApi,
353 state.currentAbortController,
354 () => state.shouldInterrupt,
355 );
356
357 // Save session after successful response
358 updateSessionHistory(state.session.history);
359
360 state.lastActivity = Date.now();
361 } catch (e: any) {
362 if (e.name === "AbortError") {
363 logger.debug("Response interrupted");
364 // Remove the partial assistant message if it exists
365 const lastMessage =
366 state.session.history[state.session.history.length - 1];
367 if (
368 lastMessage &&
369 lastMessage.message.role === "assistant" &&
370 !lastMessage.message.content
371 ) {
372 state.session.history.pop();
373 }
374 } else {
375 logger.error(`Error: ${formatError(e)}`);
376 // Add error message to chat history and display messages
377 const errorMessage = `Error: ${formatError(e)}`;
378 state.session.history.push({
379 message: { role: "assistant", content: errorMessage },
380 contextItems: [],
381 });
382 }
383 } finally {
384 state.currentAbortController = null;
385 state.isProcessing = false;
386 }
387 }
388 }
389
390 // Check for inactivity and shutdown
391 inactivityChecker = setInterval(() => {
392 if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
393 console.log(
394 chalk.yellow(
395 `\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
396 ),
397 );
398 state.serverRunning = false;
399 server.close(() => {
400 telemetryService.stopActiveTime();
401 process.exit(0);
402 });
403 if (inactivityChecker) {
404 clearInterval(inactivityChecker);
405 inactivityChecker = null;
406 }
407 }
408 }, 1000);
409
410 // Handle graceful shutdown
411 process.on("SIGINT", () => {
412 console.log(chalk.yellow("\nShutting down server..."));
413 state.serverRunning = false;
414 if (inactivityChecker) {
415 clearInterval(inactivityChecker);
416 inactivityChecker = null;
417 }
418 server.close(() => {
419 telemetryService.stopActiveTime();
420 process.exit(0);
421 });
422 });
423}
424
425// Function moved to serve.helpers.ts - remove implementation
426// async function streamChatResponseWithInterruption - moved to helpers {
427// Implementation moved to serve.helpers.ts