Elffuss BraidHub

kikocis/continue public

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